From a5225ce2d7205a3be54acde0f066c2e09db6fc93 Mon Sep 17 00:00:00 2001 From: nathan boileau Date: Tue, 11 Oct 2022 12:22:11 +0200 Subject: [PATCH] Resolution tt pb --- node_modules/.bin/loose-envify | 12 - node_modules/.bin/loose-envify.cmd | 17 - node_modules/.bin/loose-envify.ps1 | 28 - node_modules/.package-lock.json | 97 - node_modules/@remix-run/router/CHANGELOG.md | 29 - node_modules/@remix-run/router/LICENSE.md | 22 - node_modules/@remix-run/router/README.md | 107 - .../@remix-run/router/dist/history.d.ts | 226 - .../@remix-run/router/dist/index.d.ts | 8 - .../@remix-run/router/dist/router.cjs.js | 3248 -- .../@remix-run/router/dist/router.cjs.js.map | 1 - .../@remix-run/router/dist/router.d.ts | 357 - node_modules/@remix-run/router/dist/router.js | 3177 -- .../@remix-run/router/dist/router.js.map | 1 - .../@remix-run/router/dist/utils.d.ts | 359 - node_modules/@remix-run/router/history.ts | 623 - node_modules/@remix-run/router/index.ts | 82 - node_modules/@remix-run/router/package.json | 32 - node_modules/@remix-run/router/router.ts | 2854 -- node_modules/@remix-run/router/utils.ts | 1204 - node_modules/js-tokens/CHANGELOG.md | 151 - node_modules/js-tokens/LICENSE | 21 - node_modules/js-tokens/README.md | 240 - node_modules/js-tokens/index.js | 23 - node_modules/js-tokens/package.json | 30 - node_modules/loose-envify/LICENSE | 21 - node_modules/loose-envify/README.md | 45 - node_modules/loose-envify/cli.js | 16 - node_modules/loose-envify/custom.js | 4 - node_modules/loose-envify/index.js | 3 - node_modules/loose-envify/loose-envify.js | 36 - node_modules/loose-envify/package.json | 36 - node_modules/loose-envify/replace.js | 65 - node_modules/react-dom/LICENSE | 21 - node_modules/react-dom/README.md | 60 - ...t-dom-server-legacy.browser.development.js | 7018 ---- ...om-server-legacy.browser.production.min.js | 93 - ...eact-dom-server-legacy.node.development.js | 7078 ---- ...t-dom-server-legacy.node.production.min.js | 101 - .../react-dom-server.browser.development.js | 7003 ---- ...react-dom-server.browser.production.min.js | 96 - .../cjs/react-dom-server.node.development.js | 7059 ---- .../react-dom-server.node.production.min.js | 102 - .../cjs/react-dom-test-utils.development.js | 1741 - .../react-dom-test-utils.production.min.js | 40 - .../react-dom/cjs/react-dom.development.js | 29868 --------------- .../react-dom/cjs/react-dom.production.min.js | 323 - .../react-dom/cjs/react-dom.profiling.min.js | 367 - node_modules/react-dom/client.js | 25 - node_modules/react-dom/index.js | 38 - node_modules/react-dom/package.json | 62 - node_modules/react-dom/profiling.js | 38 - node_modules/react-dom/server.browser.js | 17 - node_modules/react-dom/server.js | 3 - node_modules/react-dom/server.node.js | 17 - node_modules/react-dom/test-utils.js | 7 - ...t-dom-server-legacy.browser.development.js | 7015 ---- ...om-server-legacy.browser.production.min.js | 75 - .../react-dom-server.browser.development.js | 7000 ---- ...react-dom-server.browser.production.min.js | 76 - .../umd/react-dom-test-utils.development.js | 1737 - .../react-dom-test-utils.production.min.js | 33 - .../react-dom/umd/react-dom.development.js | 29869 ---------------- .../react-dom/umd/react-dom.production.min.js | 267 - .../react-dom/umd/react-dom.profiling.min.js | 285 - node_modules/react-router-dom/CHANGELOG.md | 53 - node_modules/react-router-dom/LICENSE.md | 22 - node_modules/react-router-dom/README.md | 5 - node_modules/react-router-dom/dist/dom.d.ts | 75 - node_modules/react-router-dom/dist/index.d.ts | 211 - node_modules/react-router-dom/dist/index.js | 894 - .../react-router-dom/dist/index.js.map | 1 - node_modules/react-router-dom/dist/main.js | 19 - .../dist/react-router-dom.development.js | 838 - .../dist/react-router-dom.development.js.map | 1 - .../dist/react-router-dom.production.min.js | 12 - .../react-router-dom.production.min.js.map | 1 - .../react-router-dom/dist/server.d.ts | 26 - node_modules/react-router-dom/dist/server.js | 223 - node_modules/react-router-dom/dist/server.mjs | 196 - .../dist/umd/react-router-dom.development.js | 1139 - .../umd/react-router-dom.development.js.map | 1 - .../umd/react-router-dom.production.min.js | 12 - .../react-router-dom.production.min.js.map | 1 - node_modules/react-router-dom/package.json | 49 - node_modules/react-router-dom/server.d.ts | 26 - node_modules/react-router-dom/server.js | 223 - node_modules/react-router-dom/server.mjs | 196 - node_modules/react-router/CHANGELOG.md | 44 - node_modules/react-router/LICENSE.md | 22 - node_modules/react-router/README.md | 16 - node_modules/react-router/dist/index.d.ts | 21 - node_modules/react-router/dist/index.js | 1374 - node_modules/react-router/dist/index.js.map | 1 - .../react-router/dist/lib/components.d.ts | 146 - .../react-router/dist/lib/context.d.ts | 87 - node_modules/react-router/dist/lib/hooks.d.ts | 171 - .../use-sync-external-store-shim/index.d.ts | 7 - .../useSyncExternalStoreShimClient.d.ts | 7 - .../useSyncExternalStoreShimServer.d.ts | 9 - node_modules/react-router/dist/main.js | 19 - .../dist/react-router.development.js | 1330 - .../dist/react-router.development.js.map | 1 - .../dist/react-router.production.min.js | 12 - .../dist/react-router.production.min.js.map | 1 - .../dist/umd/react-router.development.js | 1486 - .../dist/umd/react-router.development.js.map | 1 - .../dist/umd/react-router.production.min.js | 12 - .../umd/react-router.production.min.js.map | 1 - node_modules/react-router/package.json | 43 - node_modules/react/LICENSE | 21 - node_modules/react/README.md | 37 - .../cjs/react-jsx-dev-runtime.development.js | 1296 - .../react-jsx-dev-runtime.production.min.js | 10 - .../react-jsx-dev-runtime.profiling.min.js | 10 - .../cjs/react-jsx-runtime.development.js | 1314 - .../cjs/react-jsx-runtime.production.min.js | 11 - .../cjs/react-jsx-runtime.profiling.min.js | 11 - node_modules/react/cjs/react.development.js | 2739 -- .../react/cjs/react.production.min.js | 26 - .../cjs/react.shared-subset.development.js | 20 - .../cjs/react.shared-subset.production.min.js | 10 - node_modules/react/index.js | 7 - node_modules/react/jsx-dev-runtime.js | 7 - node_modules/react/jsx-runtime.js | 7 - node_modules/react/package.json | 47 - node_modules/react/react.shared-subset.js | 7 - node_modules/react/umd/react.development.js | 3342 -- .../react/umd/react.production.min.js | 31 - node_modules/react/umd/react.profiling.min.js | 31 - node_modules/scheduler/LICENSE | 21 - node_modules/scheduler/README.md | 9 - .../scheduler-unstable_mock.development.js | 700 - .../scheduler-unstable_mock.production.min.js | 20 - ...cheduler-unstable_post_task.development.js | 207 - ...duler-unstable_post_task.production.min.js | 14 - .../scheduler/cjs/scheduler.development.js | 634 - .../scheduler/cjs/scheduler.production.min.js | 19 - node_modules/scheduler/index.js | 7 - node_modules/scheduler/package.json | 36 - .../scheduler-unstable_mock.development.js | 699 - .../scheduler-unstable_mock.production.min.js | 19 - .../scheduler/umd/scheduler.development.js | 152 - .../scheduler/umd/scheduler.production.min.js | 146 - .../scheduler/umd/scheduler.profiling.min.js | 146 - node_modules/scheduler/unstable_mock.js | 7 - node_modules/scheduler/unstable_post_task.js | 7 - package-lock.json | 169 - package.json | 5 - website/package-lock.json | 830 +- website/package.json | 3 +- website/public/favicon.ico | Bin 0 -> 3870 bytes website/public/index.html | 8 +- website/public/logo192.png | Bin 0 -> 5347 bytes website/public/logo512.png | Bin 0 -> 9664 bytes website/public/robots.txt | 3 + website/src/App.js | 10 +- website/src/index.js | 6 +- website/src/{components => pages}/Main.js | 14 +- website/src/pages/Palindrome.js | 4 +- 160 files changed, 452 insertions(+), 142171 deletions(-) delete mode 100644 node_modules/.bin/loose-envify delete mode 100644 node_modules/.bin/loose-envify.cmd delete mode 100644 node_modules/.bin/loose-envify.ps1 delete mode 100644 node_modules/.package-lock.json delete mode 100644 node_modules/@remix-run/router/CHANGELOG.md delete mode 100644 node_modules/@remix-run/router/LICENSE.md delete mode 100644 node_modules/@remix-run/router/README.md delete mode 100644 node_modules/@remix-run/router/dist/history.d.ts delete mode 100644 node_modules/@remix-run/router/dist/index.d.ts delete mode 100644 node_modules/@remix-run/router/dist/router.cjs.js delete mode 100644 node_modules/@remix-run/router/dist/router.cjs.js.map delete mode 100644 node_modules/@remix-run/router/dist/router.d.ts delete mode 100644 node_modules/@remix-run/router/dist/router.js delete mode 100644 node_modules/@remix-run/router/dist/router.js.map delete mode 100644 node_modules/@remix-run/router/dist/utils.d.ts delete mode 100644 node_modules/@remix-run/router/history.ts delete mode 100644 node_modules/@remix-run/router/index.ts delete mode 100644 node_modules/@remix-run/router/package.json delete mode 100644 node_modules/@remix-run/router/router.ts delete mode 100644 node_modules/@remix-run/router/utils.ts delete mode 100644 node_modules/js-tokens/CHANGELOG.md delete mode 100644 node_modules/js-tokens/LICENSE delete mode 100644 node_modules/js-tokens/README.md delete mode 100644 node_modules/js-tokens/index.js delete mode 100644 node_modules/js-tokens/package.json delete mode 100644 node_modules/loose-envify/LICENSE delete mode 100644 node_modules/loose-envify/README.md delete mode 100644 node_modules/loose-envify/cli.js delete mode 100644 node_modules/loose-envify/custom.js delete mode 100644 node_modules/loose-envify/index.js delete mode 100644 node_modules/loose-envify/loose-envify.js delete mode 100644 node_modules/loose-envify/package.json delete mode 100644 node_modules/loose-envify/replace.js delete mode 100644 node_modules/react-dom/LICENSE delete mode 100644 node_modules/react-dom/README.md delete mode 100644 node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js delete mode 100644 node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js delete mode 100644 node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js delete mode 100644 node_modules/react-dom/cjs/react-dom-server-legacy.node.production.min.js delete mode 100644 node_modules/react-dom/cjs/react-dom-server.browser.development.js delete mode 100644 node_modules/react-dom/cjs/react-dom-server.browser.production.min.js delete mode 100644 node_modules/react-dom/cjs/react-dom-server.node.development.js delete mode 100644 node_modules/react-dom/cjs/react-dom-server.node.production.min.js delete mode 100644 node_modules/react-dom/cjs/react-dom-test-utils.development.js delete mode 100644 node_modules/react-dom/cjs/react-dom-test-utils.production.min.js delete mode 100644 node_modules/react-dom/cjs/react-dom.development.js delete mode 100644 node_modules/react-dom/cjs/react-dom.production.min.js delete mode 100644 node_modules/react-dom/cjs/react-dom.profiling.min.js delete mode 100644 node_modules/react-dom/client.js delete mode 100644 node_modules/react-dom/index.js delete mode 100644 node_modules/react-dom/package.json delete mode 100644 node_modules/react-dom/profiling.js delete mode 100644 node_modules/react-dom/server.browser.js delete mode 100644 node_modules/react-dom/server.js delete mode 100644 node_modules/react-dom/server.node.js delete mode 100644 node_modules/react-dom/test-utils.js delete mode 100644 node_modules/react-dom/umd/react-dom-server-legacy.browser.development.js delete mode 100644 node_modules/react-dom/umd/react-dom-server-legacy.browser.production.min.js delete mode 100644 node_modules/react-dom/umd/react-dom-server.browser.development.js delete mode 100644 node_modules/react-dom/umd/react-dom-server.browser.production.min.js delete mode 100644 node_modules/react-dom/umd/react-dom-test-utils.development.js delete mode 100644 node_modules/react-dom/umd/react-dom-test-utils.production.min.js delete mode 100644 node_modules/react-dom/umd/react-dom.development.js delete mode 100644 node_modules/react-dom/umd/react-dom.production.min.js delete mode 100644 node_modules/react-dom/umd/react-dom.profiling.min.js delete mode 100644 node_modules/react-router-dom/CHANGELOG.md delete mode 100644 node_modules/react-router-dom/LICENSE.md delete mode 100644 node_modules/react-router-dom/README.md delete mode 100644 node_modules/react-router-dom/dist/dom.d.ts delete mode 100644 node_modules/react-router-dom/dist/index.d.ts delete mode 100644 node_modules/react-router-dom/dist/index.js delete mode 100644 node_modules/react-router-dom/dist/index.js.map delete mode 100644 node_modules/react-router-dom/dist/main.js delete mode 100644 node_modules/react-router-dom/dist/react-router-dom.development.js delete mode 100644 node_modules/react-router-dom/dist/react-router-dom.development.js.map delete mode 100644 node_modules/react-router-dom/dist/react-router-dom.production.min.js delete mode 100644 node_modules/react-router-dom/dist/react-router-dom.production.min.js.map delete mode 100644 node_modules/react-router-dom/dist/server.d.ts delete mode 100644 node_modules/react-router-dom/dist/server.js delete mode 100644 node_modules/react-router-dom/dist/server.mjs delete mode 100644 node_modules/react-router-dom/dist/umd/react-router-dom.development.js delete mode 100644 node_modules/react-router-dom/dist/umd/react-router-dom.development.js.map delete mode 100644 node_modules/react-router-dom/dist/umd/react-router-dom.production.min.js delete mode 100644 node_modules/react-router-dom/dist/umd/react-router-dom.production.min.js.map delete mode 100644 node_modules/react-router-dom/package.json delete mode 100644 node_modules/react-router-dom/server.d.ts delete mode 100644 node_modules/react-router-dom/server.js delete mode 100644 node_modules/react-router-dom/server.mjs delete mode 100644 node_modules/react-router/CHANGELOG.md delete mode 100644 node_modules/react-router/LICENSE.md delete mode 100644 node_modules/react-router/README.md delete mode 100644 node_modules/react-router/dist/index.d.ts delete mode 100644 node_modules/react-router/dist/index.js delete mode 100644 node_modules/react-router/dist/index.js.map delete mode 100644 node_modules/react-router/dist/lib/components.d.ts delete mode 100644 node_modules/react-router/dist/lib/context.d.ts delete mode 100644 node_modules/react-router/dist/lib/hooks.d.ts delete mode 100644 node_modules/react-router/dist/lib/use-sync-external-store-shim/index.d.ts delete mode 100644 node_modules/react-router/dist/lib/use-sync-external-store-shim/useSyncExternalStoreShimClient.d.ts delete mode 100644 node_modules/react-router/dist/lib/use-sync-external-store-shim/useSyncExternalStoreShimServer.d.ts delete mode 100644 node_modules/react-router/dist/main.js delete mode 100644 node_modules/react-router/dist/react-router.development.js delete mode 100644 node_modules/react-router/dist/react-router.development.js.map delete mode 100644 node_modules/react-router/dist/react-router.production.min.js delete mode 100644 node_modules/react-router/dist/react-router.production.min.js.map delete mode 100644 node_modules/react-router/dist/umd/react-router.development.js delete mode 100644 node_modules/react-router/dist/umd/react-router.development.js.map delete mode 100644 node_modules/react-router/dist/umd/react-router.production.min.js delete mode 100644 node_modules/react-router/dist/umd/react-router.production.min.js.map delete mode 100644 node_modules/react-router/package.json delete mode 100644 node_modules/react/LICENSE delete mode 100644 node_modules/react/README.md delete mode 100644 node_modules/react/cjs/react-jsx-dev-runtime.development.js delete mode 100644 node_modules/react/cjs/react-jsx-dev-runtime.production.min.js delete mode 100644 node_modules/react/cjs/react-jsx-dev-runtime.profiling.min.js delete mode 100644 node_modules/react/cjs/react-jsx-runtime.development.js delete mode 100644 node_modules/react/cjs/react-jsx-runtime.production.min.js delete mode 100644 node_modules/react/cjs/react-jsx-runtime.profiling.min.js delete mode 100644 node_modules/react/cjs/react.development.js delete mode 100644 node_modules/react/cjs/react.production.min.js delete mode 100644 node_modules/react/cjs/react.shared-subset.development.js delete mode 100644 node_modules/react/cjs/react.shared-subset.production.min.js delete mode 100644 node_modules/react/index.js delete mode 100644 node_modules/react/jsx-dev-runtime.js delete mode 100644 node_modules/react/jsx-runtime.js delete mode 100644 node_modules/react/package.json delete mode 100644 node_modules/react/react.shared-subset.js delete mode 100644 node_modules/react/umd/react.development.js delete mode 100644 node_modules/react/umd/react.production.min.js delete mode 100644 node_modules/react/umd/react.profiling.min.js delete mode 100644 node_modules/scheduler/LICENSE delete mode 100644 node_modules/scheduler/README.md delete mode 100644 node_modules/scheduler/cjs/scheduler-unstable_mock.development.js delete mode 100644 node_modules/scheduler/cjs/scheduler-unstable_mock.production.min.js delete mode 100644 node_modules/scheduler/cjs/scheduler-unstable_post_task.development.js delete mode 100644 node_modules/scheduler/cjs/scheduler-unstable_post_task.production.min.js delete mode 100644 node_modules/scheduler/cjs/scheduler.development.js delete mode 100644 node_modules/scheduler/cjs/scheduler.production.min.js delete mode 100644 node_modules/scheduler/index.js delete mode 100644 node_modules/scheduler/package.json delete mode 100644 node_modules/scheduler/umd/scheduler-unstable_mock.development.js delete mode 100644 node_modules/scheduler/umd/scheduler-unstable_mock.production.min.js delete mode 100644 node_modules/scheduler/umd/scheduler.development.js delete mode 100644 node_modules/scheduler/umd/scheduler.production.min.js delete mode 100644 node_modules/scheduler/umd/scheduler.profiling.min.js delete mode 100644 node_modules/scheduler/unstable_mock.js delete mode 100644 node_modules/scheduler/unstable_post_task.js delete mode 100644 package-lock.json delete mode 100644 package.json create mode 100644 website/public/favicon.ico create mode 100644 website/public/logo192.png create mode 100644 website/public/logo512.png create mode 100644 website/public/robots.txt rename website/src/{components => pages}/Main.js (76%) diff --git a/node_modules/.bin/loose-envify b/node_modules/.bin/loose-envify deleted file mode 100644 index 60598cb0..00000000 --- a/node_modules/.bin/loose-envify +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; -esac - -if [ -x "$basedir/node" ]; then - exec "$basedir/node" "$basedir/../loose-envify/cli.js" "$@" -else - exec node "$basedir/../loose-envify/cli.js" "$@" -fi diff --git a/node_modules/.bin/loose-envify.cmd b/node_modules/.bin/loose-envify.cmd deleted file mode 100644 index 599576f9..00000000 --- a/node_modules/.bin/loose-envify.cmd +++ /dev/null @@ -1,17 +0,0 @@ -@ECHO off -GOTO start -:find_dp0 -SET dp0=%~dp0 -EXIT /b -:start -SETLOCAL -CALL :find_dp0 - -IF EXIST "%dp0%\node.exe" ( - SET "_prog=%dp0%\node.exe" -) ELSE ( - SET "_prog=node" - SET PATHEXT=%PATHEXT:;.JS;=;% -) - -endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\loose-envify\cli.js" %* diff --git a/node_modules/.bin/loose-envify.ps1 b/node_modules/.bin/loose-envify.ps1 deleted file mode 100644 index eb866fca..00000000 --- a/node_modules/.bin/loose-envify.ps1 +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env pwsh -$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent - -$exe="" -if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { - # Fix case when both the Windows and Linux builds of Node - # are installed in the same directory - $exe=".exe" -} -$ret=0 -if (Test-Path "$basedir/node$exe") { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "$basedir/node$exe" "$basedir/../loose-envify/cli.js" $args - } else { - & "$basedir/node$exe" "$basedir/../loose-envify/cli.js" $args - } - $ret=$LASTEXITCODE -} else { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "node$exe" "$basedir/../loose-envify/cli.js" $args - } else { - & "node$exe" "$basedir/../loose-envify/cli.js" $args - } - $ret=$LASTEXITCODE -} -exit $ret diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json deleted file mode 100644 index 9c77e7f2..00000000 --- a/node_modules/.package-lock.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "name": "Scripted", - "lockfileVersion": 2, - "requires": true, - "packages": { - "node_modules/@remix-run/router": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.0.2.tgz", - "integrity": "sha512-GRSOFhJzjGN+d4sKHTMSvNeUPoZiDHWmRnXfzaxrqe7dE/Nzlc8BiMSJdLDESZlndM7jIUrZ/F4yWqVYlI0rwQ==", - "engines": { - "node": ">=14" - } - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "peer": true - }, - "node_modules/loose-envify": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", - "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", - "peer": true, - "dependencies": { - "js-tokens": "^3.0.0 || ^4.0.0" - }, - "bin": { - "loose-envify": "cli.js" - } - }, - "node_modules/react": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react/-/react-18.2.0.tgz", - "integrity": "sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==", - "peer": true, - "dependencies": { - "loose-envify": "^1.1.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/react-dom": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.2.0.tgz", - "integrity": "sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==", - "peer": true, - "dependencies": { - "loose-envify": "^1.1.0", - "scheduler": "^0.23.0" - }, - "peerDependencies": { - "react": "^18.2.0" - } - }, - "node_modules/react-router": { - "version": "6.4.2", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.4.2.tgz", - "integrity": "sha512-Rb0BAX9KHhVzT1OKhMvCDMw776aTYM0DtkxqUBP8dNBom3mPXlfNs76JNGK8wKJ1IZEY1+WGj+cvZxHVk/GiKw==", - "dependencies": { - "@remix-run/router": "1.0.2" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "react": ">=16.8" - } - }, - "node_modules/react-router-dom": { - "version": "6.4.2", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.4.2.tgz", - "integrity": "sha512-yM1kjoTkpfjgczPrcyWrp+OuQMyB1WleICiiGfstnQYo/S8hPEEnVjr/RdmlH6yKK4Tnj1UGXFSa7uwAtmDoLQ==", - "dependencies": { - "@remix-run/router": "1.0.2", - "react-router": "6.4.2" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "react": ">=16.8", - "react-dom": ">=16.8" - } - }, - "node_modules/scheduler": { - "version": "0.23.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.0.tgz", - "integrity": "sha512-CtuThmgHNg7zIZWAXi3AsyIzA3n4xx7aNyjwC2VJldO2LMVDhFK+63xGqq6CsJH4rTAt6/M+N4GhZiDYPx9eUw==", - "peer": true, - "dependencies": { - "loose-envify": "^1.1.0" - } - } - } -} diff --git a/node_modules/@remix-run/router/CHANGELOG.md b/node_modules/@remix-run/router/CHANGELOG.md deleted file mode 100644 index 64fbd6a3..00000000 --- a/node_modules/@remix-run/router/CHANGELOG.md +++ /dev/null @@ -1,29 +0,0 @@ -# `@remix-run/router` - -## 1.0.2 - -### Patch Changes - -- Reset `actionData` after a successful action redirect ([#9334](https://github.com/remix-run/react-router/pull/9334)) -- Update `matchPath` to avoid false positives on dash-separated segments ([#9300](https://github.com/remix-run/react-router/pull/9300)) -- If an index route has children, it will result in a runtime error. We have strengthened our `RouteObject`/`RouteProps` types to surface the error in TypeScript. ([#9366](https://github.com/remix-run/react-router/pull/9366)) - -## 1.0.1 - -### Patch Changes - -- Preserve state from `initialEntries` ([#9288](https://github.com/remix-run/react-router/pull/9288)) -- Preserve `?index` for fetcher get submissions to index routes ([#9312](https://github.com/remix-run/react-router/pull/9312)) - -## 1.0.0 - -This is the first stable release of `@remix-run/router`, which provides all the underlying routing and data loading/mutation logic for `react-router`. You should _not_ be using this package directly unless you are authoring a routing library similar to `react-router`. - -For an overview of the features provided by `react-router`, we recommend you go check out the [docs][rr-docs], especially the [feature overview][rr-feature-overview] and the [tutorial][rr-tutorial]. - -For an overview of the features provided by `@remix-run/router`, please check out the [`README`][remix-router-readme]. - -[rr-docs]: https://reactrouter.com/ -[rr-feature-overview]: https://reactrouter.com/en/v6.4.0/start/overview -[rr-tutorial]: https://reactrouter.com/en/v6.4.0/start/tutorial -[remix-router-readme]: https://github.com/remix-run/react-router/blob/main/packages/router/README.md diff --git a/node_modules/@remix-run/router/LICENSE.md b/node_modules/@remix-run/router/LICENSE.md deleted file mode 100644 index 47c96cbd..00000000 --- a/node_modules/@remix-run/router/LICENSE.md +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) React Training 2015-2019 -Copyright (c) Remix Software 2020-2022 - -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. diff --git a/node_modules/@remix-run/router/README.md b/node_modules/@remix-run/router/README.md deleted file mode 100644 index e0589a0d..00000000 --- a/node_modules/@remix-run/router/README.md +++ /dev/null @@ -1,107 +0,0 @@ -# Remix Router - -The `@remix-run/router` package is a framework-agnostic routing package (sometimes referred to as a browser-emulator) that serves as the heart of [React Router][react-router] and [Remix][remix] and provides all the core functionality for routing coupled with data loading and data mutations. It comes with built-in handling of errors, race-conditions, interruptions, cancellations, lazy-loading data, and much, much more. - -If you're using React Router, you should never `import` anything directly from the `@remix-run/router` or `react-router` packages, but you should have everything you need in either `react-router-dom` or `react-router-native`. Both of those packages re-export everything from `@remix-run/router` and `react-router`. - -> **Warning** -> -> This router is a low-level package intended to be consumed by UI layer routing libraries. You should very likely not be using this package directly unless you are authoring a routing library such as [`react-router-dom`][react-router-repo] or one of it's other [UI ports][remix-routers-repo]. - -## API - -A Router instance can be created using `createRouter`: - -```js -// Create and initialize a router. "initialize" contains all side effects -// including history listeners and kicking off the initial data fetch -let router = createRouter({ - // Routes array - routes: , - // History instance - history, -}).initialize() -``` - -Internally, the Router represents the state in an object of the following format, which is available through `router.state`. You can also register a subscriber of the signature `(state: RouterState) => void` to execute when the state updates via `router.subscribe()`; - -```ts -interface RouterState { - // False during the initial data load, true once we have our initial data - initialized: boolean; - // The `history` action of the most recently completed navigation - historyAction: Action; - // The current location of the router. During a navigation this reflects - // the "old" location and is updated upon completion of the navigation - location: Location; - // The current set of route matches - matches: DataRouteMatch[]; - // The state of the current navigation - navigation: Navigation; - // The state of any in-progress router.revalidate() calls - revalidation: RevalidationState; - // Data from the loaders for the current matches - loaderData: RouteData; - // Data from the action for the current matches - actionData: RouteData | null; - // Errors thrown from loaders/actions for the current matches - errors: RouteData | null; - // Map of all active fetchers - fetchers: Map; - // Scroll position to restore to for the active Location, false if we - // should not restore, or null if we don't have a saved position - // Note: must be enabled via router.enableScrollRestoration() - restoreScrollPosition: number | false | null; - // Proxied `preventScrollReset` value passed to router.navigate() - preventScrollReset: boolean; -} -``` - -### Navigations - -All navigations are done through the `router.navigate` API which is overloaded to support different types of navigations: - -```js -// Link navigation (pushes onto the history stack by default) -router.navigate("/page"); - -// Link navigation (replacing the history stack) -router.navigate("/page", { replace: true }); - -// Pop navigation (moving backward/forward in the history stack) -router.navigate(-1); - -// Form submission navigation -let formData = new FormData(); -formData.append(key, value); -router.navigate("/page", { - formMethod: "post", - formData, -}); -``` - -### Fetchers - -Fetchers are a mechanism to call loaders/actions without triggering a navigation, and are done through the `router.fetch()` API. All fetch calls require a unique key to identify the fetcher. - -```js -// Execute the loader for /page -router.fetch("key", "/page"); - -// Submit to the action for /page -let formData = new FormData(); -formData.append(key, value); -router.fetch("key", "/page", { - formMethod: "post", - formData, -}); -``` - -### Revalidation - -By default, active loaders will revalidate after any navigation or fetcher mutation. If you need to kick off a revalidation for other use-cases, you can use `router.revalidate()` to re-execute all active loaders. - -[react-router]: https://reactrouter.com -[remix]: https://remix.run -[react-router-repo]: https://github.com/remix-run/react-router -[remix-routers-repo]: https://github.com/brophdawg11/remix-routers diff --git a/node_modules/@remix-run/router/dist/history.d.ts b/node_modules/@remix-run/router/dist/history.d.ts deleted file mode 100644 index 87813168..00000000 --- a/node_modules/@remix-run/router/dist/history.d.ts +++ /dev/null @@ -1,226 +0,0 @@ -/** - * Actions represent the type of change to a location value. - */ -export declare 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; -} -/** - * 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 extends Path { - /** - * A value of arbitrary data associated with this location. - */ - state: any; - /** - * 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; -} -/** - * 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`. May be either a URL or the pieces of a - * URL path. - */ -export declare type To = string | Partial; -/** - * 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 attribute. - * - * @param to - The destination URL - */ - createHref(to: To): string; - /** - * 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; -} -/** - * A user-supplied object that describes a location. Used when providing - * entries to `createMemoryHistory` via its `initialEntries` option. - */ -export declare type InitialEntry = string | Partial; -export declare 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 declare function createMemoryHistory(options?: MemoryHistoryOptions): MemoryHistory; -/** - * 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 declare 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 declare function createBrowserHistory(options?: BrowserHistoryOptions): BrowserHistory; -/** - * 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 declare 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 declare function createHashHistory(options?: HashHistoryOptions): HashHistory; -/** - * Creates a Location object with a unique key from the given Path - */ -export declare function createLocation(current: string | Location, to: To, state?: any, key?: string): Readonly; -/** - * Creates a string URL path from the given pathname, search, and hash components. - */ -export declare function createPath({ pathname, search, hash, }: Partial): string; -/** - * Parses a string URL path into its separate pathname, search, and hash components. - */ -export declare function parsePath(path: string): Partial; -export interface UrlHistory extends History { -} -export declare type UrlHistoryOptions = { - window?: Window; - v5Compat?: boolean; -}; diff --git a/node_modules/@remix-run/router/dist/index.d.ts b/node_modules/@remix-run/router/dist/index.d.ts deleted file mode 100644 index 37d027e6..00000000 --- a/node_modules/@remix-run/router/dist/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { convertRoutesToDataRoutes } from "./utils"; -export type { ActionFunction, ActionFunctionArgs, AgnosticDataIndexRouteObject, AgnosticDataNonIndexRouteObject, AgnosticDataRouteMatch, AgnosticDataRouteObject, AgnosticIndexRouteObject, AgnosticNonIndexRouteObject, AgnosticRouteMatch, AgnosticRouteObject, TrackedPromise, FormEncType, FormMethod, JsonFunction, LoaderFunction, LoaderFunctionArgs, ParamParseKey, Params, PathMatch, PathPattern, RedirectFunction, ShouldRevalidateFunction, Submission, } from "./utils"; -export { AbortedDeferredError, ErrorResponse, defer, generatePath, getToPathname, invariant, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, redirect, resolvePath, resolveTo, stripBasename, warning, } from "./utils"; -export type { BrowserHistory, BrowserHistoryOptions, HashHistory, HashHistoryOptions, History, InitialEntry, Location, MemoryHistory, MemoryHistoryOptions, Path, To, } from "./history"; -export { Action, createBrowserHistory, createPath, createHashHistory, createMemoryHistory, parsePath, } from "./history"; -export * from "./router"; -/** @internal */ -export { convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes }; diff --git a/node_modules/@remix-run/router/dist/router.cjs.js b/node_modules/@remix-run/router/dist/router.cjs.js deleted file mode 100644 index e09e3944..00000000 --- a/node_modules/@remix-run/router/dist/router.cjs.js +++ /dev/null @@ -1,3248 +0,0 @@ -/** - * @remix-run/router v1.0.2 - * - * 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() { - _extends = Object.assign ? Object.assign.bind() : function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - return _extends.apply(this, arguments); -} - -//////////////////////////////////////////////////////////////////////////////// -//#region Types and Constants -//////////////////////////////////////////////////////////////////////////////// - -/** - * Actions represent the type of change to a location value. - */ -exports.Action = void 0; -/** - * The pathname, search, and hash values of a URL. - */ - -(function (Action) { - Action["Pop"] = "POP"; - Action["Push"] = "PUSH"; - Action["Replace"] = "REPLACE"; -})(exports.Action || (exports.Action = {})); - -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. - */ - -/** - * 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 = exports.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$1(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to)); - return location; - } - - let history = { - get index() { - return index; - }, - - get action() { - return action; - }, - - get location() { - return getCurrentLocation(); - }, - - createHref(to) { - return typeof to === "string" ? to : createPath(to); - }, - - push(to, state) { - action = exports.Action.Push; - let nextLocation = createMemoryLocation(to, state); - index += 1; - entries.splice(index, entries.length, nextLocation); - - if (v5Compat && listener) { - listener({ - action, - location: nextLocation - }); - } - }, - - replace(to, state) { - action = exports.Action.Replace; - let nextLocation = createMemoryLocation(to, state); - entries[index] = nextLocation; - - if (v5Compat && listener) { - listener({ - action, - location: nextLocation - }); - } - }, - - go(delta) { - action = exports.Action.Pop; - index = clampIndex(index + delta); - - if (listener) { - listener({ - action, - location: getCurrentLocation() - }); - } - }, - - 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)); - 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$1(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 -//////////////////////////////////////////////////////////////////////////////// - -function warning$1(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) { - return { - usr: location.state, - key: location.key - }; -} -/** - * 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 = exports.Action.Pop; - let listener = null; - - function handlePop() { - action = exports.Action.Pop; - - if (listener) { - listener({ - action, - location: history.location - }); - } - } - - function push(to, state) { - action = exports.Action.Push; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - let historyState = getHistoryState(location); - let url = history.createHref(location); // try...catch because iOS limits us to 100 pushState calls :/ - - try { - globalHistory.pushState(historyState, "", url); - } catch (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 - }); - } - } - - function replace(to, state) { - action = exports.Action.Replace; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - let historyState = getHistoryState(location); - let url = history.createHref(location); - globalHistory.replaceState(historyState, "", url); - - if (v5Compat && listener) { - listener({ - action, - location: location - }); - } - } - - 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); - }, - - push, - replace, - - go(n) { - return globalHistory.go(n); - } - - }; - return history; -} //#endregion - -/** - * Map of routeId -> data returned from a loader/action/error - */ - -let ResultType; -/** - * Successful result from a loader or action - */ - -(function (ResultType) { - ResultType["data"] = "data"; - ResultType["deferred"] = "deferred"; - ResultType["redirect"] = "redirect"; - ResultType["error"] = "error"; -})(ResultType || (ResultType = {})); - -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, parentPath, allIds) { - if (parentPath === void 0) { - parentPath = []; - } - - if (allIds === void 0) { - allIds = new Set(); - } - - return routes.map((route, index) => { - let treePath = [...parentPath, index]; - let id = typeof route.id === "string" ? route.id : treePath.join("-"); - invariant(route.index !== true || !route.children, "Cannot specify children on an index route"); - invariant(!allIds.has(id), "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages"); - allIds.add(id); - - if (isIndexRoute(route)) { - let indexRoute = _extends({}, route, { - id - }); - - return indexRoute; - } else { - let pathOrLayoutRoute = _extends({}, route, { - id, - children: route.children ? convertRoutesToDataRoutes(route.children, treePath, allIds) : undefined - }); - - return pathOrLayoutRoute; - } - }); -} -/** - * Matches the given routes to a location and returns the match data. - * - * @see https://reactrouter.com/docs/en/v6/utils/match-routes - */ - -function matchRoutes(routes, locationArg, basename) { - if (basename === void 0) { - basename = "/"; - } - - let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg; - let pathname = stripBasename(location.pathname || "/", basename); - - if (pathname == null) { - return null; - } - - let branches = flattenRoutes(routes); - rankRouteBranches(branches); - let matches = null; - - for (let i = 0; matches == null && i < branches.length; ++i) { - matches = matchRouteBranch(branches[i], pathname); - } - - return matches; -} - -function flattenRoutes(routes, branches, parentsMeta, parentPath) { - if (branches === void 0) { - branches = []; - } - - if (parentsMeta === void 0) { - parentsMeta = []; - } - - if (parentPath === void 0) { - parentPath = ""; - } - - routes.forEach((route, index) => { - let meta = { - relativePath: route.path || "", - 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 - }); - }); - return branches; -} - -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) { - let { - routesMeta - } = branch; - let matchedParams = {}; - let matchedPathname = "/"; - let matches = []; - - for (let i = 0; i < routesMeta.length; ++i) { - let meta = routesMeta[i]; - let end = i === routesMeta.length - 1; - let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/"; - let match = matchPath({ - path: meta.relativePath, - caseSensitive: meta.caseSensitive, - end - }, remainingPathname); - if (!match) return null; - Object.assign(matchedParams, match.params); - let route = meta.route; - matches.push({ - // TODO: Can this as be avoided? - params: matchedParams, - pathname: joinPaths([matchedPathname, match.pathname]), - pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])), - route - }); - - if (match.pathnameBase !== "/") { - matchedPathname = joinPaths([matchedPathname, match.pathnameBase]); - } - } - - return matches; -} -/** - * Returns a path with params interpolated. - * - * @see https://reactrouter.com/docs/en/v6/utils/generate-path - */ - - -function generatePath(path, params) { - if (params === void 0) { - params = {}; - } - - return path.replace(/:(\w+)/g, (_, key) => { - invariant(params[key] != null, "Missing \":" + key + "\" param"); - return params[key]; - }).replace(/(\/?)\*/, (_, prefix, __, str) => { - const star = "*"; - - if (params[star] == null) { - // If no splat was provided, trim the trailing slash _unless_ it's - // the entire path - return str === "/*" ? "/" : ""; - } // Apply the splat - - - return "" + prefix + params[star]; - }); -} -/** - * A PathPattern is used to match on some portion of a URL pathname. - */ - -/** - * Performs pattern matching on a URL pathname and returns information about - * the match. - * - * @see https://reactrouter.com/docs/en/v6/utils/match-path - */ -function matchPath(pattern, pathname) { - if (typeof pattern === "string") { - pattern = { - path: pattern, - caseSensitive: false, - end: true - }; - } - - let [matcher, paramNames] = 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 = paramNames.reduce((memo, paramName, 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"); - } - - memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || "", paramName); - return memo; - }, {}); - return { - params, - pathname: matchedPathname, - pathnameBase, - pattern - }; -} - -function compilePath(path, caseSensitive, end) { - if (caseSensitive === void 0) { - caseSensitive = false; - } - - if (end === void 0) { - end = true; - } - - warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); - let paramNames = []; - 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) => { - paramNames.push(paramName); - return "([^\\/]+)"; - }); - - if (path.endsWith("*")) { - paramNames.push("*"); - 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, paramNames]; -} - -function safelyDecodeURIComponent(value, paramName) { - try { - return decodeURIComponent(value); - } catch (error) { - warning(false, "The value for the URL param \"" + paramName + "\" will not be decoded because" + (" the string \"" + value + "\" is a malformed URL segment. This is probably") + (" due to a bad percent encoding (" + error + ").")); - return value; - } -} -/** - * @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) || "/"; -} -/** - * @private - */ - -function invariant(value, message) { - if (value === false || value === null || typeof value === "undefined") { - throw new Error(message); - } -} -/** - * @private - */ - -function warning(cond, message) { - if (!cond) { - // eslint-disable-next-line no-console - if (typeof console !== "undefined") console.warn(message); - - try { - // Welcome to debugging React Router! - // - // 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) {} - } -} -/** - * Returns a resolved path object relative to the given pathname. - * - * @see https://reactrouter.com/docs/en/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 = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname; - return { - pathname, - search: normalizeSearch(search), - hash: normalizeHash(hash) - }; -} - -function resolvePathname(relativePath, fromPathname) { - let segments = fromPathname.replace(/\/+$/, "").split("/"); - let relativeSegments = relativePath.split("/"); - relativeSegments.forEach(segment => { - if (segment === "..") { - // 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 and the router will parse it for you."; -} -/** - * @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 `` 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 (isPathRelative || toPathname == null) { - from = locationPathname; - } else { - let routePathnameIndex = routePathnames.length - 1; - - if (toPathname.startsWith("..")) { - let toSegments = toPathname.split("/"); // Each leading .. segment means "go up one route" instead of "go up one - // URL segment". This is a key difference from how works and a - // major reason we call this a "to" value instead of a "href". - - while (toSegments[0] === "..") { - toSegments.shift(); - routePathnameIndex -= 1; - } - - to.pathname = toSegments.join("/"); - } // If there are more ".." segments than parent routes, resolve relative to - // the root / URL. - - - 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; -} -/** - * @private - */ - -const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/"); -/** - * @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. - */ -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 AbortedDeferredError extends Error {} -class DeferredData { - constructor(data) { - this.pendingKeys = new Set(); - this.subscriber = undefined; - 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, _ref) => { - let [key, value] = _ref; - return Object.assign(acc, { - [key]: this.trackPromise(key, value) - }); - }, {}); - } - - trackPromise(key, value) { - if (!(value instanceof Promise)) { - return value; - } - - this.pendingKeys.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, null, 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.pendingKeys.delete(key); - - if (this.done) { - // Nothing left to abort! - this.unlistenAbortSignal(); - } - - const subscriber = this.subscriber; - - if (error) { - Object.defineProperty(promise, "_error", { - get: () => error - }); - subscriber && subscriber(false); - return Promise.reject(error); - } - - Object.defineProperty(promise, "_data", { - get: () => data - }); - subscriber && subscriber(false); - return data; - } - - subscribe(fn) { - this.subscriber = fn; - } - - cancel() { - this.controller.abort(); - this.pendingKeys.forEach((v, k) => this.pendingKeys.delete(k)); - let subscriber = this.subscriber; - subscriber && subscriber(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.pendingKeys.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, _ref2) => { - let [key, value] = _ref2; - return Object.assign(acc, { - [key]: unwrapTrackedPromise(value) - }); - }, {}); - } - -} - -function isTrackedPromise(value) { - return value instanceof Promise && value._tracked === true; -} - -function unwrapTrackedPromise(value) { - if (!isTrackedPromise(value)) { - return value; - } - - if (value._error) { - throw value._error; - } - - return value._data; -} - -function defer(data) { - return new DeferredData(data); -} - -/** - * 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 - })); -}; -/** - * @private - * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies - */ - -class ErrorResponse { - constructor(status, statusText, data) { - this.status = status; - this.statusText = statusText || ""; - this.data = data; - } - -} -/** - * Check if the given error is an ErrorResponse generated from a 4xx/5xx - * Response throw from an action/loader - */ - -function isRouteErrorResponse(e) { - return e instanceof ErrorResponse; -} - -//#region Types and Constants -//////////////////////////////////////////////////////////////////////////////// - -/** - * A Router instance manages all navigation and data loading/mutations - */ - -const IDLE_NAVIGATION = { - state: "idle", - location: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined -}; -const IDLE_FETCHER = { - state: "idle", - data: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined -}; //#endregion -//////////////////////////////////////////////////////////////////////////////// -//#region createRouter -//////////////////////////////////////////////////////////////////////////////// - -/** - * Create a router and listen to history POP navigations - */ - -function createRouter(init) { - invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter"); - let dataRoutes = convertRoutesToDataRoutes(init.routes); // 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 until _after_ - // the initial render, we need to manually trigger a separate updateState to - // send along the restoreScrollPosition - - let initialScrollRestored = false; - let initialMatches = matchRoutes(dataRoutes, init.history.location, init.basename); - let initialErrors = null; - - if (initialMatches == null) { - // If we do not match a user-provided-route, fall back to the root - // to allow the error boundary to take over - let { - matches, - route, - error - } = getNotFoundMatches(dataRoutes); - initialMatches = matches; - initialErrors = { - [route.id]: error - }; - } - - let initialized = !initialMatches.some(m => m.route.loader) || init.hydrationData != null; - let router; - let state = { - historyAction: init.history.action, - location: init.history.location, - matches: initialMatches, - initialized, - navigation: IDLE_NAVIGATION, - restoreScrollPosition: 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() - }; // -- Stateful internal variables to manage navigations -- - // Current navigation in progress (to be committed in completeNavigation) - - let pendingAction = exports.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; // 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) - // - useRevalidate() - // - 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 = []; // 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 from their actions - - let fetchRedirectIds = new Set(); // Most recent href/match for fetcher.load calls for fetchers - - let fetchLoadMatches = new Map(); // 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(); // 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 - } = _ref; - return startNavigation(historyAction, location); - }); // Kick off initial data load if needed. Use Pop to avoid modifying history - - if (!state.initialized) { - startNavigation(exports.Action.Pop, state.location); - } - - return router; - } // Clean up a router and it's side effects - - - function dispose() { - if (unlistenHistory) { - unlistenHistory(); - } - - subscribers.clear(); - pendingNavigationController && pendingNavigationController.abort(); - state.fetchers.forEach((_, key) => deleteFetcher(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) { - state = _extends({}, state, newState); - subscribers.forEach(subscriber => subscriber(state)); - } // 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) { - var _state$navigation$for; - - // Deduce if we're in a loading/actionReload state: - // - We have committed actionData in the store - // - The current navigation was a submission - // - We're past the submitting state and into the loading state - // - The location we've finished loading is different from the submission - // location, indicating we redirected from the action (avoids false - // positives for loading/submissionRedirect when actionData returned - // on a prior submission) - let isActionReload = state.actionData != null && state.navigation.formMethod != null && state.navigation.state === "loading" && ((_state$navigation$for = state.navigation.formAction) == null ? void 0 : _state$navigation$for.split("?")[0]) === location.pathname; // Always preserve any existing loaderData from re-used routes - - let newLoaderData = newState.loaderData ? { - loaderData: mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || []) - } : {}; - updateState(_extends({}, isActionReload ? {} : { - actionData: null - }, newState, newLoaderData, { - historyAction: pendingAction, - location, - initialized: true, - navigation: IDLE_NAVIGATION, - revalidation: "idle", - // Don't restore on submission navigations - restoreScrollPosition: state.navigation.formData ? false : getSavedScrollPosition(location, newState.matches || state.matches), - preventScrollReset: pendingPreventScrollReset - })); - - if (isUninterruptedRevalidation) ; else if (pendingAction === exports.Action.Pop) ; else if (pendingAction === exports.Action.Push) { - init.history.push(location, location.state); - } else if (pendingAction === exports.Action.Replace) { - init.history.replace(location, location.state); - } // Reset stateful navigation vars - - - pendingAction = exports.Action.Pop; - pendingPreventScrollReset = false; - isUninterruptedRevalidation = false; - isRevalidationRequired = false; - cancelledDeferredRoutes = []; - cancelledFetcherLoads = []; - } // 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 { - path, - submission, - error - } = normalizeNavigateOptions(to, opts); - let location = createLocation(state.location, path, opts && opts.state); - let historyAction = (opts && opts.replace) === true || submission != null ? exports.Action.Replace : exports.Action.Push; - let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined; - return await startNavigation(historyAction, location, { - 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 - }); - } // 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 - }); - } // 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; - let loadingNavigation = opts && opts.overrideNavigation; - let matches = matchRoutes(dataRoutes, location, init.basename); // Short circuit with a 404 on the root error boundary if we match nothing - - if (!matches) { - let { - matches: notFoundMatches, - route, - error - } = getNotFoundMatches(dataRoutes); // Cancel all pending deferred on 404s since we don't keep any routes - - cancelActiveDeferreds(); - completeNavigation(location, { - matches: notFoundMatches, - loaderData: {}, - errors: { - [route.id]: error - } - }); - return; - } // Short circuit if it's only a hash change - - - if (isHashChangeOnly(state.location, location)) { - completeNavigation(location, { - matches - }); - return; - } // Create a controller/Request for this navigation - - - pendingNavigationController = new AbortController(); - let request = createRequest(location, pendingNavigationController.signal, opts && opts.submission); - let pendingActionData; - let pendingError; - - 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. - pendingError = { - [findNearestBoundary(matches).route.id]: opts.pendingError - }; - } else if (opts && opts.submission) { - // Call action if we received an action submission - let actionOutput = await handleAction(request, location, opts.submission, matches, { - replace: opts.replace - }); - - if (actionOutput.shortCircuited) { - return; - } - - pendingActionData = actionOutput.pendingActionData; - pendingError = actionOutput.pendingActionError; - - let navigation = _extends({ - state: "loading", - location - }, opts.submission); - - loadingNavigation = navigation; - } // Call loaders - - - let { - shortCircuited, - loaderData, - errors - } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.replace, pendingActionData, pendingError); - - 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, - loaderData, - errors - }); - } // Call the action matched by the leaf route for this navigation and handle - // redirects/errors - - - async function handleAction(request, location, submission, matches, opts) { - interruptActiveLoads(); // Put us in a submitting state - - let navigation = _extends({ - state: "submitting", - location - }, submission); - - updateState({ - navigation - }); // Call our action and get the result - - let result; - let actionMatch = getTargetMatch(matches, location); - - if (!actionMatch.route.action) { - result = getMethodNotAllowedResult(location); - } else { - result = await callLoaderOrAction("action", request, actionMatch); - - if (request.signal.aborted) { - return { - shortCircuited: true - }; - } - } - - if (isRedirectResult(result)) { - let redirectNavigation = _extends({ - state: "loading", - location: createLocation(state.location, result.location) - }, submission); - - await startRedirectNavigation(result, redirectNavigation, opts && opts.replace); - return { - shortCircuited: true - }; - } - - 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 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 = exports.Action.Push; - } - - return { - pendingActionError: { - [boundaryMatch.route.id]: result.error - } - }; - } - - if (isDeferredResult(result)) { - throw new Error("defer() is not supported in actions"); - } - - return { - pendingActionData: { - [actionMatch.route.id]: result.data - } - }; - } // Call all applicable loaders for the given matches, handling redirects, - // errors, etc. - - - async function handleLoaders(request, location, matches, overrideNavigation, submission, replace, pendingActionData, pendingError) { - // Figure out the right navigation we want to use for data loading - let loadingNavigation = overrideNavigation; - - if (!loadingNavigation) { - let navigation = { - state: "loading", - location, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - loadingNavigation = navigation; - } - - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches); // 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)); // Short circuit if we have no loaders to run - - if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) { - completeNavigation(location, { - matches, - loaderData: mergeLoaderData(state.loaderData, {}, matches), - // Commit pending error if we're short circuiting - errors: pendingError || null, - actionData: pendingActionData || null - }); - return { - shortCircuited: true - }; - } // 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 (!isUninterruptedRevalidation) { - revalidatingFetchers.forEach(_ref2 => { - let [key] = _ref2; - const fetcher = state.fetchers.get(key); - let revalidatingFetcher = { - state: "loading", - data: fetcher && fetcher.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - state.fetchers.set(key, revalidatingFetcher); - }); - updateState(_extends({ - navigation: loadingNavigation, - actionData: pendingActionData || state.actionData || null - }, revalidatingFetchers.length > 0 ? { - fetchers: new Map(state.fetchers) - } : {})); - } - - pendingNavigationLoadId = ++incrementingLoadId; - revalidatingFetchers.forEach(_ref3 => { - let [key] = _ref3; - return fetchControllers.set(key, pendingNavigationController); - }); - let { - results, - 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 - - - revalidatingFetchers.forEach(_ref4 => { - let [key] = _ref4; - return fetchControllers.delete(key); - }); // If any loaders returned a redirect Response, start a new REPLACE navigation - - let redirect = findRedirect(results); - - if (redirect) { - let redirectNavigation = getLoaderRedirect(state, redirect); - await startRedirectNavigation(redirect, redirectNavigation, replace); - return { - shortCircuited: true - }; - } // Process and commit output from loaders - - - let { - loaderData, - errors - } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, 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); - } - }); - }); - markFetchRedirectsDone(); - let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); - return _extends({ - loaderData, - errors - }, didAbortFetchLoads || revalidatingFetchers.length > 0 ? { - fetchers: new Map(state.fetchers) - } : {}); - } - - function getFetcher(key) { - return state.fetchers.get(key) || IDLE_FETCHER; - } // Trigger a fetcher load/submit for the given fetcher key - - - function fetch(key, routeId, href, opts) { - if (typeof AbortController === "undefined") { - throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback."); - } - - if (fetchControllers.has(key)) abortFetcher(key); - let matches = matchRoutes(dataRoutes, href, init.basename); - - if (!matches) { - setFetcherError(key, routeId, new ErrorResponse(404, "Not Found", null)); - return; - } - - let { - path, - submission - } = normalizeNavigateOptions(href, opts, true); - let match = getTargetMatch(matches, path); - - if (submission) { - handleFetcherAction(key, routeId, path, match, submission); - return; - } // Store off the match so we can call it's shouldRevalidate on subsequent - // revalidations - - - fetchLoadMatches.set(key, [path, match]); - handleFetcherLoader(key, routeId, path, match); - } // Call the action for the matched fetcher.submit(), and then handle redirects, - // errors, and revalidation - - - async function handleFetcherAction(key, routeId, path, match, submission) { - interruptActiveLoads(); - fetchLoadMatches.delete(key); - - if (!match.route.action) { - let { - error - } = getMethodNotAllowedResult(path); - setFetcherError(key, routeId, error); - return; - } // Put this fetcher into it's submitting state - - - let existingFetcher = state.fetchers.get(key); - - let fetcher = _extends({ - state: "submitting" - }, submission, { - data: existingFetcher && existingFetcher.data - }); - - state.fetchers.set(key, fetcher); - updateState({ - fetchers: new Map(state.fetchers) - }); // Call the action for the fetcher - - let abortController = new AbortController(); - let fetchRequest = createRequest(path, abortController.signal, submission); - fetchControllers.set(key, abortController); - let actionResult = await callLoaderOrAction("action", fetchRequest, match); - - if (fetchRequest.signal.aborted) { - // We can delete this so long as we weren't aborted by ou our own fetcher - // re-submit which would have put _new_ controller is in fetchControllers - if (fetchControllers.get(key) === abortController) { - fetchControllers.delete(key); - } - - return; - } - - if (isRedirectResult(actionResult)) { - fetchControllers.delete(key); - fetchRedirectIds.add(key); - - let loadingFetcher = _extends({ - state: "loading" - }, submission, { - data: undefined - }); - - state.fetchers.set(key, loadingFetcher); - updateState({ - fetchers: new Map(state.fetchers) - }); - - let redirectNavigation = _extends({ - state: "loading", - location: createLocation(state.location, actionResult.location) - }, submission); - - await startRedirectNavigation(actionResult, redirectNavigation); - return; - } // Process any non-redirect errors thrown - - - if (isErrorResult(actionResult)) { - setFetcherError(key, routeId, actionResult.error); - return; - } - - if (isDeferredResult(actionResult)) { - invariant(false, "defer() is not supported in actions"); - } // 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 = createRequest(nextLocation, abortController.signal); - let matches = state.navigation.state !== "idle" ? matchRoutes(dataRoutes, state.navigation.location, init.basename) : state.matches; - invariant(matches, "Didn't find any matches after fetcher action"); - let loadId = ++incrementingLoadId; - fetchReloadIds.set(key, loadId); - - let loadFetcher = _extends({ - state: "loading", - data: actionResult.data - }, submission); - - state.fetchers.set(key, loadFetcher); - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(state, matches, submission, nextLocation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, { - [match.route.id]: actionResult.data - }, undefined, // No need to send through errors since we short circuit above - fetchLoadMatches); // 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(_ref5 => { - let [staleKey] = _ref5; - return staleKey !== key; - }).forEach(_ref6 => { - let [staleKey] = _ref6; - let existingFetcher = state.fetchers.get(staleKey); - let revalidatingFetcher = { - state: "loading", - data: existingFetcher && existingFetcher.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - state.fetchers.set(staleKey, revalidatingFetcher); - fetchControllers.set(staleKey, abortController); - }); - updateState({ - fetchers: new Map(state.fetchers) - }); - let { - results, - loaderResults, - fetcherResults - } = await callLoadersAndMaybeResolveData(state.matches, matchesToLoad, revalidatingFetchers, revalidationRequest); - - if (abortController.signal.aborted) { - return; - } - - fetchReloadIds.delete(key); - fetchControllers.delete(key); - revalidatingFetchers.forEach(_ref7 => { - let [staleKey] = _ref7; - return fetchControllers.delete(staleKey); - }); - let redirect = findRedirect(results); - - if (redirect) { - let redirectNavigation = getLoaderRedirect(state, redirect); - await startRedirectNavigation(redirect, redirectNavigation); - return; - } // Process and commit output from loaders - - - let { - loaderData, - errors - } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds); - let doneFetcher = { - state: "idle", - data: actionResult.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - state.fetchers.set(key, doneFetcher); - let didAbortFetchLoads = 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(_extends({ - errors, - loaderData: mergeLoaderData(state.loaderData, loaderData, matches) - }, didAbortFetchLoads ? { - 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) { - let existingFetcher = state.fetchers.get(key); // Put this fetcher into it's loading state - - let loadingFetcher = { - state: "loading", - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - data: existingFetcher && existingFetcher.data - }; - state.fetchers.set(key, loadingFetcher); - updateState({ - fetchers: new Map(state.fetchers) - }); // Call the loader for this fetcher route match - - let abortController = new AbortController(); - let fetchRequest = createRequest(path, abortController.signal); - fetchControllers.set(key, abortController); - let result = await callLoaderOrAction("loader", fetchRequest, match); // Deferred isn't supported or 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 ou 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; - } // If the loader threw a redirect Response, start a new REPLACE navigation - - - if (isRedirectResult(result)) { - let redirectNavigation = getLoaderRedirect(state, result); - await startRedirectNavigation(result, redirectNavigation); - return; - } // Process any non-redirect errors thrown - - - if (isErrorResult(result)) { - let boundaryMatch = findNearestBoundary(state.matches, routeId); - state.fetchers.delete(key); // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch - - // do we need to behave any differently with our non-redirect errors? - // What if it was a non-redirect Response? - - updateState({ - fetchers: new Map(state.fetchers), - errors: { - [boundaryMatch.route.id]: result.error - } - }); - return; - } - - invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); // Put the fetcher back into an idle state - - let doneFetcher = { - state: "idle", - data: result.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - state.fetchers.set(key, doneFetcher); - updateState({ - fetchers: new Map(state.fetchers) - }); - } - /** - * 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(redirect, navigation, replace) { - if (redirect.revalidate) { - isRevalidationRequired = true; - } - - invariant(navigation.location, "Expected a location on the redirect navigation"); // 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 ? exports.Action.Replace : exports.Action.Push; - await startNavigation(redirectHistoryAction, navigation.location, { - overrideNavigation: navigation - }); - } - - async function callLoadersAndMaybeResolveData(currentMatches, matchesToLoad, fetchersToLoad, request) { - // Call all navigation loaders and revalidating fetcher loaders in parallel, - // then slice off the results into separate arrays so we can handle them - // accordingly - let results = await Promise.all([...matchesToLoad.map(m => callLoaderOrAction("loader", request, m)), ...fetchersToLoad.map(_ref8 => { - let [, href, match] = _ref8; - return callLoaderOrAction("loader", createRequest(href, request.signal), match); - })]); - let loaderResults = results.slice(0, matchesToLoad.length); - let fetcherResults = results.slice(matchesToLoad.length); - await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, request.signal, false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(_ref9 => { - let [,, match] = _ref9; - return match; - }), fetcherResults, request.signal, true)]); - return { - results, - 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.push(key); - abortFetcher(key); - } - }); - } - - function setFetcherError(key, routeId, error) { - let boundaryMatch = findNearestBoundary(state.matches, routeId); - deleteFetcher(key); - updateState({ - errors: { - [boundaryMatch.route.id]: error - }, - fetchers: new Map(state.fetchers) - }); - } - - function deleteFetcher(key) { - if (fetchControllers.has(key)) abortFetcher(key); - fetchLoadMatches.delete(key); - fetchReloadIds.delete(key); - fetchRedirectIds.delete(key); - state.fetchers.delete(key); - } - - function abortFetcher(key) { - let controller = fetchControllers.get(key); - invariant(controller, "Expected fetch controller: " + key); - controller.abort(); - fetchControllers.delete(key); - } - - function markFetchersDone(keys) { - for (let key of keys) { - let fetcher = getFetcher(key); - let doneFetcher = { - state: "idle", - data: fetcher.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - state.fetchers.set(key, doneFetcher); - } - } - - function markFetchRedirectsDone() { - let doneKeys = []; - - 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); - } - } - - markFetchersDone(doneKeys); - } - - 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 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 component - - - function enableScrollRestoration(positions, getPosition, getKey) { - savedScrollPositions = positions; - getScrollPosition = getPosition; - - getScrollRestorationKey = getKey || (location => location.key); // Perform initial hydration scroll restoration, since we miss the boat on - // the initial updateState() because we've not yet rendered - // 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 saveScrollPosition(location, matches) { - if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) { - let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData)); - let key = getScrollRestorationKey(location, userMatches) || location.key; - savedScrollPositions[key] = getScrollPosition(); - } - } - - function getSavedScrollPosition(location, matches) { - if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) { - let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData)); - let key = getScrollRestorationKey(location, userMatches) || location.key; - let y = savedScrollPositions[key]; - - if (typeof y === "number") { - return y; - } - } - - return null; - } - - router = { - get basename() { - return init.basename; - }, - - get state() { - return state; - }, - - get routes() { - return dataRoutes; - }, - - initialize, - subscribe, - enableScrollRestoration, - navigate, - fetch, - revalidate, - createHref, - getFetcher, - deleteFetcher, - dispose, - _internalFetchControllers: fetchControllers, - _internalActiveDeferreds: activeDeferreds - }; - return router; -} //#endregion -//////////////////////////////////////////////////////////////////////////////// -//#region createStaticHandler -//////////////////////////////////////////////////////////////////////////////// - -function unstable_createStaticHandler(routes) { - invariant(routes.length > 0, "You must provide a non-empty routes array to unstable_createStaticHandler"); - let dataRoutes = convertRoutesToDataRoutes(routes); - - async function query(request) { - let { - location, - result - } = await queryImpl(request); - - if (result instanceof Response) { - 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 - }, result); - } - - async function queryRoute(request, routeId) { - let { - result - } = await queryImpl(request, routeId); - - if (result instanceof Response) { - return result; - } - - let error = result.errors ? Object.values(result.errors)[0] : undefined; - - if (error !== undefined) { - // While we always re-throw Responses returned from loaders/actions - // directly for route requests and prevent the unwrapping into an - // ErrorResponse, we still need this for error cases _prior_ the - // execution of the loader/action, such as a 404/405 error. - if (isRouteErrorResponse(error)) { - return new Response(error.data, { - status: error.status, - statusText: error.statusText - }); - } // 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 - - - let routeData = [result.actionData, result.loaderData].find(v => v); - let value = Object.values(routeData || {})[0]; - - if (isRouteErrorResponse(value)) { - return new Response(value.data, { - status: value.status, - statusText: value.statusText - }); - } - - return value; - } - - async function queryImpl(request, routeId) { - invariant(request.method !== "HEAD", "query()/queryRoute() do not support HEAD requests"); - invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal"); - let { - location, - matches, - shortCircuitState - } = matchRequest(request, routeId); - - try { - if (shortCircuitState) { - return { - location, - result: shortCircuitState - }; - } - - if (request.method !== "GET") { - let result = await submit(request, matches, getTargetMatch(matches, location), routeId != null); - return { - location, - result - }; - } - - let result = await loadRouteData(request, matches, routeId != null); - return { - location, - result: _extends({}, result, { - actionData: null, - actionHeaders: {} - }) - }; - } catch (e) { - if (e instanceof Response) { - return { - location, - result: e - }; - } - - throw e; - } - } - - async function submit(request, matches, actionMatch, isRouteRequest) { - let result; - - if (!actionMatch.route.action) { - let href = createHref(new URL(request.url)); - result = getMethodNotAllowedResult(href); - } else { - result = await callLoaderOrAction("action", request, actionMatch, true, isRouteRequest); - - if (request.signal.aborted) { - let method = isRouteRequest ? "queryRoute" : "query"; - throw new Error(method + "() call aborted"); - } - } - - if (isRedirectResult(result)) { - // Uhhhh - this should never happen, we should always throw these from - // calLoaderOrAction, 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.status, - headers: { - Location: result.location - } - }); - } - - if (isDeferredResult(result)) { - throw new Error("defer() is not supported in actions"); - } - - if (isRouteRequest) { - if (isErrorResult(result)) { - let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); - return { - matches: [actionMatch], - loaderData: {}, - actionData: null, - errors: { - [boundaryMatch.route.id]: result.error - }, - // Note: statusCode + headers are unused here since queryRoute will - // return the raw Response or value - statusCode: 500, - loaderHeaders: {}, - actionHeaders: {} - }; - } - - 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: {} - }; - } - - 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); - let context = await loadRouteData(request, matches, isRouteRequest, { - [boundaryMatch.route.id]: result.error - }); // action status codes take precedence over loader status codes - - return _extends({}, context, { - statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500, - actionData: null, - actionHeaders: _extends({}, result.headers ? { - [actionMatch.route.id]: result.headers - } : {}) - }); - } - - let context = await loadRouteData(request, matches, isRouteRequest); - return _extends({}, context, result.statusCode ? { - statusCode: result.statusCode - } : {}, { - actionData: { - [actionMatch.route.id]: result.data - }, - actionHeaders: _extends({}, result.headers ? { - [actionMatch.route.id]: result.headers - } : {}) - }); - } - - async function loadRouteData(request, matches, isRouteRequest, pendingActionError) { - let matchesToLoad = getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]).filter(m => m.route.loader); // Short circuit if we have no loaders to run - - if (matchesToLoad.length === 0) { - return { - matches, - loaderData: {}, - errors: pendingActionError || null, - statusCode: 200, - loaderHeaders: {} - }; - } - - let results = await Promise.all([...matchesToLoad.map(m => callLoaderOrAction("loader", request, m, true, isRouteRequest))]); - - if (request.signal.aborted) { - let method = isRouteRequest ? "queryRoute" : "query"; - throw new Error(method + "() call aborted"); - } // Can't do anything with these without the Remix side of things, so just - // cancel them for now - - - results.forEach(result => { - if (isDeferredResult(result)) { - result.deferredData.cancel(); - } - }); // Process and commit output from loaders - - let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError); - return _extends({}, context, { - matches - }); - } - - function matchRequest(req, routeId) { - let url = new URL(req.url); - let location = createLocation("", createPath(url), null, "default"); - let matches = matchRoutes(dataRoutes, location); - - if (matches && routeId) { - matches = matches.filter(m => m.route.id === routeId); - } // Short circuit with a 404 if we match nothing - - - if (!matches) { - let { - matches: notFoundMatches, - route, - error - } = getNotFoundMatches(dataRoutes); - return { - location, - matches: notFoundMatches, - shortCircuitState: { - matches: notFoundMatches, - loaderData: {}, - actionData: null, - errors: { - [route.id]: error - }, - statusCode: 404, - loaderHeaders: {}, - actionHeaders: {} - } - }; - } - - return { - location, - matches - }; - } - - 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: 500, - errors: { - [context._deepestRenderedBoundaryId || routes[0].id]: error - } - }); - - return newContext; -} // Normalize navigation options by converting formMethod=GET formData objects to -// URLSearchParams so they behave identically to links with query params - -function normalizeNavigateOptions(to, opts, isFetcher) { - if (isFetcher === void 0) { - isFetcher = false; - } - - let path = typeof to === "string" ? to : createPath(to); // Return location verbatim on non-submission navigations - - if (!opts || !("formMethod" in opts) && !("formData" in opts)) { - return { - path - }; - } // Create a Submission on non-GET navigations - - - if (opts.formMethod != null && opts.formMethod !== "get") { - return { - path, - submission: { - formMethod: opts.formMethod, - formAction: createHref(parsePath(path)), - formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded", - formData: opts.formData - } - }; - } // No formData to flatten for GET submission - - - if (!opts.formData) { - return { - path - }; - } // Flatten submission onto URLSearchParams for GET submissions - - - let parsedPath = parsePath(path); - - try { - let searchParams = convertFormDataToSearchParams(opts.formData); // Since fetcher GET submissions only run a single loader (as opposed to - // navigation GET submissions which run all loaders), we need to preserve - // any incoming ?index params - - if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) { - searchParams.append("index", ""); - } - - parsedPath.search = "?" + searchParams; - } catch (e) { - return { - path, - error: new ErrorResponse(400, "Bad Request", "Cannot submit binary form data using GET") - }; - } - - return { - path: createPath(parsedPath) - }; -} - -function getLoaderRedirect(state, redirect) { - let { - formMethod, - formAction, - formEncType, - formData - } = state.navigation; - let navigation = { - state: "loading", - location: createLocation(state.location, redirect.location), - formMethod: formMethod || undefined, - formAction: formAction || undefined, - formEncType: formEncType || undefined, - formData: formData || undefined - }; - return navigation; -} // Filter out all routes below any caught error as they aren't going to -// render so we don't need to load them - - -function getLoaderMatchesUntilBoundary(matches, boundaryId) { - let boundaryMatches = matches; - - if (boundaryId) { - let index = matches.findIndex(m => m.route.id === boundaryId); - - if (index >= 0) { - boundaryMatches = matches.slice(0, index); - } - } - - return boundaryMatches; -} - -function getMatchesToLoad(state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches) { - let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : null; // Pick navigation matches that are net-new or qualify for revalidation - - let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined; - let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId); - let navigationMatches = boundaryMatches.filter((match, index) => match.route.loader != null && (isNewLoader(state.loaderData, state.matches[index], match) || // If this route had a pending deferred cancelled it must be revalidated - cancelledDeferredRoutes.some(id => id === match.route.id) || shouldRevalidateLoader(state.location, state.matches[index], submission, location, match, isRevalidationRequired, actionResult))); // Pick fetcher.loads that need to be revalidated - - let revalidatingFetchers = []; - fetchLoadMatches && fetchLoadMatches.forEach((_ref10, key) => { - let [href, match] = _ref10; - - // This fetcher was cancelled from a prior action submission - force reload - if (cancelledFetcherLoads.includes(key)) { - revalidatingFetchers.push([key, href, match]); - } else if (isRevalidationRequired) { - let shouldRevalidate = shouldRevalidateLoader(href, match, submission, href, match, isRevalidationRequired, actionResult); - - if (shouldRevalidate) { - revalidatingFetchers.push([key, href, match]); - } - } - }); - return [navigationMatches, revalidatingFetchers]; -} - -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 && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"] - ); -} - -function shouldRevalidateLoader(currentLocation, currentMatch, submission, location, match, isRevalidationRequired, actionResult) { - let currentUrl = createURL(currentLocation); - let currentParams = currentMatch.params; - let nextUrl = createURL(location); - let nextParams = match.params; // This is the default implementation as to 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 - // Note that fetchers always provide the same current/next locations so the - // URL-based checks here don't apply to fetcher shouldRevalidate calls - - let defaultShouldRevalidate = isNewRouteInstance(currentMatch, match) || // Clicked the same link, resubmitted a GET form - currentUrl.toString() === nextUrl.toString() || // Search params affect all loaders - currentUrl.search !== nextUrl.search || // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate - isRevalidationRequired; - - if (match.route.shouldRevalidate) { - let routeChoice = match.route.shouldRevalidate(_extends({ - currentUrl, - currentParams, - nextUrl, - nextParams - }, submission, { - actionResult, - defaultShouldRevalidate - })); - - if (typeof routeChoice === "boolean") { - return routeChoice; - } - } - - return defaultShouldRevalidate; -} - -async function callLoaderOrAction(type, request, match, skipRedirects, isRouteRequest) { - if (skipRedirects === void 0) { - skipRedirects = false; - } - - if (isRouteRequest === void 0) { - isRouteRequest = false; - } - - let resultType; - let result; // Setup a promise we can race against so that abort signals short circuit - - let reject; - let abortPromise = new Promise((_, r) => reject = r); - - let onReject = () => reject(); - - request.signal.addEventListener("abort", onReject); - - try { - let handler = match.route[type]; - invariant(handler, "Could not find the " + type + " to run on the \"" + match.route.id + "\" route"); - result = await Promise.race([handler({ - request, - params: match.params - }), abortPromise]); - } catch (e) { - resultType = ResultType.error; - result = e; - } finally { - request.signal.removeEventListener("abort", onReject); - } - - if (result instanceof Response) { - // Process redirects - let status = result.status; - let location = result.headers.get("Location"); // For SSR single-route requests, we want to hand Responses back directly - // without unwrapping - - if (isRouteRequest) { - throw result; - } - - if (status >= 300 && status <= 399 && location != null) { - // Don't process redirects in the router during SSR document requests. - // Instead, throw the Response and let the server handle it with an HTTP - // redirect - if (skipRedirects) { - throw result; - } - - return { - type: ResultType.redirect, - status, - location, - revalidate: result.headers.get("X-Remix-Revalidate") !== null - }; - } - - let data; - let contentType = result.headers.get("Content-Type"); - - if (contentType && contentType.startsWith("application/json")) { - data = await result.json(); - } else { - data = await result.text(); - } - - if (resultType === ResultType.error) { - return { - type: resultType, - error: new ErrorResponse(status, result.statusText, data), - headers: result.headers - }; - } - - return { - type: ResultType.data, - data, - statusCode: result.status, - headers: result.headers - }; - } - - if (resultType === ResultType.error) { - return { - type: resultType, - error: result - }; - } - - if (result instanceof DeferredData) { - return { - type: ResultType.deferred, - deferredData: result - }; - } - - return { - type: ResultType.data, - data: result - }; -} - -function createRequest(location, signal, submission) { - let url = createURL(location).toString(); - let init = { - signal - }; - - if (submission) { - let { - formMethod, - formEncType, - formData - } = submission; - init.method = formMethod.toUpperCase(); - init.body = formEncType === "application/x-www-form-urlencoded" ? convertFormDataToSearchParams(formData) : formData; - } // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - - - return new Request(url, init); -} - -function convertFormDataToSearchParams(formData) { - let searchParams = new URLSearchParams(); - - for (let [key, value] of formData.entries()) { - invariant(typeof value === "string", 'File inputs are not supported with encType "application/x-www-form-urlencoded", ' + 'please use "multipart/form-data" instead.'); - searchParams.append(key, value); - } - - return searchParams; -} - -function processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds) { - // Fill in loaderData/errors from our loaders - let loaderData = {}; - let errors = null; - let statusCode; - let foundError = false; - let loaderHeaders = {}; // Process loader results into state.loaderData/state.errors - - results.forEach((result, index) => { - let id = matchesToLoad[index].route.id; - invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData"); - - if (isErrorResult(result)) { - // Look upwards from the matched route for the closest ancestor - // error boundary, defaulting to the root match - let boundaryMatch = findNearestBoundary(matches, id); - 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) { - error = Object.values(pendingError)[0]; - pendingError = undefined; - } - - errors = Object.assign(errors || {}, { - [boundaryMatch.route.id]: error - }); // 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 && activeDeferreds.set(id, result.deferredData); - loaderData[id] = result.deferredData.data; // TODO: Add statusCode/headers once we wire up streaming in Remix - } 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 != null && 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 - - if (pendingError) { - errors = pendingError; - } - - return { - loaderData, - errors, - statusCode: statusCode || 200, - loaderHeaders - }; -} - -function processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) { - let { - loaderData, - errors - } = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds); // Process results from our revalidating fetchers - - for (let index = 0; index < revalidatingFetchers.length; index++) { - let [key,, match] = revalidatingFetchers[index]; - invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result"); - let result = fetcherResults[index]; // Process fetcher non-redirect errors - - if (isErrorResult(result)) { - let boundaryMatch = findNearestBoundary(state.matches, 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 - throw new Error("Unhandled fetcher revalidation redirect"); - } else if (isDeferredResult(result)) { - // Should never get here, deferred data should be awaited for fetchers - // in resolveDeferredResults - throw new Error("Unhandled fetcher deferred data"); - } else { - let doneFetcher = { - state: "idle", - data: result.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - state.fetchers.set(key, doneFetcher); - } - } - - return { - loaderData, - errors - }; -} - -function mergeLoaderData(loaderData, newLoaderData, matches) { - let mergedLoaderData = _extends({}, newLoaderData); - - matches.forEach(match => { - let id = match.route.id; - - if (newLoaderData[id] === undefined && loaderData[id] !== undefined) { - mergedLoaderData[id] = loaderData[id]; - } - }); - return mergedLoaderData; -} // 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 getNotFoundMatches(routes) { - // Prefer a root layout route if present, otherwise shim in a route object - let route = routes.find(r => r.index || r.path === "" || r.path === "/") || { - id: "__shim-404-route__" - }; - return { - matches: [{ - params: {}, - pathname: "", - pathnameBase: "", - route - }], - route, - error: new ErrorResponse(404, "Not Found", null) - }; -} - -function getMethodNotAllowedResult(path) { - let href = typeof path === "string" ? path : createHref(path); - console.warn("You're trying to submit to a route that does not have an action. To " + "fix this, please add an `action` function to the route for " + ("[" + href + "]")); - return { - type: ResultType.error, - error: new ErrorResponse(405, "Method Not Allowed", "No action found for [" + href + "]") - }; -} // Find any returned redirect errors, starting from the lowest match - - -function findRedirect(results) { - for (let i = results.length - 1; i >= 0; i--) { - let result = results[i]; - - if (isRedirectResult(result)) { - return result; - } - } -} // Create an href to represent a "server" URL without the hash - - -function createHref(location) { - return (location.pathname || "") + (location.search || ""); -} - -function isHashChangeOnly(a, b) { - return a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash; -} - -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; -} - -async function resolveDeferredResults(currentMatches, matchesToLoad, results, signal, isFetcher, currentLoaderData) { - for (let index = 0; index < results.length; index++) { - let result = results[index]; - let match = matchesToLoad[index]; - 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) && (isFetcher || 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, isFetcher).then(result => { - if (result) { - results[index] = result || results[index]; - } - }); - } - } -} - -async function resolveDeferredData(result, signal, unwrap) { - if (unwrap === void 0) { - unwrap = false; - } - - let aborted = await result.deferredData.resolveData(signal); - - if (aborted) { - return; - } - - if (unwrap) { - try { - return { - type: ResultType.data, - data: result.deferredData.unwrappedData - }; - } catch (e) { - // 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 === ""); -} // Note: This should match the format exported by useMatches, so if you change -// this please also change that :) Eventually we'll DRY this up - - -function createUseMatchesMatch(match, loaderData) { - let { - route, - pathname, - params - } = match; - return { - id: route.id, - pathname, - params, - data: loaderData[route.id], - handle: route.handle - }; -} - -function getTargetMatch(matches, location) { - let search = typeof location === "string" ? parsePath(location).search : location.search; - - if (matches[matches.length - 1].route.index && !hasNakedIndexQuery(search || "")) { - return matches.slice(-2)[0]; - } - - return matches.slice(-1)[0]; -} - -function createURL(location) { - let base = typeof window !== "undefined" && typeof window.location !== "undefined" ? window.location.origin : "unknown://unknown"; - let href = typeof location === "string" ? location : createHref(location); - return new URL(href, base); -} //#endregion - -exports.AbortedDeferredError = AbortedDeferredError; -exports.ErrorResponse = ErrorResponse; -exports.IDLE_FETCHER = IDLE_FETCHER; -exports.IDLE_NAVIGATION = IDLE_NAVIGATION; -exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes; -exports.createBrowserHistory = createBrowserHistory; -exports.createHashHistory = createHashHistory; -exports.createMemoryHistory = createMemoryHistory; -exports.createPath = createPath; -exports.createRouter = createRouter; -exports.defer = defer; -exports.generatePath = generatePath; -exports.getStaticContextFromError = getStaticContextFromError; -exports.getToPathname = getToPathname; -exports.invariant = invariant; -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.resolvePath = resolvePath; -exports.resolveTo = resolveTo; -exports.stripBasename = stripBasename; -exports.unstable_createStaticHandler = unstable_createStaticHandler; -exports.warning = warning; -//# sourceMappingURL=router.cjs.js.map diff --git a/node_modules/@remix-run/router/dist/router.cjs.js.map b/node_modules/@remix-run/router/dist/router.cjs.js.map deleted file mode 100644 index 5d972acf..00000000 --- a/node_modules/@remix-run/router/dist/router.cjs.js.map +++ /dev/null @@ -1 +0,0 @@ -{"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/**\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 extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: any;\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/**\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`. May be either a URL or the pieces of a\n * URL path.\n */\nexport type To = string | Partial;\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 attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\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};\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;\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 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(to) {\n return typeof to === \"string\" ? to : createPath(to);\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 });\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 });\n }\n },\n go(delta) {\n action = Action.Pop;\n index = clampIndex(index + delta);\n if (listener) {\n listener({ action, location: getCurrentLocation() });\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 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\nfunction 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): HistoryState {\n return {\n usr: location.state,\n key: location.key,\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 {\n let location: Readonly = {\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) {\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 {\n let parsedPath: Partial = {};\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 function handlePop() {\n action = Action.Pop;\n if (listener) {\n listener({ action, location: history.location });\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 let historyState = getHistoryState(location);\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 // 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 });\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 let historyState = getHistoryState(location);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: location });\n }\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 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 { parsePath } 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: any;\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}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n status: number;\n location: string;\n revalidate: boolean;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: any;\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\nexport type FormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\";\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport interface Submission {\n formMethod: Exclude;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\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 {\n request: Request;\n params: Params;\n}\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Route loader function signature\n */\nexport interface LoaderFunction {\n (args: LoaderFunctionArgs): Promise | Response | Promise | any;\n}\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (args: ActionFunctionArgs): Promise | Response | Promise | any;\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: {\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 formData?: Submission[\"formData\"];\n actionResult?: DataResult;\n defaultShouldRevalidate: boolean;\n }): boolean;\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;\n action?: ActionFunction;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\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\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\n : // find params after `:`\n Path extends `${string}:${infer Param}`\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 */\ntype PathParam =\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\n : // look for params in the absence of wildcards\n _PathParam;\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 =\n // if could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\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;\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 {}\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 parentPath: number[] = [],\n allIds: Set = new Set()\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, 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 !allIds.has(id),\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n allIds.add(id);\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = { ...route, id };\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n id,\n children: route.children\n ? convertRoutesToDataRoutes(route.children, treePath, allIds)\n : undefined,\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/docs/en/v6/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | 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 for (let i = 0; matches == null && i < branches.length; ++i) {\n matches = matchRouteBranch(branches[i], pathname);\n }\n\n return matches;\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[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n routes.forEach((route, index) => {\n let meta: RouteMeta = {\n relativePath: route.path || \"\",\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\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({ path, score: computeScore(path, route.index), routesMeta });\n });\n\n return branches;\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,\n pathname: string\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\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 if (!match) return null;\n\n Object.assign(matchedParams, match.params);\n\n let route = meta.route;\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\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/docs/en/v6/utils/generate-path\n */\nexport function generatePath(\n path: Path,\n params: {\n [key in PathParam]: string;\n } = {} as any\n): string {\n return path\n .replace(/:(\\w+)/g, (_, key: PathParam) => {\n invariant(params[key] != null, `Missing \":${key}\" param`);\n return params[key]!;\n })\n .replace(/(\\/?)\\*/, (_, prefix, __, str) => {\n const star = \"*\" as PathParam;\n\n if (params[star] == null) {\n // If no splat was provided, trim the trailing slash _unless_ it's\n // the entire path\n return str === \"/*\" ? \"/\" : \"\";\n }\n\n // Apply the splat\n return `${prefix}${params[star]}`;\n });\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\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 {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\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 = {\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/docs/en/v6/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, paramNames] = 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 = paramNames.reduce>(\n (memo, paramName, 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 memo[paramName] = safelyDecodeURIComponent(\n captureGroups[index] || \"\",\n paramName\n );\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, string[]] {\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 paramNames: string[] = [];\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(/:(\\w+)/g, (_: string, paramName: string) => {\n paramNames.push(paramName);\n return \"([^\\\\/]+)\";\n });\n\n if (path.endsWith(\"*\")) {\n paramNames.push(\"*\");\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, paramNames];\n}\n\nfunction safelyDecodeURIComponent(value: string, paramName: string) {\n try {\n return decodeURIComponent(value);\n } catch (error) {\n warning(\n false,\n `The value for the URL param \"${paramName}\" will not be decoded because` +\n ` the string \"${value}\" is a malformed URL segment. This is probably` +\n ` due to a bad percent 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\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\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\n/**\n * @private\n */\nexport function warning(cond: any, message: string): void {\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 React Router!\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\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/docs/en/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 = toPathname\n ? toPathname.startsWith(\"/\")\n ? toPathname\n : resolvePathname(toPathname, fromPathname)\n : fromPathname;\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\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 and the router will parse it for you.`\n );\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;\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 `` 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 (isPathRelative || toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n if (toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n // Each leading .. segment means \"go up one route\" instead of \"go up one\n // URL segment\". This is a key difference from how works and a\n // major reason we call this a \"to\" value instead of a \"href\".\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n // If there are more \"..\" segments than parent routes, resolve relative to\n // the root / URL.\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\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\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 = (\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 */\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 interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeys: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscriber?: (aborted: boolean) => void = undefined;\n data: Record;\n\n constructor(data: Record) {\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\n private trackPromise(\n key: string | number,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.pendingKeys.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, null, 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 | number,\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.pendingKeys.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n const subscriber = this.subscriber;\n if (error) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n subscriber && subscriber(false);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n subscriber && subscriber(false);\n return data;\n }\n\n subscribe(fn: (aborted: boolean) => void) {\n this.subscriber = fn;\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeys.forEach((v, k) => this.pendingKeys.delete(k));\n let subscriber = this.subscriber;\n subscriber && subscriber(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.pendingKeys.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\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 function defer(data: Record) {\n return new DeferredData(data);\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 * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n */\nexport class ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n\n constructor(status: number, statusText: string | undefined, data: any) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.data = data;\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response throw from an action/loader\n */\nexport function isRouteErrorResponse(e: any): e is ErrorResponse {\n return e instanceof ErrorResponse;\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n parsePath,\n} from \"./history\";\nimport type {\n DataResult,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n DeferredResult,\n ErrorResult,\n FormEncType,\n FormMethod,\n RedirectResult,\n RouteData,\n AgnosticRouteObject,\n Submission,\n SuccessResult,\n AgnosticRouteMatch,\n} from \"./utils\";\nimport {\n DeferredData,\n ErrorResponse,\n ResultType,\n convertRoutesToDataRoutes,\n invariant,\n isRouteErrorResponse,\n matchRoutes,\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 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 * 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,\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): 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, opts?: RouterNavigateOptions): 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,\n opts?: RouterNavigateOptions\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 * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key?: string): Fetcher;\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 * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\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;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n basename?: string;\n routes: AgnosticRouteObject[];\n history: History;\n hydrationData?: HydrationState;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\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;\n actionHeaders: Record;\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(request: Request): Promise;\n queryRoute(request: Request, routeId?: string): Promise;\n}\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (state: RouterState): void;\n}\n\ninterface UseMatchesMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: unknown;\n handle: unknown;\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: UseMatchesMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\n/**\n * Options for a navigate() call for a Link navigation\n */\ntype LinkNavigateOptions = {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n};\n\n/**\n * Options for a navigate() call for a Form navigation\n */\ntype SubmissionNavigateOptions = {\n replace?: boolean;\n state?: any;\n formMethod?: FormMethod;\n formEncType?: FormEncType;\n formData: FormData;\n};\n\n/**\n * Options to pass to navigate() for either a Link or Form navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions =\n | Omit\n | Omit;\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 };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: FormMethod | undefined;\n formAction: string | undefined;\n formEncType: FormEncType | undefined;\n formData: FormData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\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 = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: FormMethod | undefined;\n formAction: string | undefined;\n formEncType: FormEncType | undefined;\n formData: FormData | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n data: TData | undefined;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\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\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Error thrown from the current action, keyed by the route containing the\n * error boundary to render the error. To be committed to the state after\n * loaders have completed\n */\n pendingActionError?: RouteData;\n /**\n * Data returned from the current action, keyed by the route owning the action.\n * To be committed to the state after loaders have completed\n */\n pendingActionData?: RouteData;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\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 * Tuple of [key, href, DataRouterMatch] for a revalidating fetcher.load()\n */\ntype RevalidatingFetcher = [string, string, AgnosticDataRouteMatch];\n\n/**\n * Tuple of [href, DataRouteMatch] for an active fetcher.load()\n */\ntype FetchLoadMatch = [string, AgnosticDataRouteMatch];\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};\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};\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 invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let dataRoutes = convertRoutesToDataRoutes(init.routes);\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();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | 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 until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n let initialScrollRestored = false;\n\n let initialMatches = matchRoutes(\n dataRoutes,\n init.history.location,\n init.basename\n );\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null) {\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 { matches, route, error } = getNotFoundMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized =\n !initialMatches.some((m) => m.route.loader) || init.hydrationData != null;\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 restoreScrollPosition: 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 };\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 // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidate()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\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 // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\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 // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n // Fetchers that triggered redirect navigations from their actions\n let fetchRedirectIds = new Set();\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\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();\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 }) =>\n startNavigation(historyAction, location)\n );\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location);\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 subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(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(newState: Partial): void {\n state = {\n ...state,\n ...newState,\n };\n subscribers.forEach((subscriber) => subscriber(state));\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>\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 submission\n // - We're past the submitting state and into the loading state\n // - The location we've finished loading is different from the submission\n // location, indicating we redirected from the action (avoids false\n // positives for loading/submissionRedirect when actionData returned\n // on a prior submission)\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n state.navigation.state === \"loading\" &&\n state.navigation.formAction?.split(\"?\")[0] === location.pathname;\n\n // Always preserve any existing loaderData from re-used routes\n let newLoaderData = newState.loaderData\n ? {\n loaderData: mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || []\n ),\n }\n : {};\n\n updateState({\n // Clear existing actionData on any completed navigation beyond the original\n // action, unless we're currently finishing the loading/actionReload state.\n // Do this prior to spreading in newState in case we got back to back actions\n ...(isActionReload ? {} : { actionData: null }),\n ...newState,\n ...newLoaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n // Don't restore on submission navigations\n restoreScrollPosition: state.navigation.formData\n ? false\n : getSavedScrollPosition(location, newState.matches || state.matches),\n preventScrollReset: pendingPreventScrollReset,\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 // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\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,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(to, opts);\n\n let location = createLocation(state.location, path, opts && opts.state);\n let historyAction =\n (opts && opts.replace) === true || submission != null\n ? HistoryAction.Replace\n : HistoryAction.Push;\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n return await startNavigation(historyAction, location, {\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 });\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 { overrideNavigation: state.navigation }\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 submission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponse;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n }\n ): Promise {\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 let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(dataRoutes, location, init.basename);\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let {\n matches: notFoundMatches,\n route,\n error,\n } = getNotFoundMatches(dataRoutes);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(location, {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n });\n return;\n }\n\n // Short circuit if it's only a hash change\n if (isHashChangeOnly(state.location, location)) {\n completeNavigation(location, { matches });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createRequest(\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionData: RouteData | undefined;\n let pendingError: RouteData | 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 pendingError = {\n [findNearestBoundary(matches).route.id]: opts.pendingError,\n };\n } else if (opts && opts.submission) {\n // Call action if we received an action submission\n let actionOutput = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n { replace: opts.replace }\n );\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n ...opts.submission,\n };\n loadingNavigation = navigation;\n }\n\n // Call loaders\n let { shortCircuited, loaderData, errors } = await handleLoaders(\n request,\n location,\n matches,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.replace,\n pendingActionData,\n pendingError\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,\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 opts?: { replace?: boolean }\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n ...submission,\n };\n updateState({ navigation });\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) {\n result = getMethodNotAllowedResult(location);\n } else {\n result = await callLoaderOrAction(\"action\", request, actionMatch);\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let redirectNavigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location: createLocation(state.location, result.location),\n ...submission,\n };\n await startRedirectNavigation(\n result,\n redirectNavigation,\n opts && opts.replace\n );\n return { shortCircuited: true };\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 are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw new Error(\"defer() is not supported in actions\");\n }\n\n return {\n pendingActionData: { [actionMatch.route.id]: result.data },\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 overrideNavigation?: Navigation,\n submission?: Submission,\n replace?: boolean,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n ): Promise {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation = overrideNavigation;\n if (!loadingNavigation) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n loadingNavigation = navigation;\n }\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n state,\n matches,\n submission,\n location,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n pendingActionData,\n pendingError,\n fetchLoadMatches\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 // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n completeNavigation(location, {\n matches,\n loaderData: mergeLoaderData(state.loaderData, {}, matches),\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n actionData: pendingActionData || null,\n });\n return { shortCircuited: true };\n }\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 (!isUninterruptedRevalidation) {\n revalidatingFetchers.forEach(([key]) => {\n const fetcher = state.fetchers.get(key);\n let revalidatingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n data: fetcher && fetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(key, revalidatingFetcher);\n });\n updateState({\n navigation: loadingNavigation,\n actionData: pendingActionData || state.actionData || null,\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n });\n }\n\n pendingNavigationLoadId = ++incrementingLoadId;\n revalidatingFetchers.forEach(([key]) =>\n fetchControllers.set(key, pendingNavigationController!)\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.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 revalidatingFetchers.forEach(([key]) => fetchControllers.delete(key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n let redirectNavigation = getLoaderRedirect(state, redirect);\n await startRedirectNavigation(redirect, redirectNavigation, replace);\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n matchesToLoad,\n loaderResults,\n pendingError,\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 markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n\n return {\n loaderData,\n errors,\n ...(didAbortFetchLoads || revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n };\n }\n\n function getFetcher(key: string): Fetcher {\n return state.fetchers.get(key) || IDLE_FETCHER;\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,\n opts?: RouterFetchOptions\n ) {\n if (typeof AbortController === \"undefined\") {\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 if (fetchControllers.has(key)) abortFetcher(key);\n\n let matches = matchRoutes(dataRoutes, href, init.basename);\n if (!matches) {\n setFetcherError(key, routeId, new ErrorResponse(404, \"Not Found\", null));\n return;\n }\n\n let { path, submission } = normalizeNavigateOptions(href, opts, true);\n let match = getTargetMatch(matches, path);\n\n if (submission) {\n handleFetcherAction(key, routeId, path, match, submission);\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, [path, match]);\n handleFetcherLoader(key, routeId, path, match);\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 submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action) {\n let { error } = getMethodNotAllowedResult(path);\n setFetcherError(key, routeId, error);\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n ...submission,\n data: existingFetcher && existingFetcher.data,\n };\n state.fetchers.set(key, fetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createRequest(path, abortController.signal, submission);\n fetchControllers.set(key, abortController);\n\n let actionResult = await callLoaderOrAction(\"action\", fetchRequest, match);\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by ou 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 if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n fetchRedirectIds.add(key);\n let loadingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n ...submission,\n data: undefined,\n };\n state.fetchers.set(key, loadingFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n let redirectNavigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location: createLocation(state.location, actionResult.location),\n ...submission,\n };\n await startRedirectNavigation(actionResult, redirectNavigation);\n return;\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n\n if (isDeferredResult(actionResult)) {\n invariant(false, \"defer() is not supported in actions\");\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 = createRequest(\n nextLocation,\n abortController.signal\n );\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(dataRoutes, state.navigation.location, init.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: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n data: actionResult.data,\n ...submission,\n };\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n state,\n matches,\n submission,\n nextLocation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n { [match.route.id]: actionResult.data },\n undefined, // No need to send through errors since we short circuit above\n fetchLoadMatches\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(([staleKey]) => staleKey !== key)\n .forEach(([staleKey]) => {\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n data: existingFetcher && existingFetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(staleKey, revalidatingFetcher);\n fetchControllers.set(staleKey, abortController);\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach(([staleKey]) =>\n fetchControllers.delete(staleKey)\n );\n\n let redirect = findRedirect(results);\n if (redirect) {\n let redirectNavigation = getLoaderRedirect(state, redirect);\n await startRedirectNavigation(redirect, redirectNavigation);\n return;\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: actionResult.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(key, doneFetcher);\n\n let didAbortFetchLoads = 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(state.loaderData, loaderData, matches),\n ...(didAbortFetchLoads ? { 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 ) {\n let existingFetcher = state.fetchers.get(key);\n // Put this fetcher into it's loading state\n let loadingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n data: existingFetcher && existingFetcher.data,\n };\n state.fetchers.set(key, loadingFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createRequest(path, abortController.signal);\n fetchControllers.set(key, abortController);\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match\n );\n\n // Deferred isn't supported or 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 ou 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 // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n let redirectNavigation = getLoaderRedirect(state, result);\n await startRedirectNavigation(result, redirectNavigation);\n return;\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n state.fetchers.delete(key);\n // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -\n // do we need to behave any differently with our non-redirect errors?\n // What if it was a non-redirect Response?\n updateState({\n fetchers: new Map(state.fetchers),\n errors: {\n [boundaryMatch.route.id]: result.error,\n },\n });\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: result.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(key, doneFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\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 redirect: RedirectResult,\n navigation: Navigation,\n replace?: boolean\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n invariant(\n navigation.location,\n \"Expected a location on the redirect navigation\"\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 ? HistoryAction.Replace : HistoryAction.Push;\n await startNavigation(redirectHistoryAction, navigation.location, {\n overrideNavigation: navigation,\n });\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n // Call all navigation loaders and revalidating fetcher loaders in parallel,\n // then slice off the results into separate arrays so we can handle them\n // accordingly\n let results = await Promise.all([\n ...matchesToLoad.map((m) => callLoaderOrAction(\"loader\", request, m)),\n ...fetchersToLoad.map(([, href, match]) =>\n callLoaderOrAction(\"loader\", createRequest(href, request.signal), match)\n ),\n ]);\n let loaderResults = results.slice(0, matchesToLoad.length);\n let fetcherResults = results.slice(matchesToLoad.length);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n request.signal,\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map(([, , match]) => match),\n fetcherResults,\n request.signal,\n true\n ),\n ]);\n\n return { results, loaderResults, fetcherResults };\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.push(key);\n abortFetcher(key);\n }\n });\n }\n\n function setFetcherError(key: string, routeId: string, error: any) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState({\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n });\n }\n\n function deleteFetcher(key: string): void {\n if (fetchControllers.has(key)) abortFetcher(key);\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n state.fetchers.delete(key);\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: fetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): void {\n let doneKeys = [];\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 }\n }\n markFetchersDone(doneKeys);\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 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 component\n function enableScrollRestoration(\n positions: Record,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || ((location) => location.key);\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered \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 saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n let userMatches = matches.map((m) =>\n createUseMatchesMatch(m, state.loaderData)\n );\n let key = getScrollRestorationKey(location, userMatches) || location.key;\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n let userMatches = matches.map((m) =>\n createUseMatchesMatch(m, state.loaderData)\n );\n let key = getScrollRestorationKey(location, userMatches) || location.key;\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n router = {\n get basename() {\n return init.basename;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n createHref,\n getFetcher,\n deleteFetcher,\n dispose,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport function unstable_createStaticHandler(\n routes: AgnosticRouteObject[]\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to unstable_createStaticHandler\"\n );\n\n let dataRoutes = convertRoutesToDataRoutes(routes);\n\n async function query(\n request: Request\n ): Promise {\n let { location, result } = await queryImpl(request);\n if (result instanceof Response) {\n return result;\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, ...result };\n }\n\n async function queryRoute(request: Request, routeId: string): Promise {\n let { result } = await queryImpl(request, routeId);\n if (result instanceof Response) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // While we always re-throw Responses returned from loaders/actions\n // directly for route requests and prevent the unwrapping into an\n // ErrorResponse, we still need this for error cases _prior_ the\n // execution of the loader/action, such as a 404/405 error.\n if (isRouteErrorResponse(error)) {\n return new Response(error.data, {\n status: error.status,\n statusText: error.statusText,\n });\n }\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 let routeData = [result.actionData, result.loaderData].find((v) => v);\n let value = Object.values(routeData || {})[0];\n\n if (isRouteErrorResponse(value)) {\n return new Response(value.data, {\n status: value.status,\n statusText: value.statusText,\n });\n }\n\n return value;\n }\n\n async function queryImpl(\n request: Request,\n routeId?: string\n ): Promise<{\n location: Location;\n result: Omit | Response;\n }> {\n invariant(\n request.method !== \"HEAD\",\n \"query()/queryRoute() do not support HEAD requests\"\n );\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n let { location, matches, shortCircuitState } = matchRequest(\n request,\n routeId\n );\n\n try {\n if (shortCircuitState) {\n return { location, result: shortCircuitState };\n }\n\n if (request.method !== \"GET\") {\n let result = await submit(\n request,\n matches,\n getTargetMatch(matches, location),\n routeId != null\n );\n return { location, result };\n }\n\n let result = await loadRouteData(request, matches, routeId != null);\n return {\n location,\n result: {\n ...result,\n actionData: null,\n actionHeaders: {},\n },\n };\n } catch (e) {\n if (e instanceof Response) {\n return { location, result: e };\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n if (!actionMatch.route.action) {\n let href = createHref(new URL(request.url));\n result = getMethodNotAllowedResult(href);\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n true,\n isRouteRequest\n );\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted`);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // calLoaderOrAction, 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.status,\n headers: {\n Location: result.location,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n throw new Error(\"defer() is not supported in actions\");\n }\n\n if (isRouteRequest) {\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: null,\n errors: {\n [boundaryMatch.route.id]: result.error,\n },\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 500,\n loaderHeaders: {},\n actionHeaders: {},\n };\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 };\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 let context = await loadRouteData(request, matches, isRouteRequest, {\n [boundaryMatch.route.id]: result.error,\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 : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n let context = await loadRouteData(request, matches, isRouteRequest);\n\n return {\n ...context,\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n isRouteRequest: boolean,\n pendingActionError?: RouteData\n ): Promise<\n | Omit\n | Response\n > {\n let matchesToLoad = getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n ).filter((m) => m.route.loader);\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0) {\n return {\n matches,\n loaderData: {},\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((m) =>\n callLoaderOrAction(\"loader\", request, m, true, isRouteRequest)\n ),\n ]);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted`);\n }\n\n // Can't do anything with these without the Remix side of things, so just\n // cancel them for now\n results.forEach((result) => {\n if (isDeferredResult(result)) {\n result.deferredData.cancel();\n }\n });\n\n // Process and commit output from loaders\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError\n );\n\n return {\n ...context,\n matches,\n };\n }\n\n function matchRequest(\n req: Request,\n routeId?: string\n ): {\n location: Location;\n matches: AgnosticDataRouteMatch[];\n routeMatch?: AgnosticDataRouteMatch;\n shortCircuitState?: Omit;\n } {\n let url = new URL(req.url);\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location);\n if (matches && routeId) {\n matches = matches.filter((m) => m.route.id === routeId);\n }\n\n // Short circuit with a 404 if we match nothing\n if (!matches) {\n let {\n matches: notFoundMatches,\n route,\n error,\n } = getNotFoundMatches(dataRoutes);\n return {\n location,\n matches: notFoundMatches,\n shortCircuitState: {\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: 404,\n loaderHeaders: {},\n actionHeaders: {},\n },\n };\n }\n\n return { location, matches };\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: 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\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 to: To,\n opts?: RouterNavigateOptions,\n isFetcher = false\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponse;\n} {\n let path = typeof to === \"string\" ? to : createPath(to);\n\n // Return location verbatim on non-submission navigations\n if (!opts || (!(\"formMethod\" in opts) && !(\"formData\" in opts))) {\n return { path };\n }\n\n // Create a Submission on non-GET navigations\n if (opts.formMethod != null && opts.formMethod !== \"get\") {\n return {\n path,\n submission: {\n formMethod: opts.formMethod,\n formAction: createHref(parsePath(path)),\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData: opts.formData,\n },\n };\n }\n\n // No formData to flatten for GET submission\n if (!opts.formData) {\n return { path };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n try {\n let searchParams = convertFormDataToSearchParams(opts.formData);\n // Since fetcher GET submissions only run a single loader (as opposed to\n // navigation GET submissions which run all loaders), we need to preserve\n // any incoming ?index params\n if (\n isFetcher &&\n parsedPath.search &&\n hasNakedIndexQuery(parsedPath.search)\n ) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n } catch (e) {\n return {\n path,\n error: new ErrorResponse(\n 400,\n \"Bad Request\",\n \"Cannot submit binary form data using GET\"\n ),\n };\n }\n\n return { path: createPath(parsedPath) };\n}\n\nfunction getLoaderRedirect(\n state: RouterState,\n redirect: RedirectResult\n): Navigation {\n let { formMethod, formAction, formEncType, formData } = state.navigation;\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location: createLocation(state.location, redirect.location),\n formMethod: formMethod || undefined,\n formAction: formAction || undefined,\n formEncType: formEncType || undefined,\n formData: formData || undefined,\n };\n return navigation;\n}\n\n// Filter out all routes 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) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n pendingActionData?: RouteData,\n pendingError?: RouteData,\n fetchLoadMatches?: Map\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : null;\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n let navigationMatches = boundaryMatches.filter(\n (match, index) =>\n match.route.loader != null &&\n (isNewLoader(state.loaderData, state.matches[index], match) ||\n // If this route had a pending deferred cancelled it must be revalidated\n cancelledDeferredRoutes.some((id) => id === match.route.id) ||\n shouldRevalidateLoader(\n state.location,\n state.matches[index],\n submission,\n location,\n match,\n isRevalidationRequired,\n actionResult\n ))\n );\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches &&\n fetchLoadMatches.forEach(([href, match], key) => {\n // This fetcher was cancelled from a prior action submission - force reload\n if (cancelledFetcherLoads.includes(key)) {\n revalidatingFetchers.push([key, href, match]);\n } else if (isRevalidationRequired) {\n let shouldRevalidate = shouldRevalidateLoader(\n href,\n match,\n submission,\n href,\n match,\n isRevalidationRequired,\n actionResult\n );\n if (shouldRevalidate) {\n revalidatingFetchers.push([key, href, match]);\n }\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\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 &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n currentLocation: string | Location,\n currentMatch: AgnosticDataRouteMatch,\n submission: Submission | undefined,\n location: string | Location,\n match: AgnosticDataRouteMatch,\n isRevalidationRequired: boolean,\n actionResult: DataResult | undefined\n) {\n let currentUrl = createURL(currentLocation);\n let currentParams = currentMatch.params;\n let nextUrl = createURL(location);\n let nextParams = match.params;\n\n // This is the default implementation as to 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 // Note that fetchers always provide the same current/next locations so the\n // URL-based checks here don't apply to fetcher shouldRevalidate calls\n let defaultShouldRevalidate =\n isNewRouteInstance(currentMatch, match) ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.toString() === nextUrl.toString() ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate\n isRevalidationRequired;\n\n if (match.route.shouldRevalidate) {\n let routeChoice = match.route.shouldRevalidate({\n currentUrl,\n currentParams,\n nextUrl,\n nextParams,\n ...submission,\n actionResult,\n defaultShouldRevalidate,\n });\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return defaultShouldRevalidate;\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n skipRedirects: boolean = false,\n isRouteRequest: boolean = false\n): Promise {\n let resultType;\n let result;\n\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n let abortPromise = new Promise((_, r) => (reject = r));\n let onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n\n try {\n let handler = match.route[type];\n invariant(\n handler,\n `Could not find the ${type} to run on the \"${match.route.id}\" route`\n );\n\n result = await Promise.race([\n handler({ request, params: match.params }),\n abortPromise,\n ]);\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n\n if (result instanceof Response) {\n // Process redirects\n let status = result.status;\n let location = result.headers.get(\"Location\");\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping\n if (isRouteRequest) {\n throw result;\n }\n\n if (status >= 300 && status <= 399 && location != null) {\n // Don't process redirects in the router during SSR document requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect\n if (skipRedirects) {\n throw result;\n }\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n };\n }\n\n let data: any;\n let contentType = result.headers.get(\"Content-Type\");\n if (contentType && contentType.startsWith(\"application/json\")) {\n data = await result.json();\n } else {\n data = await result.text();\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponse(status, result.statusText, data),\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 (resultType === ResultType.error) {\n return { type: resultType, error: result };\n }\n\n if (result instanceof DeferredData) {\n return { type: ResultType.deferred, deferredData: result };\n }\n\n return { type: ResultType.data, data: result };\n}\n\nfunction createRequest(\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = createURL(location).toString();\n let init: RequestInit = { signal };\n\n if (submission) {\n let { formMethod, formEncType, formData } = submission;\n init.method = formMethod.toUpperCase();\n init.body =\n formEncType === \"application/x-www-form-urlencoded\"\n ? convertFormDataToSearchParams(formData)\n : formData;\n }\n\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\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 invariant(\n typeof value === \"string\",\n 'File inputs are not supported with encType \"application/x-www-form-urlencoded\", ' +\n 'please use \"multipart/form-data\" instead.'\n );\n searchParams.append(key, value);\n }\n\n return searchParams;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n activeDeferreds?: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\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 = {};\n\n // Process loader results into state.loaderData/state.errors\n results.forEach((result, index) => {\n let id = matchesToLoad[index].route.id;\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n // Look upwards from the matched route for the closest ancestor\n // error boundary, defaulting to the root match\n let boundaryMatch = findNearestBoundary(matches, id);\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) {\n error = Object.values(pendingError)[0];\n pendingError = undefined;\n }\n errors = Object.assign(errors || {}, {\n [boundaryMatch.route.id]: error,\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 if (isDeferredResult(result)) {\n activeDeferreds && activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n // TODO: Add statusCode/headers once we wire up streaming in Remix\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 (\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 }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here\n if (pendingError) {\n errors = pendingError;\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 matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingError,\n activeDeferreds\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let [key, , match] = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n 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 throw new Error(\"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 throw new Error(\"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: result.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\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): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n matches.forEach((match) => {\n let id = match.route.id;\n if (newLoaderData[id] === undefined && loaderData[id] !== undefined) {\n mergedLoaderData[id] = loaderData[id];\n }\n });\n return mergedLoaderData;\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 getNotFoundMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n error: ErrorResponse;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route = routes.find(\n (r) => r.index || r.path === \"\" || r.path === \"/\"\n ) || {\n id: \"__shim-404-route__\",\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n error: new ErrorResponse(404, \"Not Found\", null),\n };\n}\n\nfunction getMethodNotAllowedResult(path: Location | string): ErrorResult {\n let href = typeof path === \"string\" ? path : createHref(path);\n console.warn(\n \"You're trying to submit to a route that does not have an action. To \" +\n \"fix this, please add an `action` function to the route for \" +\n `[${href}]`\n );\n return {\n type: ResultType.error,\n error: new ErrorResponse(\n 405,\n \"Method Not Allowed\",\n `No action found for [${href}]`\n ),\n };\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(results: DataResult[]): RedirectResult | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return result;\n }\n }\n}\n\n// Create an href to represent a \"server\" URL without the hash\nfunction createHref(location: Partial | Location | URL) {\n return (location.pathname || \"\") + (location.search || \"\");\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n return (\n a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash\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\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n signal: AbortSignal,\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\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) && (isFetcher || 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, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\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\n// Note: This should match the format exported by useMatches, so if you change\n// this please also change that :) Eventually we'll DRY this up\nfunction createUseMatchesMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UseMatchesMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id] as unknown,\n handle: route.handle as unknown,\n };\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 matches.slice(-2)[0];\n }\n return matches.slice(-1)[0];\n}\n\nfunction createURL(location: Location | string): URL {\n let base =\n typeof window !== \"undefined\" && typeof window.location !== \"undefined\"\n ? window.location.origin\n : \"unknown://unknown\";\n let href = typeof location === \"string\" ? location : createHref(location);\n return new URL(href, base);\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","history","createHref","createPath","push","Push","nextLocation","splice","replace","Replace","go","delta","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","search","hash","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","parsePath","substr","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","cond","message","console","warn","Error","e","createKey","random","toString","getHistoryState","current","path","parsedPath","searchIndex","getLocation","validateLocation","defaultView","handlePop","historyState","pushState","error","assign","replaceState","addEventListener","removeEventListener","ResultType","isIndexRoute","route","convertRoutesToDataRoutes","routes","parentPath","allIds","Set","treePath","id","join","invariant","children","has","add","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","i","matchRouteBranch","parentsMeta","forEach","meta","relativePath","caseSensitive","childrenIndex","startsWith","joinPaths","routesMeta","concat","score","computeScore","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","segments","split","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","match","matchPath","Object","params","pathnameBase","normalizePathname","generatePath","_","prefix","__","str","star","pattern","matcher","paramNames","compilePath","captureGroups","memo","paramName","splatValue","safelyDecodeURIComponent","endsWith","regexpSource","RegExp","value","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","resolvePathname","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","includes","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","data","init","responseInit","status","headers","Headers","set","Response","AbortedDeferredError","DeferredData","constructor","pendingKeys","subscriber","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","trackPromise","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","done","subscribe","cancel","abort","v","k","resolveData","resolve","size","unwrappedData","unwrapTrackedPromise","isTrackedPromise","_tracked","_error","_data","defer","redirect","ErrorResponse","statusText","isRouteErrorResponse","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","IDLE_FETCHER","createRouter","dataRoutes","unlistenHistory","subscribers","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","initialMatches","initialErrors","getNotFoundMatches","initialized","m","loader","hydrationData","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","loaderData","actionData","errors","fetchers","Map","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeDeferreds","initialize","startNavigation","dispose","clear","deleteFetcher","updateState","newState","completeNavigation","isActionReload","newLoaderData","mergeLoaderData","getSavedScrollPosition","navigate","opts","submission","normalizeNavigateOptions","pendingError","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","loadingNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","request","createRequest","pendingActionData","findNearestBoundary","actionOutput","handleAction","shortCircuited","pendingActionError","handleLoaders","result","actionMatch","getTargetMatch","getMethodNotAllowedResult","callLoaderOrAction","isRedirectResult","redirectNavigation","startRedirectNavigation","isErrorResult","boundaryMatch","isDeferredResult","matchesToLoad","revalidatingFetchers","getMatchesToLoad","routeId","fetcher","revalidatingFetcher","results","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","getLoaderRedirect","processLoaderData","deferredData","markFetchRedirectsDone","didAbortFetchLoads","abortStaleFetchLoads","getFetcher","fetch","abortFetcher","setFetcherError","handleFetcherAction","handleFetcherLoader","existingFetcher","abortController","fetchRequest","actionResult","loadingFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","redirectHistoryAction","currentMatches","fetchersToLoad","all","resolveDeferredResults","markFetchersDone","keys","doneKeys","landedId","yeetedKeys","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","userMatches","createUseMatchesMatch","_internalFetchControllers","_internalActiveDeferreds","unstable_createStaticHandler","query","queryImpl","queryRoute","values","routeData","find","method","shortCircuitState","matchRequest","submit","loadRouteData","actionHeaders","isRouteRequest","URL","Location","statusCode","loaderHeaders","context","getLoaderMatchesUntilBoundary","processRouteLoaderData","req","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","isFetcher","searchParams","convertFormDataToSearchParams","hasNakedIndexQuery","append","boundaryId","boundaryMatches","findIndex","navigationMatches","isNewLoader","shouldRevalidateLoader","shouldRevalidate","currentLoaderData","currentMatch","isNew","isMissingData","isNewRouteInstance","currentPath","currentLocation","currentUrl","createURL","currentParams","nextUrl","nextParams","defaultShouldRevalidate","routeChoice","type","skipRedirects","resultType","onReject","handler","contentType","text","deferred","toUpperCase","body","Request","URLSearchParams","foundError","mergedLoaderData","eligibleMatches","reverse","hasErrorBoundary","isRevalidatingLoader","unwrap","getAll","handle","origin"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;;AAEA;AACA;AACA;AACYA,wBAAZ;AAwBA;AACA;AACA;;WA1BYA;EAAAA;EAAAA;EAAAA;AAAAA,CAAAA,EAAAA,mBAAAA;;AAkKZ,MAAMC,iBAAiB,GAAG,UAA1B;AAGA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAqBA;AACA;AACA;AACA;AACO,S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C,IACA,CAACwb,kBAAkB,CAAChZ,MAAM,IAAI,EAAX,CAFrB,EAGE;IACA,OAAOqE,OAAO,CAACnD,KAAR,CAAc,CAAC,CAAf,CAAA,CAAkB,CAAlB,CAAP,CAAA;AACD,GAAA;;EACD,OAAOmD,OAAO,CAACnD,KAAR,CAAc,CAAC,CAAf,CAAA,CAAkB,CAAlB,CAAP,CAAA;AACD,CAAA;;AAED,SAAS+Y,SAAT,CAAmBzb,QAAnB,EAAqD;EACnD,IAAIkC,IAAI,GACN,OAAOZ,MAAP,KAAkB,WAAlB,IAAiC,OAAOA,MAAM,CAACtB,QAAd,KAA2B,WAA5D,GACIsB,MAAM,CAACtB,QAAP,CAAgBod,MADpB,GAEI,mBAHN,CAAA;AAIA,EAAA,IAAI/a,IAAI,GAAG,OAAOrC,QAAP,KAAoB,QAApB,GAA+BA,QAA/B,GAA0CQ,UAAU,CAACR,QAAD,CAA/D,CAAA;AACA,EAAA,OAAO,IAAI0Z,GAAJ,CAAQrX,IAAR,EAAcH,IAAd,CAAP,CAAA;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@remix-run/router/dist/router.d.ts b/node_modules/@remix-run/router/dist/router.d.ts deleted file mode 100644 index e719318e..00000000 --- a/node_modules/@remix-run/router/dist/router.d.ts +++ /dev/null @@ -1,357 +0,0 @@ -import type { History, Location, To } from "./history"; -import { Action as HistoryAction } from "./history"; -import type { AgnosticDataRouteMatch, AgnosticDataRouteObject, FormEncType, FormMethod, RouteData, AgnosticRouteObject, AgnosticRouteMatch } from "./utils"; -import { DeferredData } from "./utils"; -/** - * 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 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 - * - * 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, 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): void; - /** - * Navigate to the given path - * @param to Path to navigate to - * @param opts Navigation options (method, submission, etc.) - */ - navigate(to: To, opts?: RouterNavigateOptions): 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, opts?: RouterNavigateOptions): 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 - * - * Get/create a fetcher for the given key - * @param key - */ - getFetcher(key?: string): Fetcher; - /** - * @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 - * - * Internal fetch AbortControllers accessed by unit tests - */ - _internalFetchControllers: Map; - /** - * @internal - * PRIVATE - DO NOT USE - * - * Internal pending DeferredData instances accessed by unit tests - */ - _internalActiveDeferreds: Map; -} -/** - * 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; -} -/** - * Data that can be passed into hydrate a Router from SSR - */ -export declare type HydrationState = Partial>; -/** - * Initialization options for createRouter - */ -export interface RouterInit { - basename?: string; - routes: AgnosticRouteObject[]; - history: History; - hydrationData?: HydrationState; -} -/** - * State returned from a server-side query() call - */ -export interface StaticHandlerContext { - location: RouterState["location"]; - matches: RouterState["matches"]; - loaderData: RouterState["loaderData"]; - actionData: RouterState["actionData"]; - errors: RouterState["errors"]; - statusCode: number; - loaderHeaders: Record; - actionHeaders: Record; - _deepestRenderedBoundaryId?: string | null; -} -/** - * A StaticHandler instance manages a singular SSR navigation/fetch event - */ -export interface StaticHandler { - dataRoutes: AgnosticDataRouteObject[]; - query(request: Request): Promise; - queryRoute(request: Request, routeId?: string): Promise; -} -/** - * Subscriber function signature for changes to router state - */ -export interface RouterSubscriber { - (state: RouterState): void; -} -interface UseMatchesMatch { - id: string; - pathname: string; - params: AgnosticRouteMatch["params"]; - data: unknown; - handle: unknown; -} -/** - * Function signature for determining the key to be used in scroll restoration - * for a given location - */ -export interface GetScrollRestorationKeyFunction { - (location: Location, matches: UseMatchesMatch[]): string | null; -} -/** - * Function signature for determining the current scroll position - */ -export interface GetScrollPositionFunction { - (): number; -} -/** - * Options for a navigate() call for a Link navigation - */ -declare type LinkNavigateOptions = { - replace?: boolean; - state?: any; - preventScrollReset?: boolean; -}; -/** - * Options for a navigate() call for a Form navigation - */ -declare type SubmissionNavigateOptions = { - replace?: boolean; - state?: any; - formMethod?: FormMethod; - formEncType?: FormEncType; - formData: FormData; -}; -/** - * Options to pass to navigate() for either a Link or Form navigation - */ -export declare type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions; -/** - * Options to pass to fetch() - */ -export declare type RouterFetchOptions = Omit | Omit; -/** - * Potential states for state.navigation - */ -export declare type NavigationStates = { - Idle: { - state: "idle"; - location: undefined; - formMethod: undefined; - formAction: undefined; - formEncType: undefined; - formData: undefined; - }; - Loading: { - state: "loading"; - location: Location; - formMethod: FormMethod | undefined; - formAction: string | undefined; - formEncType: FormEncType | undefined; - formData: FormData | undefined; - }; - Submitting: { - state: "submitting"; - location: Location; - formMethod: FormMethod; - formAction: string; - formEncType: FormEncType; - formData: FormData; - }; -}; -export declare type Navigation = NavigationStates[keyof NavigationStates]; -export declare type RevalidationState = "idle" | "loading"; -/** - * Potential states for fetchers - */ -declare type FetcherStates = { - Idle: { - state: "idle"; - formMethod: undefined; - formAction: undefined; - formEncType: undefined; - formData: undefined; - data: TData | undefined; - }; - Loading: { - state: "loading"; - formMethod: FormMethod | undefined; - formAction: string | undefined; - formEncType: FormEncType | undefined; - formData: FormData | undefined; - data: TData | undefined; - }; - Submitting: { - state: "submitting"; - formMethod: FormMethod; - formAction: string; - formEncType: FormEncType; - formData: FormData; - data: TData | undefined; - }; -}; -export declare type Fetcher = FetcherStates[keyof FetcherStates]; -export declare const IDLE_NAVIGATION: NavigationStates["Idle"]; -export declare const IDLE_FETCHER: FetcherStates["Idle"]; -/** - * Create a router and listen to history POP navigations - */ -export declare function createRouter(init: RouterInit): Router; -export declare function unstable_createStaticHandler(routes: AgnosticRouteObject[]): StaticHandler; -/** - * Given an existing StaticHandlerContext and an error thrown at render time, - * provide an updated StaticHandlerContext suitable for a second SSR render - */ -export declare function getStaticContextFromError(routes: AgnosticDataRouteObject[], context: StaticHandlerContext, error: any): StaticHandlerContext; -export {}; diff --git a/node_modules/@remix-run/router/dist/router.js b/node_modules/@remix-run/router/dist/router.js deleted file mode 100644 index bc6ab99e..00000000 --- a/node_modules/@remix-run/router/dist/router.js +++ /dev/null @@ -1,3177 +0,0 @@ -/** - * @remix-run/router v1.0.2 - * - * 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() { - _extends = Object.assign ? Object.assign.bind() : function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - return _extends.apply(this, arguments); -} - -//////////////////////////////////////////////////////////////////////////////// -//#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$1(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to)); - return location; - } - - let history = { - get index() { - return index; - }, - - get action() { - return action; - }, - - get location() { - return getCurrentLocation(); - }, - - createHref(to) { - return typeof to === "string" ? to : createPath(to); - }, - - 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 - }); - } - }, - - replace(to, state) { - action = Action.Replace; - let nextLocation = createMemoryLocation(to, state); - entries[index] = nextLocation; - - if (v5Compat && listener) { - listener({ - action, - location: nextLocation - }); - } - }, - - go(delta) { - action = Action.Pop; - index = clampIndex(index + delta); - - if (listener) { - listener({ - action, - location: getCurrentLocation() - }); - } - }, - - 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)); - 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$1(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 -//////////////////////////////////////////////////////////////////////////////// - -function warning$1(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) { - return { - usr: location.state, - key: location.key - }; -} -/** - * 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; - - function handlePop() { - action = Action.Pop; - - if (listener) { - listener({ - action, - location: history.location - }); - } - } - - function push(to, state) { - action = Action.Push; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - let historyState = getHistoryState(location); - let url = history.createHref(location); // try...catch because iOS limits us to 100 pushState calls :/ - - try { - globalHistory.pushState(historyState, "", url); - } catch (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 - }); - } - } - - function replace(to, state) { - action = Action.Replace; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - let historyState = getHistoryState(location); - let url = history.createHref(location); - globalHistory.replaceState(historyState, "", url); - - if (v5Compat && listener) { - listener({ - action, - location: location - }); - } - } - - 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); - }, - - 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 = {})); - -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, parentPath, allIds) { - if (parentPath === void 0) { - parentPath = []; - } - - if (allIds === void 0) { - allIds = new Set(); - } - - return routes.map((route, index) => { - let treePath = [...parentPath, index]; - let id = typeof route.id === "string" ? route.id : treePath.join("-"); - invariant(route.index !== true || !route.children, "Cannot specify children on an index route"); - invariant(!allIds.has(id), "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages"); - allIds.add(id); - - if (isIndexRoute(route)) { - let indexRoute = _extends({}, route, { - id - }); - - return indexRoute; - } else { - let pathOrLayoutRoute = _extends({}, route, { - id, - children: route.children ? convertRoutesToDataRoutes(route.children, treePath, allIds) : undefined - }); - - return pathOrLayoutRoute; - } - }); -} -/** - * Matches the given routes to a location and returns the match data. - * - * @see https://reactrouter.com/docs/en/v6/utils/match-routes - */ - -function matchRoutes(routes, locationArg, basename) { - if (basename === void 0) { - basename = "/"; - } - - let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg; - let pathname = stripBasename(location.pathname || "/", basename); - - if (pathname == null) { - return null; - } - - let branches = flattenRoutes(routes); - rankRouteBranches(branches); - let matches = null; - - for (let i = 0; matches == null && i < branches.length; ++i) { - matches = matchRouteBranch(branches[i], pathname); - } - - return matches; -} - -function flattenRoutes(routes, branches, parentsMeta, parentPath) { - if (branches === void 0) { - branches = []; - } - - if (parentsMeta === void 0) { - parentsMeta = []; - } - - if (parentPath === void 0) { - parentPath = ""; - } - - routes.forEach((route, index) => { - let meta = { - relativePath: route.path || "", - 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 - }); - }); - return branches; -} - -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) { - let { - routesMeta - } = branch; - let matchedParams = {}; - let matchedPathname = "/"; - let matches = []; - - for (let i = 0; i < routesMeta.length; ++i) { - let meta = routesMeta[i]; - let end = i === routesMeta.length - 1; - let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/"; - let match = matchPath({ - path: meta.relativePath, - caseSensitive: meta.caseSensitive, - end - }, remainingPathname); - if (!match) return null; - Object.assign(matchedParams, match.params); - let route = meta.route; - matches.push({ - // TODO: Can this as be avoided? - params: matchedParams, - pathname: joinPaths([matchedPathname, match.pathname]), - pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])), - route - }); - - if (match.pathnameBase !== "/") { - matchedPathname = joinPaths([matchedPathname, match.pathnameBase]); - } - } - - return matches; -} -/** - * Returns a path with params interpolated. - * - * @see https://reactrouter.com/docs/en/v6/utils/generate-path - */ - - -function generatePath(path, params) { - if (params === void 0) { - params = {}; - } - - return path.replace(/:(\w+)/g, (_, key) => { - invariant(params[key] != null, "Missing \":" + key + "\" param"); - return params[key]; - }).replace(/(\/?)\*/, (_, prefix, __, str) => { - const star = "*"; - - if (params[star] == null) { - // If no splat was provided, trim the trailing slash _unless_ it's - // the entire path - return str === "/*" ? "/" : ""; - } // Apply the splat - - - return "" + prefix + params[star]; - }); -} -/** - * Performs pattern matching on a URL pathname and returns information about - * the match. - * - * @see https://reactrouter.com/docs/en/v6/utils/match-path - */ - -function matchPath(pattern, pathname) { - if (typeof pattern === "string") { - pattern = { - path: pattern, - caseSensitive: false, - end: true - }; - } - - let [matcher, paramNames] = 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 = paramNames.reduce((memo, paramName, 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"); - } - - memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || "", paramName); - return memo; - }, {}); - return { - params, - pathname: matchedPathname, - pathnameBase, - pattern - }; -} - -function compilePath(path, caseSensitive, end) { - if (caseSensitive === void 0) { - caseSensitive = false; - } - - if (end === void 0) { - end = true; - } - - warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); - let paramNames = []; - 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) => { - paramNames.push(paramName); - return "([^\\/]+)"; - }); - - if (path.endsWith("*")) { - paramNames.push("*"); - 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, paramNames]; -} - -function safelyDecodeURIComponent(value, paramName) { - try { - return decodeURIComponent(value); - } catch (error) { - warning(false, "The value for the URL param \"" + paramName + "\" will not be decoded because" + (" the string \"" + value + "\" is a malformed URL segment. This is probably") + (" due to a bad percent encoding (" + error + ").")); - return value; - } -} -/** - * @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) || "/"; -} -function invariant(value, message) { - if (value === false || value === null || typeof value === "undefined") { - throw new Error(message); - } -} -/** - * @private - */ - -function warning(cond, message) { - if (!cond) { - // eslint-disable-next-line no-console - if (typeof console !== "undefined") console.warn(message); - - try { - // Welcome to debugging React Router! - // - // 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) {} - } -} -/** - * Returns a resolved path object relative to the given pathname. - * - * @see https://reactrouter.com/docs/en/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 = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname; - return { - pathname, - search: normalizeSearch(search), - hash: normalizeHash(hash) - }; -} - -function resolvePathname(relativePath, fromPathname) { - let segments = fromPathname.replace(/\/+$/, "").split("/"); - let relativeSegments = relativePath.split("/"); - relativeSegments.forEach(segment => { - if (segment === "..") { - // 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 and the router will parse it for you."; -} -/** - * @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 `` 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 (isPathRelative || toPathname == null) { - from = locationPathname; - } else { - let routePathnameIndex = routePathnames.length - 1; - - if (toPathname.startsWith("..")) { - let toSegments = toPathname.split("/"); // Each leading .. segment means "go up one route" instead of "go up one - // URL segment". This is a key difference from how works and a - // major reason we call this a "to" value instead of a "href". - - while (toSegments[0] === "..") { - toSegments.shift(); - routePathnameIndex -= 1; - } - - to.pathname = toSegments.join("/"); - } // If there are more ".." segments than parent routes, resolve relative to - // the root / URL. - - - 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; -} -/** - * @private - */ - -const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/"); -/** - * @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. - */ - -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 AbortedDeferredError extends Error {} -class DeferredData { - constructor(data) { - this.pendingKeys = new Set(); - this.subscriber = undefined; - 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, _ref) => { - let [key, value] = _ref; - return Object.assign(acc, { - [key]: this.trackPromise(key, value) - }); - }, {}); - } - - trackPromise(key, value) { - if (!(value instanceof Promise)) { - return value; - } - - this.pendingKeys.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, null, 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.pendingKeys.delete(key); - - if (this.done) { - // Nothing left to abort! - this.unlistenAbortSignal(); - } - - const subscriber = this.subscriber; - - if (error) { - Object.defineProperty(promise, "_error", { - get: () => error - }); - subscriber && subscriber(false); - return Promise.reject(error); - } - - Object.defineProperty(promise, "_data", { - get: () => data - }); - subscriber && subscriber(false); - return data; - } - - subscribe(fn) { - this.subscriber = fn; - } - - cancel() { - this.controller.abort(); - this.pendingKeys.forEach((v, k) => this.pendingKeys.delete(k)); - let subscriber = this.subscriber; - subscriber && subscriber(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.pendingKeys.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, _ref2) => { - let [key, value] = _ref2; - return Object.assign(acc, { - [key]: unwrapTrackedPromise(value) - }); - }, {}); - } - -} - -function isTrackedPromise(value) { - return value instanceof Promise && value._tracked === true; -} - -function unwrapTrackedPromise(value) { - if (!isTrackedPromise(value)) { - return value; - } - - if (value._error) { - throw value._error; - } - - return value._data; -} - -function defer(data) { - return new DeferredData(data); -} -/** - * 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 - })); -}; -/** - * @private - * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies - */ - -class ErrorResponse { - constructor(status, statusText, data) { - this.status = status; - this.statusText = statusText || ""; - this.data = data; - } - -} -/** - * Check if the given error is an ErrorResponse generated from a 4xx/5xx - * Response throw from an action/loader - */ - -function isRouteErrorResponse(e) { - return e instanceof ErrorResponse; -} - -const IDLE_NAVIGATION = { - state: "idle", - location: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined -}; -const IDLE_FETCHER = { - state: "idle", - data: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined -}; //#endregion -//////////////////////////////////////////////////////////////////////////////// -//#region createRouter -//////////////////////////////////////////////////////////////////////////////// - -/** - * Create a router and listen to history POP navigations - */ - -function createRouter(init) { - invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter"); - let dataRoutes = convertRoutesToDataRoutes(init.routes); // 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 until _after_ - // the initial render, we need to manually trigger a separate updateState to - // send along the restoreScrollPosition - - let initialScrollRestored = false; - let initialMatches = matchRoutes(dataRoutes, init.history.location, init.basename); - let initialErrors = null; - - if (initialMatches == null) { - // If we do not match a user-provided-route, fall back to the root - // to allow the error boundary to take over - let { - matches, - route, - error - } = getNotFoundMatches(dataRoutes); - initialMatches = matches; - initialErrors = { - [route.id]: error - }; - } - - let initialized = !initialMatches.some(m => m.route.loader) || init.hydrationData != null; - let router; - let state = { - historyAction: init.history.action, - location: init.history.location, - matches: initialMatches, - initialized, - navigation: IDLE_NAVIGATION, - restoreScrollPosition: 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() - }; // -- 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; // 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) - // - useRevalidate() - // - 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 = []; // 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 from their actions - - let fetchRedirectIds = new Set(); // Most recent href/match for fetcher.load calls for fetchers - - let fetchLoadMatches = new Map(); // 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(); // 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 - } = _ref; - return startNavigation(historyAction, location); - }); // Kick off initial data load if needed. Use Pop to avoid modifying history - - if (!state.initialized) { - startNavigation(Action.Pop, state.location); - } - - return router; - } // Clean up a router and it's side effects - - - function dispose() { - if (unlistenHistory) { - unlistenHistory(); - } - - subscribers.clear(); - pendingNavigationController && pendingNavigationController.abort(); - state.fetchers.forEach((_, key) => deleteFetcher(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) { - state = _extends({}, state, newState); - subscribers.forEach(subscriber => subscriber(state)); - } // 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) { - var _state$navigation$for; - - // Deduce if we're in a loading/actionReload state: - // - We have committed actionData in the store - // - The current navigation was a submission - // - We're past the submitting state and into the loading state - // - The location we've finished loading is different from the submission - // location, indicating we redirected from the action (avoids false - // positives for loading/submissionRedirect when actionData returned - // on a prior submission) - let isActionReload = state.actionData != null && state.navigation.formMethod != null && state.navigation.state === "loading" && ((_state$navigation$for = state.navigation.formAction) == null ? void 0 : _state$navigation$for.split("?")[0]) === location.pathname; // Always preserve any existing loaderData from re-used routes - - let newLoaderData = newState.loaderData ? { - loaderData: mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || []) - } : {}; - updateState(_extends({}, isActionReload ? {} : { - actionData: null - }, newState, newLoaderData, { - historyAction: pendingAction, - location, - initialized: true, - navigation: IDLE_NAVIGATION, - revalidation: "idle", - // Don't restore on submission navigations - restoreScrollPosition: state.navigation.formData ? false : getSavedScrollPosition(location, newState.matches || state.matches), - preventScrollReset: pendingPreventScrollReset - })); - - 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); - } // Reset stateful navigation vars - - - pendingAction = Action.Pop; - pendingPreventScrollReset = false; - isUninterruptedRevalidation = false; - isRevalidationRequired = false; - cancelledDeferredRoutes = []; - cancelledFetcherLoads = []; - } // 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 { - path, - submission, - error - } = normalizeNavigateOptions(to, opts); - let location = createLocation(state.location, path, opts && opts.state); - let historyAction = (opts && opts.replace) === true || submission != null ? Action.Replace : Action.Push; - let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined; - return await startNavigation(historyAction, location, { - 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 - }); - } // 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 - }); - } // 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; - let loadingNavigation = opts && opts.overrideNavigation; - let matches = matchRoutes(dataRoutes, location, init.basename); // Short circuit with a 404 on the root error boundary if we match nothing - - if (!matches) { - let { - matches: notFoundMatches, - route, - error - } = getNotFoundMatches(dataRoutes); // Cancel all pending deferred on 404s since we don't keep any routes - - cancelActiveDeferreds(); - completeNavigation(location, { - matches: notFoundMatches, - loaderData: {}, - errors: { - [route.id]: error - } - }); - return; - } // Short circuit if it's only a hash change - - - if (isHashChangeOnly(state.location, location)) { - completeNavigation(location, { - matches - }); - return; - } // Create a controller/Request for this navigation - - - pendingNavigationController = new AbortController(); - let request = createRequest(location, pendingNavigationController.signal, opts && opts.submission); - let pendingActionData; - let pendingError; - - 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. - pendingError = { - [findNearestBoundary(matches).route.id]: opts.pendingError - }; - } else if (opts && opts.submission) { - // Call action if we received an action submission - let actionOutput = await handleAction(request, location, opts.submission, matches, { - replace: opts.replace - }); - - if (actionOutput.shortCircuited) { - return; - } - - pendingActionData = actionOutput.pendingActionData; - pendingError = actionOutput.pendingActionError; - - let navigation = _extends({ - state: "loading", - location - }, opts.submission); - - loadingNavigation = navigation; - } // Call loaders - - - let { - shortCircuited, - loaderData, - errors - } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.replace, pendingActionData, pendingError); - - 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, - loaderData, - errors - }); - } // Call the action matched by the leaf route for this navigation and handle - // redirects/errors - - - async function handleAction(request, location, submission, matches, opts) { - interruptActiveLoads(); // Put us in a submitting state - - let navigation = _extends({ - state: "submitting", - location - }, submission); - - updateState({ - navigation - }); // Call our action and get the result - - let result; - let actionMatch = getTargetMatch(matches, location); - - if (!actionMatch.route.action) { - result = getMethodNotAllowedResult(location); - } else { - result = await callLoaderOrAction("action", request, actionMatch); - - if (request.signal.aborted) { - return { - shortCircuited: true - }; - } - } - - if (isRedirectResult(result)) { - let redirectNavigation = _extends({ - state: "loading", - location: createLocation(state.location, result.location) - }, submission); - - await startRedirectNavigation(result, redirectNavigation, opts && opts.replace); - return { - shortCircuited: true - }; - } - - 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 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 { - pendingActionError: { - [boundaryMatch.route.id]: result.error - } - }; - } - - if (isDeferredResult(result)) { - throw new Error("defer() is not supported in actions"); - } - - return { - pendingActionData: { - [actionMatch.route.id]: result.data - } - }; - } // Call all applicable loaders for the given matches, handling redirects, - // errors, etc. - - - async function handleLoaders(request, location, matches, overrideNavigation, submission, replace, pendingActionData, pendingError) { - // Figure out the right navigation we want to use for data loading - let loadingNavigation = overrideNavigation; - - if (!loadingNavigation) { - let navigation = { - state: "loading", - location, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - loadingNavigation = navigation; - } - - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches); // 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)); // Short circuit if we have no loaders to run - - if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) { - completeNavigation(location, { - matches, - loaderData: mergeLoaderData(state.loaderData, {}, matches), - // Commit pending error if we're short circuiting - errors: pendingError || null, - actionData: pendingActionData || null - }); - return { - shortCircuited: true - }; - } // 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 (!isUninterruptedRevalidation) { - revalidatingFetchers.forEach(_ref2 => { - let [key] = _ref2; - const fetcher = state.fetchers.get(key); - let revalidatingFetcher = { - state: "loading", - data: fetcher && fetcher.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - state.fetchers.set(key, revalidatingFetcher); - }); - updateState(_extends({ - navigation: loadingNavigation, - actionData: pendingActionData || state.actionData || null - }, revalidatingFetchers.length > 0 ? { - fetchers: new Map(state.fetchers) - } : {})); - } - - pendingNavigationLoadId = ++incrementingLoadId; - revalidatingFetchers.forEach(_ref3 => { - let [key] = _ref3; - return fetchControllers.set(key, pendingNavigationController); - }); - let { - results, - 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 - - - revalidatingFetchers.forEach(_ref4 => { - let [key] = _ref4; - return fetchControllers.delete(key); - }); // If any loaders returned a redirect Response, start a new REPLACE navigation - - let redirect = findRedirect(results); - - if (redirect) { - let redirectNavigation = getLoaderRedirect(state, redirect); - await startRedirectNavigation(redirect, redirectNavigation, replace); - return { - shortCircuited: true - }; - } // Process and commit output from loaders - - - let { - loaderData, - errors - } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, 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); - } - }); - }); - markFetchRedirectsDone(); - let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); - return _extends({ - loaderData, - errors - }, didAbortFetchLoads || revalidatingFetchers.length > 0 ? { - fetchers: new Map(state.fetchers) - } : {}); - } - - function getFetcher(key) { - return state.fetchers.get(key) || IDLE_FETCHER; - } // Trigger a fetcher load/submit for the given fetcher key - - - function fetch(key, routeId, href, opts) { - if (typeof AbortController === "undefined") { - throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback."); - } - - if (fetchControllers.has(key)) abortFetcher(key); - let matches = matchRoutes(dataRoutes, href, init.basename); - - if (!matches) { - setFetcherError(key, routeId, new ErrorResponse(404, "Not Found", null)); - return; - } - - let { - path, - submission - } = normalizeNavigateOptions(href, opts, true); - let match = getTargetMatch(matches, path); - - if (submission) { - handleFetcherAction(key, routeId, path, match, submission); - return; - } // Store off the match so we can call it's shouldRevalidate on subsequent - // revalidations - - - fetchLoadMatches.set(key, [path, match]); - handleFetcherLoader(key, routeId, path, match); - } // Call the action for the matched fetcher.submit(), and then handle redirects, - // errors, and revalidation - - - async function handleFetcherAction(key, routeId, path, match, submission) { - interruptActiveLoads(); - fetchLoadMatches.delete(key); - - if (!match.route.action) { - let { - error - } = getMethodNotAllowedResult(path); - setFetcherError(key, routeId, error); - return; - } // Put this fetcher into it's submitting state - - - let existingFetcher = state.fetchers.get(key); - - let fetcher = _extends({ - state: "submitting" - }, submission, { - data: existingFetcher && existingFetcher.data - }); - - state.fetchers.set(key, fetcher); - updateState({ - fetchers: new Map(state.fetchers) - }); // Call the action for the fetcher - - let abortController = new AbortController(); - let fetchRequest = createRequest(path, abortController.signal, submission); - fetchControllers.set(key, abortController); - let actionResult = await callLoaderOrAction("action", fetchRequest, match); - - if (fetchRequest.signal.aborted) { - // We can delete this so long as we weren't aborted by ou our own fetcher - // re-submit which would have put _new_ controller is in fetchControllers - if (fetchControllers.get(key) === abortController) { - fetchControllers.delete(key); - } - - return; - } - - if (isRedirectResult(actionResult)) { - fetchControllers.delete(key); - fetchRedirectIds.add(key); - - let loadingFetcher = _extends({ - state: "loading" - }, submission, { - data: undefined - }); - - state.fetchers.set(key, loadingFetcher); - updateState({ - fetchers: new Map(state.fetchers) - }); - - let redirectNavigation = _extends({ - state: "loading", - location: createLocation(state.location, actionResult.location) - }, submission); - - await startRedirectNavigation(actionResult, redirectNavigation); - return; - } // Process any non-redirect errors thrown - - - if (isErrorResult(actionResult)) { - setFetcherError(key, routeId, actionResult.error); - return; - } - - if (isDeferredResult(actionResult)) { - invariant(false, "defer() is not supported in actions"); - } // 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 = createRequest(nextLocation, abortController.signal); - let matches = state.navigation.state !== "idle" ? matchRoutes(dataRoutes, state.navigation.location, init.basename) : state.matches; - invariant(matches, "Didn't find any matches after fetcher action"); - let loadId = ++incrementingLoadId; - fetchReloadIds.set(key, loadId); - - let loadFetcher = _extends({ - state: "loading", - data: actionResult.data - }, submission); - - state.fetchers.set(key, loadFetcher); - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(state, matches, submission, nextLocation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, { - [match.route.id]: actionResult.data - }, undefined, // No need to send through errors since we short circuit above - fetchLoadMatches); // 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(_ref5 => { - let [staleKey] = _ref5; - return staleKey !== key; - }).forEach(_ref6 => { - let [staleKey] = _ref6; - let existingFetcher = state.fetchers.get(staleKey); - let revalidatingFetcher = { - state: "loading", - data: existingFetcher && existingFetcher.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - state.fetchers.set(staleKey, revalidatingFetcher); - fetchControllers.set(staleKey, abortController); - }); - updateState({ - fetchers: new Map(state.fetchers) - }); - let { - results, - loaderResults, - fetcherResults - } = await callLoadersAndMaybeResolveData(state.matches, matchesToLoad, revalidatingFetchers, revalidationRequest); - - if (abortController.signal.aborted) { - return; - } - - fetchReloadIds.delete(key); - fetchControllers.delete(key); - revalidatingFetchers.forEach(_ref7 => { - let [staleKey] = _ref7; - return fetchControllers.delete(staleKey); - }); - let redirect = findRedirect(results); - - if (redirect) { - let redirectNavigation = getLoaderRedirect(state, redirect); - await startRedirectNavigation(redirect, redirectNavigation); - return; - } // Process and commit output from loaders - - - let { - loaderData, - errors - } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds); - let doneFetcher = { - state: "idle", - data: actionResult.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - state.fetchers.set(key, doneFetcher); - let didAbortFetchLoads = 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(_extends({ - errors, - loaderData: mergeLoaderData(state.loaderData, loaderData, matches) - }, didAbortFetchLoads ? { - 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) { - let existingFetcher = state.fetchers.get(key); // Put this fetcher into it's loading state - - let loadingFetcher = { - state: "loading", - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - data: existingFetcher && existingFetcher.data - }; - state.fetchers.set(key, loadingFetcher); - updateState({ - fetchers: new Map(state.fetchers) - }); // Call the loader for this fetcher route match - - let abortController = new AbortController(); - let fetchRequest = createRequest(path, abortController.signal); - fetchControllers.set(key, abortController); - let result = await callLoaderOrAction("loader", fetchRequest, match); // Deferred isn't supported or 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 ou 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; - } // If the loader threw a redirect Response, start a new REPLACE navigation - - - if (isRedirectResult(result)) { - let redirectNavigation = getLoaderRedirect(state, result); - await startRedirectNavigation(result, redirectNavigation); - return; - } // Process any non-redirect errors thrown - - - if (isErrorResult(result)) { - let boundaryMatch = findNearestBoundary(state.matches, routeId); - state.fetchers.delete(key); // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch - - // do we need to behave any differently with our non-redirect errors? - // What if it was a non-redirect Response? - - updateState({ - fetchers: new Map(state.fetchers), - errors: { - [boundaryMatch.route.id]: result.error - } - }); - return; - } - - invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); // Put the fetcher back into an idle state - - let doneFetcher = { - state: "idle", - data: result.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - state.fetchers.set(key, doneFetcher); - updateState({ - fetchers: new Map(state.fetchers) - }); - } - /** - * 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(redirect, navigation, replace) { - if (redirect.revalidate) { - isRevalidationRequired = true; - } - - invariant(navigation.location, "Expected a location on the redirect navigation"); // 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 ? Action.Replace : Action.Push; - await startNavigation(redirectHistoryAction, navigation.location, { - overrideNavigation: navigation - }); - } - - async function callLoadersAndMaybeResolveData(currentMatches, matchesToLoad, fetchersToLoad, request) { - // Call all navigation loaders and revalidating fetcher loaders in parallel, - // then slice off the results into separate arrays so we can handle them - // accordingly - let results = await Promise.all([...matchesToLoad.map(m => callLoaderOrAction("loader", request, m)), ...fetchersToLoad.map(_ref8 => { - let [, href, match] = _ref8; - return callLoaderOrAction("loader", createRequest(href, request.signal), match); - })]); - let loaderResults = results.slice(0, matchesToLoad.length); - let fetcherResults = results.slice(matchesToLoad.length); - await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, request.signal, false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(_ref9 => { - let [,, match] = _ref9; - return match; - }), fetcherResults, request.signal, true)]); - return { - results, - 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.push(key); - abortFetcher(key); - } - }); - } - - function setFetcherError(key, routeId, error) { - let boundaryMatch = findNearestBoundary(state.matches, routeId); - deleteFetcher(key); - updateState({ - errors: { - [boundaryMatch.route.id]: error - }, - fetchers: new Map(state.fetchers) - }); - } - - function deleteFetcher(key) { - if (fetchControllers.has(key)) abortFetcher(key); - fetchLoadMatches.delete(key); - fetchReloadIds.delete(key); - fetchRedirectIds.delete(key); - state.fetchers.delete(key); - } - - function abortFetcher(key) { - let controller = fetchControllers.get(key); - invariant(controller, "Expected fetch controller: " + key); - controller.abort(); - fetchControllers.delete(key); - } - - function markFetchersDone(keys) { - for (let key of keys) { - let fetcher = getFetcher(key); - let doneFetcher = { - state: "idle", - data: fetcher.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - state.fetchers.set(key, doneFetcher); - } - } - - function markFetchRedirectsDone() { - let doneKeys = []; - - 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); - } - } - - markFetchersDone(doneKeys); - } - - 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 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 component - - - function enableScrollRestoration(positions, getPosition, getKey) { - savedScrollPositions = positions; - getScrollPosition = getPosition; - - getScrollRestorationKey = getKey || (location => location.key); // Perform initial hydration scroll restoration, since we miss the boat on - // the initial updateState() because we've not yet rendered - // 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 saveScrollPosition(location, matches) { - if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) { - let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData)); - let key = getScrollRestorationKey(location, userMatches) || location.key; - savedScrollPositions[key] = getScrollPosition(); - } - } - - function getSavedScrollPosition(location, matches) { - if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) { - let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData)); - let key = getScrollRestorationKey(location, userMatches) || location.key; - let y = savedScrollPositions[key]; - - if (typeof y === "number") { - return y; - } - } - - return null; - } - - router = { - get basename() { - return init.basename; - }, - - get state() { - return state; - }, - - get routes() { - return dataRoutes; - }, - - initialize, - subscribe, - enableScrollRestoration, - navigate, - fetch, - revalidate, - createHref, - getFetcher, - deleteFetcher, - dispose, - _internalFetchControllers: fetchControllers, - _internalActiveDeferreds: activeDeferreds - }; - return router; -} //#endregion -//////////////////////////////////////////////////////////////////////////////// -//#region createStaticHandler -//////////////////////////////////////////////////////////////////////////////// - -function unstable_createStaticHandler(routes) { - invariant(routes.length > 0, "You must provide a non-empty routes array to unstable_createStaticHandler"); - let dataRoutes = convertRoutesToDataRoutes(routes); - - async function query(request) { - let { - location, - result - } = await queryImpl(request); - - if (result instanceof Response) { - 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 - }, result); - } - - async function queryRoute(request, routeId) { - let { - result - } = await queryImpl(request, routeId); - - if (result instanceof Response) { - return result; - } - - let error = result.errors ? Object.values(result.errors)[0] : undefined; - - if (error !== undefined) { - // While we always re-throw Responses returned from loaders/actions - // directly for route requests and prevent the unwrapping into an - // ErrorResponse, we still need this for error cases _prior_ the - // execution of the loader/action, such as a 404/405 error. - if (isRouteErrorResponse(error)) { - return new Response(error.data, { - status: error.status, - statusText: error.statusText - }); - } // 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 - - - let routeData = [result.actionData, result.loaderData].find(v => v); - let value = Object.values(routeData || {})[0]; - - if (isRouteErrorResponse(value)) { - return new Response(value.data, { - status: value.status, - statusText: value.statusText - }); - } - - return value; - } - - async function queryImpl(request, routeId) { - invariant(request.method !== "HEAD", "query()/queryRoute() do not support HEAD requests"); - invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal"); - let { - location, - matches, - shortCircuitState - } = matchRequest(request, routeId); - - try { - if (shortCircuitState) { - return { - location, - result: shortCircuitState - }; - } - - if (request.method !== "GET") { - let result = await submit(request, matches, getTargetMatch(matches, location), routeId != null); - return { - location, - result - }; - } - - let result = await loadRouteData(request, matches, routeId != null); - return { - location, - result: _extends({}, result, { - actionData: null, - actionHeaders: {} - }) - }; - } catch (e) { - if (e instanceof Response) { - return { - location, - result: e - }; - } - - throw e; - } - } - - async function submit(request, matches, actionMatch, isRouteRequest) { - let result; - - if (!actionMatch.route.action) { - let href = createHref(new URL(request.url)); - result = getMethodNotAllowedResult(href); - } else { - result = await callLoaderOrAction("action", request, actionMatch, true, isRouteRequest); - - if (request.signal.aborted) { - let method = isRouteRequest ? "queryRoute" : "query"; - throw new Error(method + "() call aborted"); - } - } - - if (isRedirectResult(result)) { - // Uhhhh - this should never happen, we should always throw these from - // calLoaderOrAction, 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.status, - headers: { - Location: result.location - } - }); - } - - if (isDeferredResult(result)) { - throw new Error("defer() is not supported in actions"); - } - - if (isRouteRequest) { - if (isErrorResult(result)) { - let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); - return { - matches: [actionMatch], - loaderData: {}, - actionData: null, - errors: { - [boundaryMatch.route.id]: result.error - }, - // Note: statusCode + headers are unused here since queryRoute will - // return the raw Response or value - statusCode: 500, - loaderHeaders: {}, - actionHeaders: {} - }; - } - - 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: {} - }; - } - - 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); - let context = await loadRouteData(request, matches, isRouteRequest, { - [boundaryMatch.route.id]: result.error - }); // action status codes take precedence over loader status codes - - return _extends({}, context, { - statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500, - actionData: null, - actionHeaders: _extends({}, result.headers ? { - [actionMatch.route.id]: result.headers - } : {}) - }); - } - - let context = await loadRouteData(request, matches, isRouteRequest); - return _extends({}, context, result.statusCode ? { - statusCode: result.statusCode - } : {}, { - actionData: { - [actionMatch.route.id]: result.data - }, - actionHeaders: _extends({}, result.headers ? { - [actionMatch.route.id]: result.headers - } : {}) - }); - } - - async function loadRouteData(request, matches, isRouteRequest, pendingActionError) { - let matchesToLoad = getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]).filter(m => m.route.loader); // Short circuit if we have no loaders to run - - if (matchesToLoad.length === 0) { - return { - matches, - loaderData: {}, - errors: pendingActionError || null, - statusCode: 200, - loaderHeaders: {} - }; - } - - let results = await Promise.all([...matchesToLoad.map(m => callLoaderOrAction("loader", request, m, true, isRouteRequest))]); - - if (request.signal.aborted) { - let method = isRouteRequest ? "queryRoute" : "query"; - throw new Error(method + "() call aborted"); - } // Can't do anything with these without the Remix side of things, so just - // cancel them for now - - - results.forEach(result => { - if (isDeferredResult(result)) { - result.deferredData.cancel(); - } - }); // Process and commit output from loaders - - let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError); - return _extends({}, context, { - matches - }); - } - - function matchRequest(req, routeId) { - let url = new URL(req.url); - let location = createLocation("", createPath(url), null, "default"); - let matches = matchRoutes(dataRoutes, location); - - if (matches && routeId) { - matches = matches.filter(m => m.route.id === routeId); - } // Short circuit with a 404 if we match nothing - - - if (!matches) { - let { - matches: notFoundMatches, - route, - error - } = getNotFoundMatches(dataRoutes); - return { - location, - matches: notFoundMatches, - shortCircuitState: { - matches: notFoundMatches, - loaderData: {}, - actionData: null, - errors: { - [route.id]: error - }, - statusCode: 404, - loaderHeaders: {}, - actionHeaders: {} - } - }; - } - - return { - location, - matches - }; - } - - 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: 500, - errors: { - [context._deepestRenderedBoundaryId || routes[0].id]: error - } - }); - - return newContext; -} // Normalize navigation options by converting formMethod=GET formData objects to -// URLSearchParams so they behave identically to links with query params - -function normalizeNavigateOptions(to, opts, isFetcher) { - if (isFetcher === void 0) { - isFetcher = false; - } - - let path = typeof to === "string" ? to : createPath(to); // Return location verbatim on non-submission navigations - - if (!opts || !("formMethod" in opts) && !("formData" in opts)) { - return { - path - }; - } // Create a Submission on non-GET navigations - - - if (opts.formMethod != null && opts.formMethod !== "get") { - return { - path, - submission: { - formMethod: opts.formMethod, - formAction: createHref(parsePath(path)), - formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded", - formData: opts.formData - } - }; - } // No formData to flatten for GET submission - - - if (!opts.formData) { - return { - path - }; - } // Flatten submission onto URLSearchParams for GET submissions - - - let parsedPath = parsePath(path); - - try { - let searchParams = convertFormDataToSearchParams(opts.formData); // Since fetcher GET submissions only run a single loader (as opposed to - // navigation GET submissions which run all loaders), we need to preserve - // any incoming ?index params - - if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) { - searchParams.append("index", ""); - } - - parsedPath.search = "?" + searchParams; - } catch (e) { - return { - path, - error: new ErrorResponse(400, "Bad Request", "Cannot submit binary form data using GET") - }; - } - - return { - path: createPath(parsedPath) - }; -} - -function getLoaderRedirect(state, redirect) { - let { - formMethod, - formAction, - formEncType, - formData - } = state.navigation; - let navigation = { - state: "loading", - location: createLocation(state.location, redirect.location), - formMethod: formMethod || undefined, - formAction: formAction || undefined, - formEncType: formEncType || undefined, - formData: formData || undefined - }; - return navigation; -} // Filter out all routes below any caught error as they aren't going to -// render so we don't need to load them - - -function getLoaderMatchesUntilBoundary(matches, boundaryId) { - let boundaryMatches = matches; - - if (boundaryId) { - let index = matches.findIndex(m => m.route.id === boundaryId); - - if (index >= 0) { - boundaryMatches = matches.slice(0, index); - } - } - - return boundaryMatches; -} - -function getMatchesToLoad(state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches) { - let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : null; // Pick navigation matches that are net-new or qualify for revalidation - - let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined; - let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId); - let navigationMatches = boundaryMatches.filter((match, index) => match.route.loader != null && (isNewLoader(state.loaderData, state.matches[index], match) || // If this route had a pending deferred cancelled it must be revalidated - cancelledDeferredRoutes.some(id => id === match.route.id) || shouldRevalidateLoader(state.location, state.matches[index], submission, location, match, isRevalidationRequired, actionResult))); // Pick fetcher.loads that need to be revalidated - - let revalidatingFetchers = []; - fetchLoadMatches && fetchLoadMatches.forEach((_ref10, key) => { - let [href, match] = _ref10; - - // This fetcher was cancelled from a prior action submission - force reload - if (cancelledFetcherLoads.includes(key)) { - revalidatingFetchers.push([key, href, match]); - } else if (isRevalidationRequired) { - let shouldRevalidate = shouldRevalidateLoader(href, match, submission, href, match, isRevalidationRequired, actionResult); - - if (shouldRevalidate) { - revalidatingFetchers.push([key, href, match]); - } - } - }); - return [navigationMatches, revalidatingFetchers]; -} - -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 && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"] - ); -} - -function shouldRevalidateLoader(currentLocation, currentMatch, submission, location, match, isRevalidationRequired, actionResult) { - let currentUrl = createURL(currentLocation); - let currentParams = currentMatch.params; - let nextUrl = createURL(location); - let nextParams = match.params; // This is the default implementation as to 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 - // Note that fetchers always provide the same current/next locations so the - // URL-based checks here don't apply to fetcher shouldRevalidate calls - - let defaultShouldRevalidate = isNewRouteInstance(currentMatch, match) || // Clicked the same link, resubmitted a GET form - currentUrl.toString() === nextUrl.toString() || // Search params affect all loaders - currentUrl.search !== nextUrl.search || // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate - isRevalidationRequired; - - if (match.route.shouldRevalidate) { - let routeChoice = match.route.shouldRevalidate(_extends({ - currentUrl, - currentParams, - nextUrl, - nextParams - }, submission, { - actionResult, - defaultShouldRevalidate - })); - - if (typeof routeChoice === "boolean") { - return routeChoice; - } - } - - return defaultShouldRevalidate; -} - -async function callLoaderOrAction(type, request, match, skipRedirects, isRouteRequest) { - if (skipRedirects === void 0) { - skipRedirects = false; - } - - if (isRouteRequest === void 0) { - isRouteRequest = false; - } - - let resultType; - let result; // Setup a promise we can race against so that abort signals short circuit - - let reject; - let abortPromise = new Promise((_, r) => reject = r); - - let onReject = () => reject(); - - request.signal.addEventListener("abort", onReject); - - try { - let handler = match.route[type]; - invariant(handler, "Could not find the " + type + " to run on the \"" + match.route.id + "\" route"); - result = await Promise.race([handler({ - request, - params: match.params - }), abortPromise]); - } catch (e) { - resultType = ResultType.error; - result = e; - } finally { - request.signal.removeEventListener("abort", onReject); - } - - if (result instanceof Response) { - // Process redirects - let status = result.status; - let location = result.headers.get("Location"); // For SSR single-route requests, we want to hand Responses back directly - // without unwrapping - - if (isRouteRequest) { - throw result; - } - - if (status >= 300 && status <= 399 && location != null) { - // Don't process redirects in the router during SSR document requests. - // Instead, throw the Response and let the server handle it with an HTTP - // redirect - if (skipRedirects) { - throw result; - } - - return { - type: ResultType.redirect, - status, - location, - revalidate: result.headers.get("X-Remix-Revalidate") !== null - }; - } - - let data; - let contentType = result.headers.get("Content-Type"); - - if (contentType && contentType.startsWith("application/json")) { - data = await result.json(); - } else { - data = await result.text(); - } - - if (resultType === ResultType.error) { - return { - type: resultType, - error: new ErrorResponse(status, result.statusText, data), - headers: result.headers - }; - } - - return { - type: ResultType.data, - data, - statusCode: result.status, - headers: result.headers - }; - } - - if (resultType === ResultType.error) { - return { - type: resultType, - error: result - }; - } - - if (result instanceof DeferredData) { - return { - type: ResultType.deferred, - deferredData: result - }; - } - - return { - type: ResultType.data, - data: result - }; -} - -function createRequest(location, signal, submission) { - let url = createURL(location).toString(); - let init = { - signal - }; - - if (submission) { - let { - formMethod, - formEncType, - formData - } = submission; - init.method = formMethod.toUpperCase(); - init.body = formEncType === "application/x-www-form-urlencoded" ? convertFormDataToSearchParams(formData) : formData; - } // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - - - return new Request(url, init); -} - -function convertFormDataToSearchParams(formData) { - let searchParams = new URLSearchParams(); - - for (let [key, value] of formData.entries()) { - invariant(typeof value === "string", 'File inputs are not supported with encType "application/x-www-form-urlencoded", ' + 'please use "multipart/form-data" instead.'); - searchParams.append(key, value); - } - - return searchParams; -} - -function processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds) { - // Fill in loaderData/errors from our loaders - let loaderData = {}; - let errors = null; - let statusCode; - let foundError = false; - let loaderHeaders = {}; // Process loader results into state.loaderData/state.errors - - results.forEach((result, index) => { - let id = matchesToLoad[index].route.id; - invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData"); - - if (isErrorResult(result)) { - // Look upwards from the matched route for the closest ancestor - // error boundary, defaulting to the root match - let boundaryMatch = findNearestBoundary(matches, id); - 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) { - error = Object.values(pendingError)[0]; - pendingError = undefined; - } - - errors = Object.assign(errors || {}, { - [boundaryMatch.route.id]: error - }); // 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 && activeDeferreds.set(id, result.deferredData); - loaderData[id] = result.deferredData.data; // TODO: Add statusCode/headers once we wire up streaming in Remix - } 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 != null && 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 - - if (pendingError) { - errors = pendingError; - } - - return { - loaderData, - errors, - statusCode: statusCode || 200, - loaderHeaders - }; -} - -function processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) { - let { - loaderData, - errors - } = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds); // Process results from our revalidating fetchers - - for (let index = 0; index < revalidatingFetchers.length; index++) { - let [key,, match] = revalidatingFetchers[index]; - invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result"); - let result = fetcherResults[index]; // Process fetcher non-redirect errors - - if (isErrorResult(result)) { - let boundaryMatch = findNearestBoundary(state.matches, 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 - throw new Error("Unhandled fetcher revalidation redirect"); - } else if (isDeferredResult(result)) { - // Should never get here, deferred data should be awaited for fetchers - // in resolveDeferredResults - throw new Error("Unhandled fetcher deferred data"); - } else { - let doneFetcher = { - state: "idle", - data: result.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined - }; - state.fetchers.set(key, doneFetcher); - } - } - - return { - loaderData, - errors - }; -} - -function mergeLoaderData(loaderData, newLoaderData, matches) { - let mergedLoaderData = _extends({}, newLoaderData); - - matches.forEach(match => { - let id = match.route.id; - - if (newLoaderData[id] === undefined && loaderData[id] !== undefined) { - mergedLoaderData[id] = loaderData[id]; - } - }); - return mergedLoaderData; -} // 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 getNotFoundMatches(routes) { - // Prefer a root layout route if present, otherwise shim in a route object - let route = routes.find(r => r.index || r.path === "" || r.path === "/") || { - id: "__shim-404-route__" - }; - return { - matches: [{ - params: {}, - pathname: "", - pathnameBase: "", - route - }], - route, - error: new ErrorResponse(404, "Not Found", null) - }; -} - -function getMethodNotAllowedResult(path) { - let href = typeof path === "string" ? path : createHref(path); - console.warn("You're trying to submit to a route that does not have an action. To " + "fix this, please add an `action` function to the route for " + ("[" + href + "]")); - return { - type: ResultType.error, - error: new ErrorResponse(405, "Method Not Allowed", "No action found for [" + href + "]") - }; -} // Find any returned redirect errors, starting from the lowest match - - -function findRedirect(results) { - for (let i = results.length - 1; i >= 0; i--) { - let result = results[i]; - - if (isRedirectResult(result)) { - return result; - } - } -} // Create an href to represent a "server" URL without the hash - - -function createHref(location) { - return (location.pathname || "") + (location.search || ""); -} - -function isHashChangeOnly(a, b) { - return a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash; -} - -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; -} - -async function resolveDeferredResults(currentMatches, matchesToLoad, results, signal, isFetcher, currentLoaderData) { - for (let index = 0; index < results.length; index++) { - let result = results[index]; - let match = matchesToLoad[index]; - 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) && (isFetcher || 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, isFetcher).then(result => { - if (result) { - results[index] = result || results[index]; - } - }); - } - } -} - -async function resolveDeferredData(result, signal, unwrap) { - if (unwrap === void 0) { - unwrap = false; - } - - let aborted = await result.deferredData.resolveData(signal); - - if (aborted) { - return; - } - - if (unwrap) { - try { - return { - type: ResultType.data, - data: result.deferredData.unwrappedData - }; - } catch (e) { - // 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 === ""); -} // Note: This should match the format exported by useMatches, so if you change -// this please also change that :) Eventually we'll DRY this up - - -function createUseMatchesMatch(match, loaderData) { - let { - route, - pathname, - params - } = match; - return { - id: route.id, - pathname, - params, - data: loaderData[route.id], - handle: route.handle - }; -} - -function getTargetMatch(matches, location) { - let search = typeof location === "string" ? parsePath(location).search : location.search; - - if (matches[matches.length - 1].route.index && !hasNakedIndexQuery(search || "")) { - return matches.slice(-2)[0]; - } - - return matches.slice(-1)[0]; -} - -function createURL(location) { - let base = typeof window !== "undefined" && typeof window.location !== "undefined" ? window.location.origin : "unknown://unknown"; - let href = typeof location === "string" ? location : createHref(location); - return new URL(href, base); -} //#endregion - -export { AbortedDeferredError, Action, ErrorResponse, IDLE_FETCHER, IDLE_NAVIGATION, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, createRouter, defer, generatePath, getStaticContextFromError, getToPathname, invariant, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, parsePath, redirect, resolvePath, resolveTo, stripBasename, unstable_createStaticHandler, warning }; -//# sourceMappingURL=router.js.map diff --git a/node_modules/@remix-run/router/dist/router.js.map b/node_modules/@remix-run/router/dist/router.js.map deleted file mode 100644 index 0a24de6d..00000000 --- a/node_modules/@remix-run/router/dist/router.js.map +++ /dev/null @@ -1 +0,0 @@ -{"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/**\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 extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: any;\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/**\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`. May be either a URL or the pieces of a\n * URL path.\n */\nexport type To = string | Partial;\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 attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\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};\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;\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 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(to) {\n return typeof to === \"string\" ? to : createPath(to);\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 });\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 });\n }\n },\n go(delta) {\n action = Action.Pop;\n index = clampIndex(index + delta);\n if (listener) {\n listener({ action, location: getCurrentLocation() });\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 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\nfunction 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): HistoryState {\n return {\n usr: location.state,\n key: location.key,\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 {\n let location: Readonly = {\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) {\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 {\n let parsedPath: Partial = {};\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 function handlePop() {\n action = Action.Pop;\n if (listener) {\n listener({ action, location: history.location });\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 let historyState = getHistoryState(location);\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 // 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 });\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 let historyState = getHistoryState(location);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: location });\n }\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 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 { parsePath } 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: any;\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}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n status: number;\n location: string;\n revalidate: boolean;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: any;\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\nexport type FormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\";\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport interface Submission {\n formMethod: Exclude;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\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 {\n request: Request;\n params: Params;\n}\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Route loader function signature\n */\nexport interface LoaderFunction {\n (args: LoaderFunctionArgs): Promise | Response | Promise | any;\n}\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (args: ActionFunctionArgs): Promise | Response | Promise | any;\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: {\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 formData?: Submission[\"formData\"];\n actionResult?: DataResult;\n defaultShouldRevalidate: boolean;\n }): boolean;\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;\n action?: ActionFunction;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\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\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\n : // find params after `:`\n Path extends `${string}:${infer Param}`\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 */\ntype PathParam =\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\n : // look for params in the absence of wildcards\n _PathParam;\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 =\n // if could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\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;\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 {}\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 parentPath: number[] = [],\n allIds: Set = new Set()\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, 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 !allIds.has(id),\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n allIds.add(id);\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = { ...route, id };\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n id,\n children: route.children\n ? convertRoutesToDataRoutes(route.children, treePath, allIds)\n : undefined,\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/docs/en/v6/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | 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 for (let i = 0; matches == null && i < branches.length; ++i) {\n matches = matchRouteBranch(branches[i], pathname);\n }\n\n return matches;\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[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n routes.forEach((route, index) => {\n let meta: RouteMeta = {\n relativePath: route.path || \"\",\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\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({ path, score: computeScore(path, route.index), routesMeta });\n });\n\n return branches;\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,\n pathname: string\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\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 if (!match) return null;\n\n Object.assign(matchedParams, match.params);\n\n let route = meta.route;\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\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/docs/en/v6/utils/generate-path\n */\nexport function generatePath(\n path: Path,\n params: {\n [key in PathParam]: string;\n } = {} as any\n): string {\n return path\n .replace(/:(\\w+)/g, (_, key: PathParam) => {\n invariant(params[key] != null, `Missing \":${key}\" param`);\n return params[key]!;\n })\n .replace(/(\\/?)\\*/, (_, prefix, __, str) => {\n const star = \"*\" as PathParam;\n\n if (params[star] == null) {\n // If no splat was provided, trim the trailing slash _unless_ it's\n // the entire path\n return str === \"/*\" ? \"/\" : \"\";\n }\n\n // Apply the splat\n return `${prefix}${params[star]}`;\n });\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\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 {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\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 = {\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/docs/en/v6/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, paramNames] = 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 = paramNames.reduce>(\n (memo, paramName, 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 memo[paramName] = safelyDecodeURIComponent(\n captureGroups[index] || \"\",\n paramName\n );\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, string[]] {\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 paramNames: string[] = [];\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(/:(\\w+)/g, (_: string, paramName: string) => {\n paramNames.push(paramName);\n return \"([^\\\\/]+)\";\n });\n\n if (path.endsWith(\"*\")) {\n paramNames.push(\"*\");\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, paramNames];\n}\n\nfunction safelyDecodeURIComponent(value: string, paramName: string) {\n try {\n return decodeURIComponent(value);\n } catch (error) {\n warning(\n false,\n `The value for the URL param \"${paramName}\" will not be decoded because` +\n ` the string \"${value}\" is a malformed URL segment. This is probably` +\n ` due to a bad percent 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\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\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\n/**\n * @private\n */\nexport function warning(cond: any, message: string): void {\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 React Router!\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\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/docs/en/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 = toPathname\n ? toPathname.startsWith(\"/\")\n ? toPathname\n : resolvePathname(toPathname, fromPathname)\n : fromPathname;\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\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 and the router will parse it for you.`\n );\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;\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 `` 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 (isPathRelative || toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n if (toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n // Each leading .. segment means \"go up one route\" instead of \"go up one\n // URL segment\". This is a key difference from how works and a\n // major reason we call this a \"to\" value instead of a \"href\".\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n // If there are more \"..\" segments than parent routes, resolve relative to\n // the root / URL.\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\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\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 = (\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 */\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 interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeys: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscriber?: (aborted: boolean) => void = undefined;\n data: Record;\n\n constructor(data: Record) {\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\n private trackPromise(\n key: string | number,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.pendingKeys.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, null, 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 | number,\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.pendingKeys.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n const subscriber = this.subscriber;\n if (error) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n subscriber && subscriber(false);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n subscriber && subscriber(false);\n return data;\n }\n\n subscribe(fn: (aborted: boolean) => void) {\n this.subscriber = fn;\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeys.forEach((v, k) => this.pendingKeys.delete(k));\n let subscriber = this.subscriber;\n subscriber && subscriber(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.pendingKeys.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\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 function defer(data: Record) {\n return new DeferredData(data);\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 * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n */\nexport class ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n\n constructor(status: number, statusText: string | undefined, data: any) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.data = data;\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response throw from an action/loader\n */\nexport function isRouteErrorResponse(e: any): e is ErrorResponse {\n return e instanceof ErrorResponse;\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n parsePath,\n} from \"./history\";\nimport type {\n DataResult,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n DeferredResult,\n ErrorResult,\n FormEncType,\n FormMethod,\n RedirectResult,\n RouteData,\n AgnosticRouteObject,\n Submission,\n SuccessResult,\n AgnosticRouteMatch,\n} from \"./utils\";\nimport {\n DeferredData,\n ErrorResponse,\n ResultType,\n convertRoutesToDataRoutes,\n invariant,\n isRouteErrorResponse,\n matchRoutes,\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 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 * 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,\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): 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, opts?: RouterNavigateOptions): 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,\n opts?: RouterNavigateOptions\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 * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key?: string): Fetcher;\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 * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\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;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n basename?: string;\n routes: AgnosticRouteObject[];\n history: History;\n hydrationData?: HydrationState;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\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;\n actionHeaders: Record;\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(request: Request): Promise;\n queryRoute(request: Request, routeId?: string): Promise;\n}\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (state: RouterState): void;\n}\n\ninterface UseMatchesMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: unknown;\n handle: unknown;\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: UseMatchesMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\n/**\n * Options for a navigate() call for a Link navigation\n */\ntype LinkNavigateOptions = {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n};\n\n/**\n * Options for a navigate() call for a Form navigation\n */\ntype SubmissionNavigateOptions = {\n replace?: boolean;\n state?: any;\n formMethod?: FormMethod;\n formEncType?: FormEncType;\n formData: FormData;\n};\n\n/**\n * Options to pass to navigate() for either a Link or Form navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions =\n | Omit\n | Omit;\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 };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: FormMethod | undefined;\n formAction: string | undefined;\n formEncType: FormEncType | undefined;\n formData: FormData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\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 = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: FormMethod | undefined;\n formAction: string | undefined;\n formEncType: FormEncType | undefined;\n formData: FormData | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n data: TData | undefined;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\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\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Error thrown from the current action, keyed by the route containing the\n * error boundary to render the error. To be committed to the state after\n * loaders have completed\n */\n pendingActionError?: RouteData;\n /**\n * Data returned from the current action, keyed by the route owning the action.\n * To be committed to the state after loaders have completed\n */\n pendingActionData?: RouteData;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\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 * Tuple of [key, href, DataRouterMatch] for a revalidating fetcher.load()\n */\ntype RevalidatingFetcher = [string, string, AgnosticDataRouteMatch];\n\n/**\n * Tuple of [href, DataRouteMatch] for an active fetcher.load()\n */\ntype FetchLoadMatch = [string, AgnosticDataRouteMatch];\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};\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};\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 invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let dataRoutes = convertRoutesToDataRoutes(init.routes);\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();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | 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 until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n let initialScrollRestored = false;\n\n let initialMatches = matchRoutes(\n dataRoutes,\n init.history.location,\n init.basename\n );\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null) {\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 { matches, route, error } = getNotFoundMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized =\n !initialMatches.some((m) => m.route.loader) || init.hydrationData != null;\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 restoreScrollPosition: 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 };\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 // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidate()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\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 // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\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 // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n // Fetchers that triggered redirect navigations from their actions\n let fetchRedirectIds = new Set();\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\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();\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 }) =>\n startNavigation(historyAction, location)\n );\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location);\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 subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(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(newState: Partial): void {\n state = {\n ...state,\n ...newState,\n };\n subscribers.forEach((subscriber) => subscriber(state));\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>\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 submission\n // - We're past the submitting state and into the loading state\n // - The location we've finished loading is different from the submission\n // location, indicating we redirected from the action (avoids false\n // positives for loading/submissionRedirect when actionData returned\n // on a prior submission)\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n state.navigation.state === \"loading\" &&\n state.navigation.formAction?.split(\"?\")[0] === location.pathname;\n\n // Always preserve any existing loaderData from re-used routes\n let newLoaderData = newState.loaderData\n ? {\n loaderData: mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || []\n ),\n }\n : {};\n\n updateState({\n // Clear existing actionData on any completed navigation beyond the original\n // action, unless we're currently finishing the loading/actionReload state.\n // Do this prior to spreading in newState in case we got back to back actions\n ...(isActionReload ? {} : { actionData: null }),\n ...newState,\n ...newLoaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n // Don't restore on submission navigations\n restoreScrollPosition: state.navigation.formData\n ? false\n : getSavedScrollPosition(location, newState.matches || state.matches),\n preventScrollReset: pendingPreventScrollReset,\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 // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\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,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(to, opts);\n\n let location = createLocation(state.location, path, opts && opts.state);\n let historyAction =\n (opts && opts.replace) === true || submission != null\n ? HistoryAction.Replace\n : HistoryAction.Push;\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n return await startNavigation(historyAction, location, {\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 });\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 { overrideNavigation: state.navigation }\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 submission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponse;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n }\n ): Promise {\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 let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(dataRoutes, location, init.basename);\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let {\n matches: notFoundMatches,\n route,\n error,\n } = getNotFoundMatches(dataRoutes);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(location, {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n });\n return;\n }\n\n // Short circuit if it's only a hash change\n if (isHashChangeOnly(state.location, location)) {\n completeNavigation(location, { matches });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createRequest(\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionData: RouteData | undefined;\n let pendingError: RouteData | 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 pendingError = {\n [findNearestBoundary(matches).route.id]: opts.pendingError,\n };\n } else if (opts && opts.submission) {\n // Call action if we received an action submission\n let actionOutput = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n { replace: opts.replace }\n );\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n ...opts.submission,\n };\n loadingNavigation = navigation;\n }\n\n // Call loaders\n let { shortCircuited, loaderData, errors } = await handleLoaders(\n request,\n location,\n matches,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.replace,\n pendingActionData,\n pendingError\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,\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 opts?: { replace?: boolean }\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n ...submission,\n };\n updateState({ navigation });\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) {\n result = getMethodNotAllowedResult(location);\n } else {\n result = await callLoaderOrAction(\"action\", request, actionMatch);\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let redirectNavigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location: createLocation(state.location, result.location),\n ...submission,\n };\n await startRedirectNavigation(\n result,\n redirectNavigation,\n opts && opts.replace\n );\n return { shortCircuited: true };\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 are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw new Error(\"defer() is not supported in actions\");\n }\n\n return {\n pendingActionData: { [actionMatch.route.id]: result.data },\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 overrideNavigation?: Navigation,\n submission?: Submission,\n replace?: boolean,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n ): Promise {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation = overrideNavigation;\n if (!loadingNavigation) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n loadingNavigation = navigation;\n }\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n state,\n matches,\n submission,\n location,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n pendingActionData,\n pendingError,\n fetchLoadMatches\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 // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n completeNavigation(location, {\n matches,\n loaderData: mergeLoaderData(state.loaderData, {}, matches),\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n actionData: pendingActionData || null,\n });\n return { shortCircuited: true };\n }\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 (!isUninterruptedRevalidation) {\n revalidatingFetchers.forEach(([key]) => {\n const fetcher = state.fetchers.get(key);\n let revalidatingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n data: fetcher && fetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(key, revalidatingFetcher);\n });\n updateState({\n navigation: loadingNavigation,\n actionData: pendingActionData || state.actionData || null,\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n });\n }\n\n pendingNavigationLoadId = ++incrementingLoadId;\n revalidatingFetchers.forEach(([key]) =>\n fetchControllers.set(key, pendingNavigationController!)\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.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 revalidatingFetchers.forEach(([key]) => fetchControllers.delete(key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n let redirectNavigation = getLoaderRedirect(state, redirect);\n await startRedirectNavigation(redirect, redirectNavigation, replace);\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n matchesToLoad,\n loaderResults,\n pendingError,\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 markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n\n return {\n loaderData,\n errors,\n ...(didAbortFetchLoads || revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n };\n }\n\n function getFetcher(key: string): Fetcher {\n return state.fetchers.get(key) || IDLE_FETCHER;\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,\n opts?: RouterFetchOptions\n ) {\n if (typeof AbortController === \"undefined\") {\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 if (fetchControllers.has(key)) abortFetcher(key);\n\n let matches = matchRoutes(dataRoutes, href, init.basename);\n if (!matches) {\n setFetcherError(key, routeId, new ErrorResponse(404, \"Not Found\", null));\n return;\n }\n\n let { path, submission } = normalizeNavigateOptions(href, opts, true);\n let match = getTargetMatch(matches, path);\n\n if (submission) {\n handleFetcherAction(key, routeId, path, match, submission);\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, [path, match]);\n handleFetcherLoader(key, routeId, path, match);\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 submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action) {\n let { error } = getMethodNotAllowedResult(path);\n setFetcherError(key, routeId, error);\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n ...submission,\n data: existingFetcher && existingFetcher.data,\n };\n state.fetchers.set(key, fetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createRequest(path, abortController.signal, submission);\n fetchControllers.set(key, abortController);\n\n let actionResult = await callLoaderOrAction(\"action\", fetchRequest, match);\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by ou 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 if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n fetchRedirectIds.add(key);\n let loadingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n ...submission,\n data: undefined,\n };\n state.fetchers.set(key, loadingFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n let redirectNavigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location: createLocation(state.location, actionResult.location),\n ...submission,\n };\n await startRedirectNavigation(actionResult, redirectNavigation);\n return;\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n\n if (isDeferredResult(actionResult)) {\n invariant(false, \"defer() is not supported in actions\");\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 = createRequest(\n nextLocation,\n abortController.signal\n );\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(dataRoutes, state.navigation.location, init.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: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n data: actionResult.data,\n ...submission,\n };\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n state,\n matches,\n submission,\n nextLocation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n { [match.route.id]: actionResult.data },\n undefined, // No need to send through errors since we short circuit above\n fetchLoadMatches\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(([staleKey]) => staleKey !== key)\n .forEach(([staleKey]) => {\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n data: existingFetcher && existingFetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(staleKey, revalidatingFetcher);\n fetchControllers.set(staleKey, abortController);\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach(([staleKey]) =>\n fetchControllers.delete(staleKey)\n );\n\n let redirect = findRedirect(results);\n if (redirect) {\n let redirectNavigation = getLoaderRedirect(state, redirect);\n await startRedirectNavigation(redirect, redirectNavigation);\n return;\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: actionResult.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(key, doneFetcher);\n\n let didAbortFetchLoads = 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(state.loaderData, loaderData, matches),\n ...(didAbortFetchLoads ? { 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 ) {\n let existingFetcher = state.fetchers.get(key);\n // Put this fetcher into it's loading state\n let loadingFetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n data: existingFetcher && existingFetcher.data,\n };\n state.fetchers.set(key, loadingFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createRequest(path, abortController.signal);\n fetchControllers.set(key, abortController);\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match\n );\n\n // Deferred isn't supported or 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 ou 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 // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n let redirectNavigation = getLoaderRedirect(state, result);\n await startRedirectNavigation(result, redirectNavigation);\n return;\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n state.fetchers.delete(key);\n // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -\n // do we need to behave any differently with our non-redirect errors?\n // What if it was a non-redirect Response?\n updateState({\n fetchers: new Map(state.fetchers),\n errors: {\n [boundaryMatch.route.id]: result.error,\n },\n });\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: result.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(key, doneFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\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 redirect: RedirectResult,\n navigation: Navigation,\n replace?: boolean\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n invariant(\n navigation.location,\n \"Expected a location on the redirect navigation\"\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 ? HistoryAction.Replace : HistoryAction.Push;\n await startNavigation(redirectHistoryAction, navigation.location, {\n overrideNavigation: navigation,\n });\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n // Call all navigation loaders and revalidating fetcher loaders in parallel,\n // then slice off the results into separate arrays so we can handle them\n // accordingly\n let results = await Promise.all([\n ...matchesToLoad.map((m) => callLoaderOrAction(\"loader\", request, m)),\n ...fetchersToLoad.map(([, href, match]) =>\n callLoaderOrAction(\"loader\", createRequest(href, request.signal), match)\n ),\n ]);\n let loaderResults = results.slice(0, matchesToLoad.length);\n let fetcherResults = results.slice(matchesToLoad.length);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n request.signal,\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map(([, , match]) => match),\n fetcherResults,\n request.signal,\n true\n ),\n ]);\n\n return { results, loaderResults, fetcherResults };\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.push(key);\n abortFetcher(key);\n }\n });\n }\n\n function setFetcherError(key: string, routeId: string, error: any) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState({\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n });\n }\n\n function deleteFetcher(key: string): void {\n if (fetchControllers.has(key)) abortFetcher(key);\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n state.fetchers.delete(key);\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: fetcher.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): void {\n let doneKeys = [];\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 }\n }\n markFetchersDone(doneKeys);\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 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 component\n function enableScrollRestoration(\n positions: Record,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || ((location) => location.key);\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered \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 saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n let userMatches = matches.map((m) =>\n createUseMatchesMatch(m, state.loaderData)\n );\n let key = getScrollRestorationKey(location, userMatches) || location.key;\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {\n let userMatches = matches.map((m) =>\n createUseMatchesMatch(m, state.loaderData)\n );\n let key = getScrollRestorationKey(location, userMatches) || location.key;\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n router = {\n get basename() {\n return init.basename;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n createHref,\n getFetcher,\n deleteFetcher,\n dispose,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport function unstable_createStaticHandler(\n routes: AgnosticRouteObject[]\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to unstable_createStaticHandler\"\n );\n\n let dataRoutes = convertRoutesToDataRoutes(routes);\n\n async function query(\n request: Request\n ): Promise {\n let { location, result } = await queryImpl(request);\n if (result instanceof Response) {\n return result;\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, ...result };\n }\n\n async function queryRoute(request: Request, routeId: string): Promise {\n let { result } = await queryImpl(request, routeId);\n if (result instanceof Response) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // While we always re-throw Responses returned from loaders/actions\n // directly for route requests and prevent the unwrapping into an\n // ErrorResponse, we still need this for error cases _prior_ the\n // execution of the loader/action, such as a 404/405 error.\n if (isRouteErrorResponse(error)) {\n return new Response(error.data, {\n status: error.status,\n statusText: error.statusText,\n });\n }\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 let routeData = [result.actionData, result.loaderData].find((v) => v);\n let value = Object.values(routeData || {})[0];\n\n if (isRouteErrorResponse(value)) {\n return new Response(value.data, {\n status: value.status,\n statusText: value.statusText,\n });\n }\n\n return value;\n }\n\n async function queryImpl(\n request: Request,\n routeId?: string\n ): Promise<{\n location: Location;\n result: Omit | Response;\n }> {\n invariant(\n request.method !== \"HEAD\",\n \"query()/queryRoute() do not support HEAD requests\"\n );\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n let { location, matches, shortCircuitState } = matchRequest(\n request,\n routeId\n );\n\n try {\n if (shortCircuitState) {\n return { location, result: shortCircuitState };\n }\n\n if (request.method !== \"GET\") {\n let result = await submit(\n request,\n matches,\n getTargetMatch(matches, location),\n routeId != null\n );\n return { location, result };\n }\n\n let result = await loadRouteData(request, matches, routeId != null);\n return {\n location,\n result: {\n ...result,\n actionData: null,\n actionHeaders: {},\n },\n };\n } catch (e) {\n if (e instanceof Response) {\n return { location, result: e };\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n if (!actionMatch.route.action) {\n let href = createHref(new URL(request.url));\n result = getMethodNotAllowedResult(href);\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n true,\n isRouteRequest\n );\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted`);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // calLoaderOrAction, 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.status,\n headers: {\n Location: result.location,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n throw new Error(\"defer() is not supported in actions\");\n }\n\n if (isRouteRequest) {\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: null,\n errors: {\n [boundaryMatch.route.id]: result.error,\n },\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 500,\n loaderHeaders: {},\n actionHeaders: {},\n };\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 };\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 let context = await loadRouteData(request, matches, isRouteRequest, {\n [boundaryMatch.route.id]: result.error,\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 : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n let context = await loadRouteData(request, matches, isRouteRequest);\n\n return {\n ...context,\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n isRouteRequest: boolean,\n pendingActionError?: RouteData\n ): Promise<\n | Omit\n | Response\n > {\n let matchesToLoad = getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n ).filter((m) => m.route.loader);\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0) {\n return {\n matches,\n loaderData: {},\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((m) =>\n callLoaderOrAction(\"loader\", request, m, true, isRouteRequest)\n ),\n ]);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted`);\n }\n\n // Can't do anything with these without the Remix side of things, so just\n // cancel them for now\n results.forEach((result) => {\n if (isDeferredResult(result)) {\n result.deferredData.cancel();\n }\n });\n\n // Process and commit output from loaders\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError\n );\n\n return {\n ...context,\n matches,\n };\n }\n\n function matchRequest(\n req: Request,\n routeId?: string\n ): {\n location: Location;\n matches: AgnosticDataRouteMatch[];\n routeMatch?: AgnosticDataRouteMatch;\n shortCircuitState?: Omit;\n } {\n let url = new URL(req.url);\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location);\n if (matches && routeId) {\n matches = matches.filter((m) => m.route.id === routeId);\n }\n\n // Short circuit with a 404 if we match nothing\n if (!matches) {\n let {\n matches: notFoundMatches,\n route,\n error,\n } = getNotFoundMatches(dataRoutes);\n return {\n location,\n matches: notFoundMatches,\n shortCircuitState: {\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: 404,\n loaderHeaders: {},\n actionHeaders: {},\n },\n };\n }\n\n return { location, matches };\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: 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\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 to: To,\n opts?: RouterNavigateOptions,\n isFetcher = false\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponse;\n} {\n let path = typeof to === \"string\" ? to : createPath(to);\n\n // Return location verbatim on non-submission navigations\n if (!opts || (!(\"formMethod\" in opts) && !(\"formData\" in opts))) {\n return { path };\n }\n\n // Create a Submission on non-GET navigations\n if (opts.formMethod != null && opts.formMethod !== \"get\") {\n return {\n path,\n submission: {\n formMethod: opts.formMethod,\n formAction: createHref(parsePath(path)),\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData: opts.formData,\n },\n };\n }\n\n // No formData to flatten for GET submission\n if (!opts.formData) {\n return { path };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n try {\n let searchParams = convertFormDataToSearchParams(opts.formData);\n // Since fetcher GET submissions only run a single loader (as opposed to\n // navigation GET submissions which run all loaders), we need to preserve\n // any incoming ?index params\n if (\n isFetcher &&\n parsedPath.search &&\n hasNakedIndexQuery(parsedPath.search)\n ) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n } catch (e) {\n return {\n path,\n error: new ErrorResponse(\n 400,\n \"Bad Request\",\n \"Cannot submit binary form data using GET\"\n ),\n };\n }\n\n return { path: createPath(parsedPath) };\n}\n\nfunction getLoaderRedirect(\n state: RouterState,\n redirect: RedirectResult\n): Navigation {\n let { formMethod, formAction, formEncType, formData } = state.navigation;\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location: createLocation(state.location, redirect.location),\n formMethod: formMethod || undefined,\n formAction: formAction || undefined,\n formEncType: formEncType || undefined,\n formData: formData || undefined,\n };\n return navigation;\n}\n\n// Filter out all routes 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) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n pendingActionData?: RouteData,\n pendingError?: RouteData,\n fetchLoadMatches?: Map\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : null;\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n let navigationMatches = boundaryMatches.filter(\n (match, index) =>\n match.route.loader != null &&\n (isNewLoader(state.loaderData, state.matches[index], match) ||\n // If this route had a pending deferred cancelled it must be revalidated\n cancelledDeferredRoutes.some((id) => id === match.route.id) ||\n shouldRevalidateLoader(\n state.location,\n state.matches[index],\n submission,\n location,\n match,\n isRevalidationRequired,\n actionResult\n ))\n );\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches &&\n fetchLoadMatches.forEach(([href, match], key) => {\n // This fetcher was cancelled from a prior action submission - force reload\n if (cancelledFetcherLoads.includes(key)) {\n revalidatingFetchers.push([key, href, match]);\n } else if (isRevalidationRequired) {\n let shouldRevalidate = shouldRevalidateLoader(\n href,\n match,\n submission,\n href,\n match,\n isRevalidationRequired,\n actionResult\n );\n if (shouldRevalidate) {\n revalidatingFetchers.push([key, href, match]);\n }\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\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 &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n currentLocation: string | Location,\n currentMatch: AgnosticDataRouteMatch,\n submission: Submission | undefined,\n location: string | Location,\n match: AgnosticDataRouteMatch,\n isRevalidationRequired: boolean,\n actionResult: DataResult | undefined\n) {\n let currentUrl = createURL(currentLocation);\n let currentParams = currentMatch.params;\n let nextUrl = createURL(location);\n let nextParams = match.params;\n\n // This is the default implementation as to 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 // Note that fetchers always provide the same current/next locations so the\n // URL-based checks here don't apply to fetcher shouldRevalidate calls\n let defaultShouldRevalidate =\n isNewRouteInstance(currentMatch, match) ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.toString() === nextUrl.toString() ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate\n isRevalidationRequired;\n\n if (match.route.shouldRevalidate) {\n let routeChoice = match.route.shouldRevalidate({\n currentUrl,\n currentParams,\n nextUrl,\n nextParams,\n ...submission,\n actionResult,\n defaultShouldRevalidate,\n });\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return defaultShouldRevalidate;\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n skipRedirects: boolean = false,\n isRouteRequest: boolean = false\n): Promise {\n let resultType;\n let result;\n\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n let abortPromise = new Promise((_, r) => (reject = r));\n let onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n\n try {\n let handler = match.route[type];\n invariant(\n handler,\n `Could not find the ${type} to run on the \"${match.route.id}\" route`\n );\n\n result = await Promise.race([\n handler({ request, params: match.params }),\n abortPromise,\n ]);\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n\n if (result instanceof Response) {\n // Process redirects\n let status = result.status;\n let location = result.headers.get(\"Location\");\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping\n if (isRouteRequest) {\n throw result;\n }\n\n if (status >= 300 && status <= 399 && location != null) {\n // Don't process redirects in the router during SSR document requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect\n if (skipRedirects) {\n throw result;\n }\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n };\n }\n\n let data: any;\n let contentType = result.headers.get(\"Content-Type\");\n if (contentType && contentType.startsWith(\"application/json\")) {\n data = await result.json();\n } else {\n data = await result.text();\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponse(status, result.statusText, data),\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 (resultType === ResultType.error) {\n return { type: resultType, error: result };\n }\n\n if (result instanceof DeferredData) {\n return { type: ResultType.deferred, deferredData: result };\n }\n\n return { type: ResultType.data, data: result };\n}\n\nfunction createRequest(\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = createURL(location).toString();\n let init: RequestInit = { signal };\n\n if (submission) {\n let { formMethod, formEncType, formData } = submission;\n init.method = formMethod.toUpperCase();\n init.body =\n formEncType === \"application/x-www-form-urlencoded\"\n ? convertFormDataToSearchParams(formData)\n : formData;\n }\n\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\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 invariant(\n typeof value === \"string\",\n 'File inputs are not supported with encType \"application/x-www-form-urlencoded\", ' +\n 'please use \"multipart/form-data\" instead.'\n );\n searchParams.append(key, value);\n }\n\n return searchParams;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n activeDeferreds?: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\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 = {};\n\n // Process loader results into state.loaderData/state.errors\n results.forEach((result, index) => {\n let id = matchesToLoad[index].route.id;\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n // Look upwards from the matched route for the closest ancestor\n // error boundary, defaulting to the root match\n let boundaryMatch = findNearestBoundary(matches, id);\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) {\n error = Object.values(pendingError)[0];\n pendingError = undefined;\n }\n errors = Object.assign(errors || {}, {\n [boundaryMatch.route.id]: error,\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 if (isDeferredResult(result)) {\n activeDeferreds && activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n // TODO: Add statusCode/headers once we wire up streaming in Remix\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 (\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 }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here\n if (pendingError) {\n errors = pendingError;\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 matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingError,\n activeDeferreds\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let [key, , match] = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n 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 throw new Error(\"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 throw new Error(\"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: result.data,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n };\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): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n matches.forEach((match) => {\n let id = match.route.id;\n if (newLoaderData[id] === undefined && loaderData[id] !== undefined) {\n mergedLoaderData[id] = loaderData[id];\n }\n });\n return mergedLoaderData;\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 getNotFoundMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n error: ErrorResponse;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route = routes.find(\n (r) => r.index || r.path === \"\" || r.path === \"/\"\n ) || {\n id: \"__shim-404-route__\",\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n error: new ErrorResponse(404, \"Not Found\", null),\n };\n}\n\nfunction getMethodNotAllowedResult(path: Location | string): ErrorResult {\n let href = typeof path === \"string\" ? path : createHref(path);\n console.warn(\n \"You're trying to submit to a route that does not have an action. To \" +\n \"fix this, please add an `action` function to the route for \" +\n `[${href}]`\n );\n return {\n type: ResultType.error,\n error: new ErrorResponse(\n 405,\n \"Method Not Allowed\",\n `No action found for [${href}]`\n ),\n };\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(results: DataResult[]): RedirectResult | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return result;\n }\n }\n}\n\n// Create an href to represent a \"server\" URL without the hash\nfunction createHref(location: Partial | Location | URL) {\n return (location.pathname || \"\") + (location.search || \"\");\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n return (\n a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash\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\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n signal: AbortSignal,\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\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) && (isFetcher || 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, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\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\n// Note: This should match the format exported by useMatches, so if you change\n// this please also change that :) Eventually we'll DRY this up\nfunction createUseMatchesMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UseMatchesMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id] as unknown,\n handle: route.handle as unknown,\n };\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 matches.slice(-2)[0];\n }\n return matches.slice(-1)[0];\n}\n\nfunction createURL(location: Location | string): URL {\n let base =\n typeof window !== \"undefined\" && typeof window.location !== \"undefined\"\n ? window.location.origin\n : \"unknown://unknown\";\n let href = typeof location === \"string\" ? location : createHref(location);\n return new URL(href, base);\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","history","createHref","createPath","push","Push","nextLocation","splice","replace","Replace","go","delta","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","search","hash","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","parsePath","substr","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","cond","message","console","warn","Error","e","createKey","random","toString","getHistoryState","current","path","parsedPath","searchIndex","getLocation","validateLocation","defaultView","handlePop","historyState","pushState","error","assign","replaceState","addEventListener","removeEventListener","ResultType","isIndexRoute","route","convertRoutesToDataRoutes","routes","parentPath","allIds","Set","treePath","id","join","invariant","children","has","add","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","i","matchRouteBranch","parentsMeta","forEach","meta","relativePath","caseSensitive","childrenIndex","startsWith","joinPaths","routesMeta","concat","score","computeScore","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","segments","split","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","match","matchPath","Object","params","pathnameBase","normalizePathname","generatePath","_","prefix","__","str","star","pattern","matcher","paramNames","compilePath","captureGroups","memo","paramName","splatValue","safelyDecodeURIComponent","endsWith","regexpSource","RegExp","value","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","resolvePathname","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","includes","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","data","init","responseInit","status","headers","Headers","set","Response","AbortedDeferredError","DeferredData","constructor","pendingKeys","subscriber","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","trackPromise","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","done","subscribe","cancel","abort","v","k","resolveData","resolve","size","unwrappedData","unwrapTrackedPromise","isTrackedPromise","_tracked","_error","_data","defer","redirect","ErrorResponse","statusText","isRouteErrorResponse","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","IDLE_FETCHER","createRouter","dataRoutes","unlistenHistory","subscribers","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","initialMatches","initialErrors","getNotFoundMatches","initialized","m","loader","hydrationData","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","loaderData","actionData","errors","fetchers","Map","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeDeferreds","initialize","startNavigation","dispose","clear","deleteFetcher","updateState","newState","completeNavigation","isActionReload","newLoaderData","mergeLoaderData","getSavedScrollPosition","navigate","opts","submission","normalizeNavigateOptions","pendingError","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","loadingNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","request","createRequest","pendingActionData","findNearestBoundary","actionOutput","handleAction","shortCircuited","pendingActionError","handleLoaders","result","actionMatch","getTargetMatch","getMethodNotAllowedResult","callLoaderOrAction","isRedirectResult","redirectNavigation","startRedirectNavigation","isErrorResult","boundaryMatch","isDeferredResult","matchesToLoad","revalidatingFetchers","getMatchesToLoad","routeId","fetcher","revalidatingFetcher","results","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","getLoaderRedirect","processLoaderData","deferredData","markFetchRedirectsDone","didAbortFetchLoads","abortStaleFetchLoads","getFetcher","fetch","abortFetcher","setFetcherError","handleFetcherAction","handleFetcherLoader","existingFetcher","abortController","fetchRequest","actionResult","loadingFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","redirectHistoryAction","currentMatches","fetchersToLoad","all","resolveDeferredResults","markFetchersDone","keys","doneKeys","landedId","yeetedKeys","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","userMatches","createUseMatchesMatch","_internalFetchControllers","_internalActiveDeferreds","unstable_createStaticHandler","query","queryImpl","queryRoute","values","routeData","find","method","shortCircuitState","matchRequest","submit","loadRouteData","actionHeaders","isRouteRequest","URL","Location","statusCode","loaderHeaders","context","getLoaderMatchesUntilBoundary","processRouteLoaderData","req","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","isFetcher","searchParams","convertFormDataToSearchParams","hasNakedIndexQuery","append","boundaryId","boundaryMatches","findIndex","navigationMatches","isNewLoader","shouldRevalidateLoader","shouldRevalidate","currentLoaderData","currentMatch","isNew","isMissingData","isNewRouteInstance","currentPath","currentLocation","currentUrl","createURL","currentParams","nextUrl","nextParams","defaultShouldRevalidate","routeChoice","type","skipRedirects","resultType","onReject","handler","contentType","text","deferred","toUpperCase","body","Request","URLSearchParams","foundError","mergedLoaderData","eligibleMatches","reverse","hasErrorBoundary","isRevalidatingLoader","unwrap","getAll","handle","origin"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;;AAEA;;AAEG;IACSA,OAAZ;;AAAA,CAAA,UAAYA,MAAZ,EAAkB;AAChB;;;;;;AAMG;AACHA,EAAAA,MAAA,CAAA,KAAA,CAAA,GAAA,KAAA,CAAA;AAEA;;;;AAIG;;AACHA,EAAAA,MAAA,CAAA,MAAA,CAAA,GAAA,MAAA,CAAA;AAEA;;;AAGG;;AACHA,EAAAA,MAAA,CAAA,SAAA,CAAA,GAAA,SAAA,CAAA;AACD,CAtBD,EAAYA,MAAM,KAANA,MAAM,GAsBjB,EAtBiB,CAAlB,CAAA,CAAA;;AAkKA,MAAMC,iBAAiB,GAAG,UAA1B,CAAA;AA+BA;;;AAGG;;AACa,SAAAC,mBAAA,CACdC,OADc,EACoB;AAAA,EAAA,IAAlCA,OAAkC,KAAA,KAAA,CAAA,EAAA;AAAlCA,IAAAA,OAAkC,GAAF,EAAE,CAAA;AAAA,GAAA;;EAElC,IAAI;IAAEC,cAAc,GAAG,CAAC,GAAD,CAAnB;IAA0BC,YAA1B;AAAwCC,IAAAA,QAAQ,GAAG,KAAA;AAAnD,GAAA,GAA6DH,OAAjE,CAAA;EACA,IAAII,OAAJ,CAHkC;;AAIlCA,EAAAA,OAAO,GAAGH,cAAc,CAACI,GAAf,CAAmB,CAACC,KAAD,EAAQC,KAAR,KAC3BC,oBAAoB,CAClBF,K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EI,mBAHN,CAAA;AAIA,EAAA,IAAI/a,IAAI,GAAG,OAAOrC,QAAP,KAAoB,QAApB,GAA+BA,QAA/B,GAA0CQ,UAAU,CAACR,QAAD,CAA/D,CAAA;AACA,EAAA,OAAO,IAAI0Z,GAAJ,CAAQrX,IAAR,EAAcH,IAAd,CAAP,CAAA;AACD;;;;"} \ No newline at end of file diff --git a/node_modules/@remix-run/router/dist/utils.d.ts b/node_modules/@remix-run/router/dist/utils.d.ts deleted file mode 100644 index 75d783b3..00000000 --- a/node_modules/@remix-run/router/dist/utils.d.ts +++ /dev/null @@ -1,359 +0,0 @@ -import type { Location, Path, To } from "./history"; -/** - * Map of routeId -> data returned from a loader/action/error - */ -export interface RouteData { - [routeId: string]: any; -} -export declare enum ResultType { - data = "data", - deferred = "deferred", - redirect = "redirect", - error = "error" -} -/** - * Successful result from a loader or action - */ -export interface SuccessResult { - type: ResultType.data; - data: any; - statusCode?: number; - headers?: Headers; -} -/** - * Successful defer() result from a loader or action - */ -export interface DeferredResult { - type: ResultType.deferred; - deferredData: DeferredData; -} -/** - * Redirect result from a loader or action - */ -export interface RedirectResult { - type: ResultType.redirect; - status: number; - location: string; - revalidate: boolean; -} -/** - * Unsuccessful result from a loader or action - */ -export interface ErrorResult { - type: ResultType.error; - error: any; - headers?: Headers; -} -/** - * Result from a loader or action - potentially successful or unsuccessful - */ -export declare type DataResult = SuccessResult | DeferredResult | RedirectResult | ErrorResult; -export declare type FormMethod = "get" | "post" | "put" | "patch" | "delete"; -export declare type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data"; -/** - * @private - * Internal interface to pass around for action submissions, not intended for - * external consumption - */ -export interface Submission { - formMethod: Exclude; - formAction: string; - formEncType: FormEncType; - formData: FormData; -} -/** - * @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 { - request: Request; - params: Params; -} -/** - * Arguments passed to loader functions - */ -export interface LoaderFunctionArgs extends DataFunctionArgs { -} -/** - * Arguments passed to action functions - */ -export interface ActionFunctionArgs extends DataFunctionArgs { -} -/** - * Route loader function signature - */ -export interface LoaderFunction { - (args: LoaderFunctionArgs): Promise | Response | Promise | any; -} -/** - * Route action function signature - */ -export interface ActionFunction { - (args: ActionFunctionArgs): Promise | Response | Promise | any; -} -/** - * 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: { - currentUrl: URL; - currentParams: AgnosticDataRouteMatch["params"]; - nextUrl: URL; - nextParams: AgnosticDataRouteMatch["params"]; - formMethod?: Submission["formMethod"]; - formAction?: Submission["formAction"]; - formEncType?: Submission["formEncType"]; - formData?: Submission["formData"]; - actionResult?: DataResult; - defaultShouldRevalidate: boolean; - }): boolean; -} -/** - * Base RouteObject with common props shared by all types of routes - */ -declare type AgnosticBaseRouteObject = { - caseSensitive?: boolean; - path?: string; - id?: string; - loader?: LoaderFunction; - action?: ActionFunction; - hasErrorBoundary?: boolean; - shouldRevalidate?: ShouldRevalidateFunction; - handle?: any; -}; -/** - * Index routes must not have children - */ -export declare type AgnosticIndexRouteObject = AgnosticBaseRouteObject & { - children?: undefined; - index: true; -}; -/** - * Non-index routes may have children, but cannot have index - */ -export declare 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 declare type AgnosticRouteObject = AgnosticIndexRouteObject | AgnosticNonIndexRouteObject; -export declare type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & { - id: string; -}; -export declare type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & { - children?: AgnosticDataRouteObject[]; - id: string; -}; -/** - * A data route object, which is just a RouteObject with a required unique ID - */ -export declare type AgnosticDataRouteObject = AgnosticDataIndexRouteObject | AgnosticDataNonIndexRouteObject; -declare type _PathParam = Path extends `${infer L}/${infer R}` ? _PathParam | _PathParam : Path extends `${string}:${infer Param}` ? Param : never; -/** - * Examples: - * "/a/b/*" -> "*" - * ":a" -> "a" - * "/a/:b" -> "b" - * "/a/blahblahblah:b" -> "b" - * "/:a/:b" -> "a" | "b" - * "/:a/b/:c/*" -> "a" | "c" | "*" - */ -declare type PathParam = Path extends "*" ? "*" : Path extends `${infer Rest}/*` ? "*" | _PathParam : _PathParam; -export declare type ParamParseKey = [ - PathParam -] extends [never] ? string : PathParam; -/** - * The parameters that were parsed from the URL path. - */ -export declare type Params = { - readonly [key in Key]: string | undefined; -}; -/** - * A RouteMatch contains info about how a route matched a URL. - */ -export interface AgnosticRouteMatch { - /** - * The names and values of dynamic parameters in the URL. - */ - params: Params; - /** - * 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 { -} -export declare function convertRoutesToDataRoutes(routes: AgnosticRouteObject[], parentPath?: number[], allIds?: Set): AgnosticDataRouteObject[]; -/** - * Matches the given routes to a location and returns the match data. - * - * @see https://reactrouter.com/docs/en/v6/utils/match-routes - */ -export declare function matchRoutes(routes: RouteObjectType[], locationArg: Partial | string, basename?: string): AgnosticRouteMatch[] | null; -/** - * Returns a path with params interpolated. - * - * @see https://reactrouter.com/docs/en/v6/utils/generate-path - */ -export declare function generatePath(path: Path, params?: { - [key in PathParam]: string; -}): string; -/** - * A PathPattern is used to match on some portion of a URL pathname. - */ -export interface PathPattern { - /** - * 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 { - /** - * The names and values of dynamic parameters in the URL. - */ - params: Params; - /** - * 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; -} -/** - * Performs pattern matching on a URL pathname and returns information about - * the match. - * - * @see https://reactrouter.com/docs/en/v6/utils/match-path - */ -export declare function matchPath, Path extends string>(pattern: PathPattern | Path, pathname: string): PathMatch | null; -/** - * @private - */ -export declare function stripBasename(pathname: string, basename: string): string | null; -/** - * @private - */ -export declare function invariant(value: boolean, message?: string): asserts value; -export declare function invariant(value: T | null | undefined, message?: string): asserts value is T; -/** - * @private - */ -export declare function warning(cond: any, message: string): void; -/** - * Returns a resolved path object relative to the given pathname. - * - * @see https://reactrouter.com/docs/en/v6/utils/resolve-path - */ -export declare function resolvePath(to: To, fromPathname?: string): Path; -/** - * @private - */ -export declare function resolveTo(toArg: To, routePathnames: string[], locationPathname: string, isPathRelative?: boolean): Path; -/** - * @private - */ -export declare function getToPathname(to: To): string | undefined; -/** - * @private - */ -export declare const joinPaths: (paths: string[]) => string; -/** - * @private - */ -export declare const normalizePathname: (pathname: string) => string; -/** - * @private - */ -export declare const normalizeSearch: (search: string) => string; -/** - * @private - */ -export declare const normalizeHash: (hash: string) => string; -export declare type JsonFunction = (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. - */ -export declare const json: JsonFunction; -export interface TrackedPromise extends Promise { - _tracked?: boolean; - _data?: any; - _error?: any; -} -export declare class AbortedDeferredError extends Error { -} -export declare class DeferredData { - private pendingKeys; - private controller; - private abortPromise; - private unlistenAbortSignal; - private subscriber?; - data: Record; - constructor(data: Record); - private trackPromise; - private onSettle; - subscribe(fn: (aborted: boolean) => void): void; - cancel(): void; - resolveData(signal: AbortSignal): Promise; - get done(): boolean; - get unwrappedData(): {}; -} -export declare function defer(data: Record): DeferredData; -export declare type RedirectFunction = (url: string, init?: number | ResponseInit) => Response; -/** - * A redirect response. Sets the status code and the `Location` header. - * Defaults to "302 Found". - */ -export declare const redirect: RedirectFunction; -/** - * @private - * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies - */ -export declare class ErrorResponse { - status: number; - statusText: string; - data: any; - constructor(status: number, statusText: string | undefined, data: any); -} -/** - * Check if the given error is an ErrorResponse generated from a 4xx/5xx - * Response throw from an action/loader - */ -export declare function isRouteErrorResponse(e: any): e is ErrorResponse; -export {}; diff --git a/node_modules/@remix-run/router/history.ts b/node_modules/@remix-run/router/history.ts deleted file mode 100644 index ce6d0c1f..00000000 --- a/node_modules/@remix-run/router/history.ts +++ /dev/null @@ -1,623 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -//#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; -} - -/** - * 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 extends Path { - /** - * A value of arbitrary data associated with this location. - */ - state: any; - - /** - * 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; -} - -/** - * 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`. May be either a URL or the pieces of a - * URL path. - */ -export type To = string | Partial; - -/** - * 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 attribute. - * - * @param to - The destination URL - */ - createHref(to: To): string; - - /** - * 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; -}; - -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; - -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; - } - - let history: MemoryHistory = { - get index() { - return index; - }, - get action() { - return action; - }, - get location() { - return getCurrentLocation(); - }, - createHref(to) { - return typeof to === "string" ? to : createPath(to); - }, - 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 }); - } - }, - replace(to, state) { - action = Action.Replace; - let nextLocation = createMemoryLocation(to, state); - entries[index] = nextLocation; - if (v5Compat && listener) { - listener({ action, location: nextLocation }); - } - }, - go(delta) { - action = Action.Pop; - index = clampIndex(index + delta); - if (listener) { - listener({ action, location: getCurrentLocation() }); - } - }, - 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)); - 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 -//////////////////////////////////////////////////////////////////////////////// - -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): HistoryState { - return { - usr: location.state, - key: location.key, - }; -} - -/** - * 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 { - let location: Readonly = { - 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) { - 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 { - let parsedPath: Partial = {}; - - 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; - - function handlePop() { - action = Action.Pop; - if (listener) { - listener({ action, location: history.location }); - } - } - - function push(to: To, state?: any) { - action = Action.Push; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - - let historyState = getHistoryState(location); - let url = history.createHref(location); - - // try...catch because iOS limits us to 100 pushState calls :/ - try { - globalHistory.pushState(historyState, "", url); - } catch (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 }); - } - } - - function replace(to: To, state?: any) { - action = Action.Replace; - let location = createLocation(history.location, to, state); - if (validateLocation) validateLocation(location, to); - - let historyState = getHistoryState(location); - let url = history.createHref(location); - globalHistory.replaceState(historyState, "", url); - - if (v5Compat && listener) { - listener({ action, location: location }); - } - } - - 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); - }, - push, - replace, - go(n) { - return globalHistory.go(n); - }, - }; - - return history; -} - -//#endregion diff --git a/node_modules/@remix-run/router/index.ts b/node_modules/@remix-run/router/index.ts deleted file mode 100644 index 4196adc3..00000000 --- a/node_modules/@remix-run/router/index.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { convertRoutesToDataRoutes } from "./utils"; - -export type { - ActionFunction, - ActionFunctionArgs, - AgnosticDataIndexRouteObject, - AgnosticDataNonIndexRouteObject, - AgnosticDataRouteMatch, - AgnosticDataRouteObject, - AgnosticIndexRouteObject, - AgnosticNonIndexRouteObject, - AgnosticRouteMatch, - AgnosticRouteObject, - TrackedPromise, - FormEncType, - FormMethod, - JsonFunction, - LoaderFunction, - LoaderFunctionArgs, - ParamParseKey, - Params, - PathMatch, - PathPattern, - RedirectFunction, - ShouldRevalidateFunction, - Submission, -} from "./utils"; - -export { - AbortedDeferredError, - ErrorResponse, - defer, - generatePath, - getToPathname, - invariant, - isRouteErrorResponse, - joinPaths, - json, - matchPath, - matchRoutes, - normalizePathname, - redirect, - resolvePath, - resolveTo, - stripBasename, - warning, -} from "./utils"; - -export type { - BrowserHistory, - BrowserHistoryOptions, - HashHistory, - HashHistoryOptions, - History, - InitialEntry, - Location, - MemoryHistory, - MemoryHistoryOptions, - Path, - To, -} from "./history"; - -export { - Action, - createBrowserHistory, - createPath, - createHashHistory, - createMemoryHistory, - 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 { convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes }; diff --git a/node_modules/@remix-run/router/package.json b/node_modules/@remix-run/router/package.json deleted file mode 100644 index a9db8732..00000000 --- a/node_modules/@remix-run/router/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "@remix-run/router", - "version": "1.0.2", - "description": "Nested/Data-driven/Framework-agnostic Routing", - "keywords": [ - "remix", - "router", - "location" - ], - "repository": { - "type": "git", - "url": "https://github.com/remix-run/react-router", - "directory": "packages/router" - }, - "license": "MIT", - "author": "Remix Software ", - "sideEffects": false, - "main": "./dist/router.cjs.js", - "module": "./dist/router.js", - "types": "./dist/index.d.ts", - "files": [ - "dist/", - "*.ts", - "CHANGELOG.md" - ], - "engines": { - "node": ">=14" - }, - "publishConfig": { - "access": "public" - } -} diff --git a/node_modules/@remix-run/router/router.ts b/node_modules/@remix-run/router/router.ts deleted file mode 100644 index 2e7e495c..00000000 --- a/node_modules/@remix-run/router/router.ts +++ /dev/null @@ -1,2854 +0,0 @@ -import type { History, Location, Path, To } from "./history"; -import { - Action as HistoryAction, - createLocation, - createPath, - parsePath, -} from "./history"; -import type { - DataResult, - AgnosticDataRouteMatch, - AgnosticDataRouteObject, - DeferredResult, - ErrorResult, - FormEncType, - FormMethod, - RedirectResult, - RouteData, - AgnosticRouteObject, - Submission, - SuccessResult, - AgnosticRouteMatch, -} from "./utils"; -import { - DeferredData, - ErrorResponse, - ResultType, - convertRoutesToDataRoutes, - invariant, - isRouteErrorResponse, - matchRoutes, -} 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 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 - * - * 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, - 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): void; - - /** - * Navigate to the given path - * @param to Path to navigate to - * @param opts Navigation options (method, submission, etc.) - */ - navigate(to: To, opts?: RouterNavigateOptions): 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, - opts?: RouterNavigateOptions - ): 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 - * - * Get/create a fetcher for the given key - * @param key - */ - getFetcher(key?: string): Fetcher; - - /** - * @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 - * - * Internal fetch AbortControllers accessed by unit tests - */ - _internalFetchControllers: Map; - - /** - * @internal - * PRIVATE - DO NOT USE - * - * Internal pending DeferredData instances accessed by unit tests - */ - _internalActiveDeferreds: Map; -} - -/** - * 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; -} - -/** - * Data that can be passed into hydrate a Router from SSR - */ -export type HydrationState = Partial< - Pick ->; - -/** - * Initialization options for createRouter - */ -export interface RouterInit { - basename?: string; - routes: AgnosticRouteObject[]; - history: History; - hydrationData?: HydrationState; -} - -/** - * State returned from a server-side query() call - */ -export interface StaticHandlerContext { - location: RouterState["location"]; - matches: RouterState["matches"]; - loaderData: RouterState["loaderData"]; - actionData: RouterState["actionData"]; - errors: RouterState["errors"]; - statusCode: number; - loaderHeaders: Record; - actionHeaders: Record; - _deepestRenderedBoundaryId?: string | null; -} - -/** - * A StaticHandler instance manages a singular SSR navigation/fetch event - */ -export interface StaticHandler { - dataRoutes: AgnosticDataRouteObject[]; - query(request: Request): Promise; - queryRoute(request: Request, routeId?: string): Promise; -} - -/** - * Subscriber function signature for changes to router state - */ -export interface RouterSubscriber { - (state: RouterState): void; -} - -interface UseMatchesMatch { - id: string; - pathname: string; - params: AgnosticRouteMatch["params"]; - data: unknown; - handle: unknown; -} - -/** - * Function signature for determining the key to be used in scroll restoration - * for a given location - */ -export interface GetScrollRestorationKeyFunction { - (location: Location, matches: UseMatchesMatch[]): string | null; -} - -/** - * Function signature for determining the current scroll position - */ -export interface GetScrollPositionFunction { - (): number; -} - -/** - * Options for a navigate() call for a Link navigation - */ -type LinkNavigateOptions = { - replace?: boolean; - state?: any; - preventScrollReset?: boolean; -}; - -/** - * Options for a navigate() call for a Form navigation - */ -type SubmissionNavigateOptions = { - replace?: boolean; - state?: any; - formMethod?: FormMethod; - formEncType?: FormEncType; - formData: FormData; -}; - -/** - * Options to pass to navigate() for either a Link or Form navigation - */ -export type RouterNavigateOptions = - | LinkNavigateOptions - | SubmissionNavigateOptions; - -/** - * Options to pass to fetch() - */ -export type RouterFetchOptions = - | Omit - | Omit; - -/** - * Potential states for state.navigation - */ -export type NavigationStates = { - Idle: { - state: "idle"; - location: undefined; - formMethod: undefined; - formAction: undefined; - formEncType: undefined; - formData: undefined; - }; - Loading: { - state: "loading"; - location: Location; - formMethod: FormMethod | undefined; - formAction: string | undefined; - formEncType: FormEncType | undefined; - formData: FormData | undefined; - }; - Submitting: { - state: "submitting"; - location: Location; - formMethod: FormMethod; - formAction: string; - formEncType: FormEncType; - formData: FormData; - }; -}; - -export type Navigation = NavigationStates[keyof NavigationStates]; - -export type RevalidationState = "idle" | "loading"; - -/** - * Potential states for fetchers - */ -type FetcherStates = { - Idle: { - state: "idle"; - formMethod: undefined; - formAction: undefined; - formEncType: undefined; - formData: undefined; - data: TData | undefined; - }; - Loading: { - state: "loading"; - formMethod: FormMethod | undefined; - formAction: string | undefined; - formEncType: FormEncType | undefined; - formData: FormData | undefined; - data: TData | undefined; - }; - Submitting: { - state: "submitting"; - formMethod: FormMethod; - formAction: string; - formEncType: FormEncType; - formData: FormData; - data: TData | undefined; - }; -}; - -export type Fetcher = - FetcherStates[keyof FetcherStates]; - -interface ShortCircuitable { - /** - * startNavigation does not need to complete the navigation because we - * redirected or got interrupted - */ - shortCircuited?: boolean; -} - -interface HandleActionResult extends ShortCircuitable { - /** - * Error thrown from the current action, keyed by the route containing the - * error boundary to render the error. To be committed to the state after - * loaders have completed - */ - pendingActionError?: RouteData; - /** - * Data returned from the current action, keyed by the route owning the action. - * To be committed to the state after loaders have completed - */ - pendingActionData?: RouteData; -} - -interface HandleLoadersResult extends ShortCircuitable { - /** - * loaderData returned from the current set of loaders - */ - loaderData?: RouterState["loaderData"]; - /** - * errors thrown from the current set of loaders - */ - errors?: RouterState["errors"]; -} - -/** - * Tuple of [key, href, DataRouterMatch] for a revalidating fetcher.load() - */ -type RevalidatingFetcher = [string, string, AgnosticDataRouteMatch]; - -/** - * Tuple of [href, DataRouteMatch] for an active fetcher.load() - */ -type FetchLoadMatch = [string, AgnosticDataRouteMatch]; - -export const IDLE_NAVIGATION: NavigationStates["Idle"] = { - state: "idle", - location: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, -}; - -export const IDLE_FETCHER: FetcherStates["Idle"] = { - state: "idle", - data: undefined, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, -}; -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region createRouter -//////////////////////////////////////////////////////////////////////////////// - -/** - * Create a router and listen to history POP navigations - */ -export function createRouter(init: RouterInit): Router { - invariant( - init.routes.length > 0, - "You must provide a non-empty routes array to createRouter" - ); - - let dataRoutes = convertRoutesToDataRoutes(init.routes); - // Cleanup function for history - let unlistenHistory: (() => void) | null = 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: Record | 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 until _after_ - // the initial render, we need to manually trigger a separate updateState to - // send along the restoreScrollPosition - let initialScrollRestored = false; - - let initialMatches = matchRoutes( - dataRoutes, - init.history.location, - init.basename - ); - let initialErrors: RouteData | null = null; - - if (initialMatches == null) { - // If we do not match a user-provided-route, fall back to the root - // to allow the error boundary to take over - let { matches, route, error } = getNotFoundMatches(dataRoutes); - initialMatches = matches; - initialErrors = { [route.id]: error }; - } - - let initialized = - !initialMatches.some((m) => m.route.loader) || init.hydrationData != null; - - let router: Router; - let state: RouterState = { - historyAction: init.history.action, - location: init.history.location, - matches: initialMatches, - initialized, - navigation: IDLE_NAVIGATION, - restoreScrollPosition: 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(), - }; - - // -- 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; - // 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) - // - useRevalidate() - // - 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: string[] = []; - // 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 from their actions - let fetchRedirectIds = new Set(); - // Most recent href/match for fetcher.load calls for fetchers - let fetchLoadMatches = new Map(); - // 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(); - - // 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 }) => - startNavigation(historyAction, location) - ); - - // Kick off initial data load if needed. Use Pop to avoid modifying history - if (!state.initialized) { - startNavigation(HistoryAction.Pop, state.location); - } - - return router; - } - - // Clean up a router and it's side effects - function dispose() { - if (unlistenHistory) { - unlistenHistory(); - } - subscribers.clear(); - pendingNavigationController && pendingNavigationController.abort(); - state.fetchers.forEach((_, key) => deleteFetcher(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): void { - state = { - ...state, - ...newState, - }; - subscribers.forEach((subscriber) => subscriber(state)); - } - - // 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> - ): void { - // Deduce if we're in a loading/actionReload state: - // - We have committed actionData in the store - // - The current navigation was a submission - // - We're past the submitting state and into the loading state - // - The location we've finished loading is different from the submission - // location, indicating we redirected from the action (avoids false - // positives for loading/submissionRedirect when actionData returned - // on a prior submission) - let isActionReload = - state.actionData != null && - state.navigation.formMethod != null && - state.navigation.state === "loading" && - state.navigation.formAction?.split("?")[0] === location.pathname; - - // Always preserve any existing loaderData from re-used routes - let newLoaderData = newState.loaderData - ? { - loaderData: mergeLoaderData( - state.loaderData, - newState.loaderData, - newState.matches || [] - ), - } - : {}; - - updateState({ - // Clear existing actionData on any completed navigation beyond the original - // action, unless we're currently finishing the loading/actionReload state. - // Do this prior to spreading in newState in case we got back to back actions - ...(isActionReload ? {} : { actionData: null }), - ...newState, - ...newLoaderData, - historyAction: pendingAction, - location, - initialized: true, - navigation: IDLE_NAVIGATION, - revalidation: "idle", - // Don't restore on submission navigations - restoreScrollPosition: state.navigation.formData - ? false - : getSavedScrollPosition(location, newState.matches || state.matches), - preventScrollReset: pendingPreventScrollReset, - }); - - 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); - } - - // Reset stateful navigation vars - pendingAction = HistoryAction.Pop; - pendingPreventScrollReset = false; - isUninterruptedRevalidation = false; - isRevalidationRequired = false; - cancelledDeferredRoutes = []; - cancelledFetcherLoads = []; - } - - // 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, - opts?: RouterNavigateOptions - ): Promise { - if (typeof to === "number") { - init.history.go(to); - return; - } - - let { path, submission, error } = normalizeNavigateOptions(to, opts); - - let location = createLocation(state.location, path, opts && opts.state); - let historyAction = - (opts && opts.replace) === true || submission != null - ? HistoryAction.Replace - : HistoryAction.Push; - let preventScrollReset = - opts && "preventScrollReset" in opts - ? opts.preventScrollReset === true - : undefined; - - return await startNavigation(historyAction, location, { - 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, - }); - } - - // 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 } - ); - } - - // 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?: { - submission?: Submission; - overrideNavigation?: Navigation; - pendingError?: ErrorResponse; - startUninterruptedRevalidation?: boolean; - preventScrollReset?: boolean; - replace?: boolean; - } - ): Promise { - // 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; - - let loadingNavigation = opts && opts.overrideNavigation; - let matches = matchRoutes(dataRoutes, location, init.basename); - - // Short circuit with a 404 on the root error boundary if we match nothing - if (!matches) { - let { - matches: notFoundMatches, - route, - error, - } = getNotFoundMatches(dataRoutes); - // Cancel all pending deferred on 404s since we don't keep any routes - cancelActiveDeferreds(); - completeNavigation(location, { - matches: notFoundMatches, - loaderData: {}, - errors: { - [route.id]: error, - }, - }); - return; - } - - // Short circuit if it's only a hash change - if (isHashChangeOnly(state.location, location)) { - completeNavigation(location, { matches }); - return; - } - - // Create a controller/Request for this navigation - pendingNavigationController = new AbortController(); - let request = createRequest( - location, - pendingNavigationController.signal, - opts && opts.submission - ); - let pendingActionData: RouteData | undefined; - let pendingError: RouteData | 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. - pendingError = { - [findNearestBoundary(matches).route.id]: opts.pendingError, - }; - } else if (opts && opts.submission) { - // Call action if we received an action submission - let actionOutput = await handleAction( - request, - location, - opts.submission, - matches, - { replace: opts.replace } - ); - - if (actionOutput.shortCircuited) { - return; - } - - pendingActionData = actionOutput.pendingActionData; - pendingError = actionOutput.pendingActionError; - - let navigation: NavigationStates["Loading"] = { - state: "loading", - location, - ...opts.submission, - }; - loadingNavigation = navigation; - } - - // Call loaders - let { shortCircuited, loaderData, errors } = await handleLoaders( - request, - location, - matches, - loadingNavigation, - opts && opts.submission, - opts && opts.replace, - pendingActionData, - pendingError - ); - - 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, - 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[], - opts?: { replace?: boolean } - ): Promise { - interruptActiveLoads(); - - // Put us in a submitting state - let navigation: NavigationStates["Submitting"] = { - state: "submitting", - location, - ...submission, - }; - updateState({ navigation }); - - // Call our action and get the result - let result: DataResult; - let actionMatch = getTargetMatch(matches, location); - - if (!actionMatch.route.action) { - result = getMethodNotAllowedResult(location); - } else { - result = await callLoaderOrAction("action", request, actionMatch); - - if (request.signal.aborted) { - return { shortCircuited: true }; - } - } - - if (isRedirectResult(result)) { - let redirectNavigation: NavigationStates["Loading"] = { - state: "loading", - location: createLocation(state.location, result.location), - ...submission, - }; - await startRedirectNavigation( - result, - redirectNavigation, - opts && opts.replace - ); - return { shortCircuited: true }; - } - - 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 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 { - pendingActionError: { [boundaryMatch.route.id]: result.error }, - }; - } - - if (isDeferredResult(result)) { - throw new Error("defer() is not supported in actions"); - } - - return { - pendingActionData: { [actionMatch.route.id]: result.data }, - }; - } - - // Call all applicable loaders for the given matches, handling redirects, - // errors, etc. - async function handleLoaders( - request: Request, - location: Location, - matches: AgnosticDataRouteMatch[], - overrideNavigation?: Navigation, - submission?: Submission, - replace?: boolean, - pendingActionData?: RouteData, - pendingError?: RouteData - ): Promise { - // Figure out the right navigation we want to use for data loading - let loadingNavigation = overrideNavigation; - if (!loadingNavigation) { - let navigation: NavigationStates["Loading"] = { - state: "loading", - location, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - }; - loadingNavigation = navigation; - } - - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad( - state, - matches, - submission, - location, - isRevalidationRequired, - cancelledDeferredRoutes, - cancelledFetcherLoads, - pendingActionData, - pendingError, - fetchLoadMatches - ); - - // 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)) - ); - - // Short circuit if we have no loaders to run - if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) { - completeNavigation(location, { - matches, - loaderData: mergeLoaderData(state.loaderData, {}, matches), - // Commit pending error if we're short circuiting - errors: pendingError || null, - actionData: pendingActionData || null, - }); - return { shortCircuited: true }; - } - - // 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 (!isUninterruptedRevalidation) { - revalidatingFetchers.forEach(([key]) => { - const fetcher = state.fetchers.get(key); - let revalidatingFetcher: FetcherStates["Loading"] = { - state: "loading", - data: fetcher && fetcher.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - }; - state.fetchers.set(key, revalidatingFetcher); - }); - updateState({ - navigation: loadingNavigation, - actionData: pendingActionData || state.actionData || null, - ...(revalidatingFetchers.length > 0 - ? { fetchers: new Map(state.fetchers) } - : {}), - }); - } - - pendingNavigationLoadId = ++incrementingLoadId; - revalidatingFetchers.forEach(([key]) => - fetchControllers.set(key, pendingNavigationController!) - ); - - let { results, 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 - revalidatingFetchers.forEach(([key]) => fetchControllers.delete(key)); - - // If any loaders returned a redirect Response, start a new REPLACE navigation - let redirect = findRedirect(results); - if (redirect) { - let redirectNavigation = getLoaderRedirect(state, redirect); - await startRedirectNavigation(redirect, redirectNavigation, replace); - return { shortCircuited: true }; - } - - // Process and commit output from loaders - let { loaderData, errors } = processLoaderData( - state, - matches, - matchesToLoad, - loaderResults, - pendingError, - 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); - } - }); - }); - - markFetchRedirectsDone(); - let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); - - return { - loaderData, - errors, - ...(didAbortFetchLoads || revalidatingFetchers.length > 0 - ? { fetchers: new Map(state.fetchers) } - : {}), - }; - } - - function getFetcher(key: string): Fetcher { - return state.fetchers.get(key) || IDLE_FETCHER; - } - - // Trigger a fetcher load/submit for the given fetcher key - function fetch( - key: string, - routeId: string, - href: string, - opts?: RouterFetchOptions - ) { - if (typeof AbortController === "undefined") { - throw new Error( - "router.fetch() was called during the server render, but it shouldn't be. " + - "You are likely calling a useFetcher() method in the body of your component. " + - "Try moving it to a useEffect or a callback." - ); - } - - if (fetchControllers.has(key)) abortFetcher(key); - - let matches = matchRoutes(dataRoutes, href, init.basename); - if (!matches) { - setFetcherError(key, routeId, new ErrorResponse(404, "Not Found", null)); - return; - } - - let { path, submission } = normalizeNavigateOptions(href, opts, true); - let match = getTargetMatch(matches, path); - - if (submission) { - handleFetcherAction(key, routeId, path, match, submission); - return; - } - - // Store off the match so we can call it's shouldRevalidate on subsequent - // revalidations - fetchLoadMatches.set(key, [path, match]); - handleFetcherLoader(key, routeId, path, match); - } - - // 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, - submission: Submission - ) { - interruptActiveLoads(); - fetchLoadMatches.delete(key); - - if (!match.route.action) { - let { error } = getMethodNotAllowedResult(path); - setFetcherError(key, routeId, error); - return; - } - - // Put this fetcher into it's submitting state - let existingFetcher = state.fetchers.get(key); - let fetcher: FetcherStates["Submitting"] = { - state: "submitting", - ...submission, - data: existingFetcher && existingFetcher.data, - }; - state.fetchers.set(key, fetcher); - updateState({ fetchers: new Map(state.fetchers) }); - - // Call the action for the fetcher - let abortController = new AbortController(); - let fetchRequest = createRequest(path, abortController.signal, submission); - fetchControllers.set(key, abortController); - - let actionResult = await callLoaderOrAction("action", fetchRequest, match); - - if (fetchRequest.signal.aborted) { - // We can delete this so long as we weren't aborted by ou our own fetcher - // re-submit which would have put _new_ controller is in fetchControllers - if (fetchControllers.get(key) === abortController) { - fetchControllers.delete(key); - } - return; - } - - if (isRedirectResult(actionResult)) { - fetchControllers.delete(key); - fetchRedirectIds.add(key); - let loadingFetcher: FetcherStates["Loading"] = { - state: "loading", - ...submission, - data: undefined, - }; - state.fetchers.set(key, loadingFetcher); - updateState({ fetchers: new Map(state.fetchers) }); - - let redirectNavigation: NavigationStates["Loading"] = { - state: "loading", - location: createLocation(state.location, actionResult.location), - ...submission, - }; - await startRedirectNavigation(actionResult, redirectNavigation); - return; - } - - // Process any non-redirect errors thrown - if (isErrorResult(actionResult)) { - setFetcherError(key, routeId, actionResult.error); - return; - } - - if (isDeferredResult(actionResult)) { - invariant(false, "defer() is not supported in actions"); - } - - // 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 = createRequest( - nextLocation, - abortController.signal - ); - let matches = - state.navigation.state !== "idle" - ? matchRoutes(dataRoutes, state.navigation.location, init.basename) - : state.matches; - - invariant(matches, "Didn't find any matches after fetcher action"); - - let loadId = ++incrementingLoadId; - fetchReloadIds.set(key, loadId); - - let loadFetcher: FetcherStates["Loading"] = { - state: "loading", - data: actionResult.data, - ...submission, - }; - state.fetchers.set(key, loadFetcher); - - let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad( - state, - matches, - submission, - nextLocation, - isRevalidationRequired, - cancelledDeferredRoutes, - cancelledFetcherLoads, - { [match.route.id]: actionResult.data }, - undefined, // No need to send through errors since we short circuit above - fetchLoadMatches - ); - - // 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(([staleKey]) => staleKey !== key) - .forEach(([staleKey]) => { - let existingFetcher = state.fetchers.get(staleKey); - let revalidatingFetcher: FetcherStates["Loading"] = { - state: "loading", - data: existingFetcher && existingFetcher.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - }; - state.fetchers.set(staleKey, revalidatingFetcher); - fetchControllers.set(staleKey, abortController); - }); - - updateState({ fetchers: new Map(state.fetchers) }); - - let { results, loaderResults, fetcherResults } = - await callLoadersAndMaybeResolveData( - state.matches, - matchesToLoad, - revalidatingFetchers, - revalidationRequest - ); - - if (abortController.signal.aborted) { - return; - } - - fetchReloadIds.delete(key); - fetchControllers.delete(key); - revalidatingFetchers.forEach(([staleKey]) => - fetchControllers.delete(staleKey) - ); - - let redirect = findRedirect(results); - if (redirect) { - let redirectNavigation = getLoaderRedirect(state, redirect); - await startRedirectNavigation(redirect, redirectNavigation); - return; - } - - // Process and commit output from loaders - let { loaderData, errors } = processLoaderData( - state, - state.matches, - matchesToLoad, - loaderResults, - undefined, - revalidatingFetchers, - fetcherResults, - activeDeferreds - ); - - let doneFetcher: FetcherStates["Idle"] = { - state: "idle", - data: actionResult.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - }; - state.fetchers.set(key, doneFetcher); - - let didAbortFetchLoads = 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), - ...(didAbortFetchLoads ? { 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 - ) { - let existingFetcher = state.fetchers.get(key); - // Put this fetcher into it's loading state - let loadingFetcher: FetcherStates["Loading"] = { - state: "loading", - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - data: existingFetcher && existingFetcher.data, - }; - state.fetchers.set(key, loadingFetcher); - updateState({ fetchers: new Map(state.fetchers) }); - - // Call the loader for this fetcher route match - let abortController = new AbortController(); - let fetchRequest = createRequest(path, abortController.signal); - fetchControllers.set(key, abortController); - let result: DataResult = await callLoaderOrAction( - "loader", - fetchRequest, - match - ); - - // Deferred isn't supported or 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 ou 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; - } - - // If the loader threw a redirect Response, start a new REPLACE navigation - if (isRedirectResult(result)) { - let redirectNavigation = getLoaderRedirect(state, result); - await startRedirectNavigation(result, redirectNavigation); - return; - } - - // Process any non-redirect errors thrown - if (isErrorResult(result)) { - let boundaryMatch = findNearestBoundary(state.matches, routeId); - state.fetchers.delete(key); - // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch - - // do we need to behave any differently with our non-redirect errors? - // What if it was a non-redirect Response? - updateState({ - fetchers: new Map(state.fetchers), - errors: { - [boundaryMatch.route.id]: result.error, - }, - }); - return; - } - - invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); - - // Put the fetcher back into an idle state - let doneFetcher: FetcherStates["Idle"] = { - state: "idle", - data: result.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - }; - state.fetchers.set(key, doneFetcher); - updateState({ fetchers: new Map(state.fetchers) }); - } - - /** - * 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( - redirect: RedirectResult, - navigation: Navigation, - replace?: boolean - ) { - if (redirect.revalidate) { - isRevalidationRequired = true; - } - invariant( - navigation.location, - "Expected a location on the redirect navigation" - ); - // 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 ? HistoryAction.Replace : HistoryAction.Push; - await startNavigation(redirectHistoryAction, navigation.location, { - overrideNavigation: navigation, - }); - } - - async function callLoadersAndMaybeResolveData( - currentMatches: AgnosticDataRouteMatch[], - matchesToLoad: AgnosticDataRouteMatch[], - fetchersToLoad: RevalidatingFetcher[], - request: Request - ) { - // Call all navigation loaders and revalidating fetcher loaders in parallel, - // then slice off the results into separate arrays so we can handle them - // accordingly - let results = await Promise.all([ - ...matchesToLoad.map((m) => callLoaderOrAction("loader", request, m)), - ...fetchersToLoad.map(([, href, match]) => - callLoaderOrAction("loader", createRequest(href, request.signal), match) - ), - ]); - let loaderResults = results.slice(0, matchesToLoad.length); - let fetcherResults = results.slice(matchesToLoad.length); - - await Promise.all([ - resolveDeferredResults( - currentMatches, - matchesToLoad, - loaderResults, - request.signal, - false, - state.loaderData - ), - resolveDeferredResults( - currentMatches, - fetchersToLoad.map(([, , match]) => match), - fetcherResults, - request.signal, - true - ), - ]); - - return { results, 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.push(key); - abortFetcher(key); - } - }); - } - - function setFetcherError(key: string, routeId: string, error: any) { - let boundaryMatch = findNearestBoundary(state.matches, routeId); - deleteFetcher(key); - updateState({ - errors: { - [boundaryMatch.route.id]: error, - }, - fetchers: new Map(state.fetchers), - }); - } - - function deleteFetcher(key: string): void { - if (fetchControllers.has(key)) abortFetcher(key); - fetchLoadMatches.delete(key); - fetchReloadIds.delete(key); - fetchRedirectIds.delete(key); - state.fetchers.delete(key); - } - - function abortFetcher(key: string) { - let controller = fetchControllers.get(key); - invariant(controller, `Expected fetch controller: ${key}`); - controller.abort(); - fetchControllers.delete(key); - } - - function markFetchersDone(keys: string[]) { - for (let key of keys) { - let fetcher = getFetcher(key); - let doneFetcher: FetcherStates["Idle"] = { - state: "idle", - data: fetcher.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - }; - state.fetchers.set(key, doneFetcher); - } - } - - function markFetchRedirectsDone(): void { - let doneKeys = []; - 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); - } - } - markFetchersDone(doneKeys); - } - - 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 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 component - function enableScrollRestoration( - positions: Record, - getPosition: GetScrollPositionFunction, - getKey?: GetScrollRestorationKeyFunction - ) { - savedScrollPositions = positions; - getScrollPosition = getPosition; - getScrollRestorationKey = getKey || ((location) => location.key); - - // Perform initial hydration scroll restoration, since we miss the boat on - // the initial updateState() because we've not yet rendered - // 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 saveScrollPosition( - location: Location, - matches: AgnosticDataRouteMatch[] - ): void { - if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) { - let userMatches = matches.map((m) => - createUseMatchesMatch(m, state.loaderData) - ); - let key = getScrollRestorationKey(location, userMatches) || location.key; - savedScrollPositions[key] = getScrollPosition(); - } - } - - function getSavedScrollPosition( - location: Location, - matches: AgnosticDataRouteMatch[] - ): number | null { - if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) { - let userMatches = matches.map((m) => - createUseMatchesMatch(m, state.loaderData) - ); - let key = getScrollRestorationKey(location, userMatches) || location.key; - let y = savedScrollPositions[key]; - if (typeof y === "number") { - return y; - } - } - return null; - } - - router = { - get basename() { - return init.basename; - }, - get state() { - return state; - }, - get routes() { - return dataRoutes; - }, - initialize, - subscribe, - enableScrollRestoration, - navigate, - fetch, - revalidate, - createHref, - getFetcher, - deleteFetcher, - dispose, - _internalFetchControllers: fetchControllers, - _internalActiveDeferreds: activeDeferreds, - }; - - return router; -} -//#endregion - -//////////////////////////////////////////////////////////////////////////////// -//#region createStaticHandler -//////////////////////////////////////////////////////////////////////////////// - -export function unstable_createStaticHandler( - routes: AgnosticRouteObject[] -): StaticHandler { - invariant( - routes.length > 0, - "You must provide a non-empty routes array to unstable_createStaticHandler" - ); - - let dataRoutes = convertRoutesToDataRoutes(routes); - - async function query( - request: Request - ): Promise { - let { location, result } = await queryImpl(request); - if (result instanceof Response) { - 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, ...result }; - } - - async function queryRoute(request: Request, routeId: string): Promise { - let { result } = await queryImpl(request, routeId); - if (result instanceof Response) { - return result; - } - - let error = result.errors ? Object.values(result.errors)[0] : undefined; - if (error !== undefined) { - // While we always re-throw Responses returned from loaders/actions - // directly for route requests and prevent the unwrapping into an - // ErrorResponse, we still need this for error cases _prior_ the - // execution of the loader/action, such as a 404/405 error. - if (isRouteErrorResponse(error)) { - return new Response(error.data, { - status: error.status, - statusText: error.statusText, - }); - } - // 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 - let routeData = [result.actionData, result.loaderData].find((v) => v); - let value = Object.values(routeData || {})[0]; - - if (isRouteErrorResponse(value)) { - return new Response(value.data, { - status: value.status, - statusText: value.statusText, - }); - } - - return value; - } - - async function queryImpl( - request: Request, - routeId?: string - ): Promise<{ - location: Location; - result: Omit | Response; - }> { - invariant( - request.method !== "HEAD", - "query()/queryRoute() do not support HEAD requests" - ); - invariant( - request.signal, - "query()/queryRoute() requests must contain an AbortController signal" - ); - - let { location, matches, shortCircuitState } = matchRequest( - request, - routeId - ); - - try { - if (shortCircuitState) { - return { location, result: shortCircuitState }; - } - - if (request.method !== "GET") { - let result = await submit( - request, - matches, - getTargetMatch(matches, location), - routeId != null - ); - return { location, result }; - } - - let result = await loadRouteData(request, matches, routeId != null); - return { - location, - result: { - ...result, - actionData: null, - actionHeaders: {}, - }, - }; - } catch (e) { - if (e instanceof Response) { - return { location, result: e }; - } - throw e; - } - } - - async function submit( - request: Request, - matches: AgnosticDataRouteMatch[], - actionMatch: AgnosticDataRouteMatch, - isRouteRequest: boolean - ): Promise | Response> { - let result: DataResult; - if (!actionMatch.route.action) { - let href = createHref(new URL(request.url)); - result = getMethodNotAllowedResult(href); - } else { - result = await callLoaderOrAction( - "action", - request, - actionMatch, - true, - isRouteRequest - ); - - if (request.signal.aborted) { - let method = isRouteRequest ? "queryRoute" : "query"; - throw new Error(`${method}() call aborted`); - } - } - - if (isRedirectResult(result)) { - // Uhhhh - this should never happen, we should always throw these from - // calLoaderOrAction, 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.status, - headers: { - Location: result.location, - }, - }); - } - - if (isDeferredResult(result)) { - throw new Error("defer() is not supported in actions"); - } - - if (isRouteRequest) { - if (isErrorResult(result)) { - let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); - return { - matches: [actionMatch], - loaderData: {}, - actionData: null, - errors: { - [boundaryMatch.route.id]: result.error, - }, - // Note: statusCode + headers are unused here since queryRoute will - // return the raw Response or value - statusCode: 500, - loaderHeaders: {}, - actionHeaders: {}, - }; - } - - 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: {}, - }; - } - - 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); - let context = await loadRouteData(request, matches, isRouteRequest, { - [boundaryMatch.route.id]: result.error, - }); - - // action status codes take precedence over loader status codes - return { - ...context, - statusCode: isRouteErrorResponse(result.error) - ? result.error.status - : 500, - actionData: null, - actionHeaders: { - ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}), - }, - }; - } - - let context = await loadRouteData(request, matches, isRouteRequest); - - return { - ...context, - // action status codes take precedence over loader status codes - ...(result.statusCode ? { statusCode: result.statusCode } : {}), - actionData: { - [actionMatch.route.id]: result.data, - }, - actionHeaders: { - ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}), - }, - }; - } - - async function loadRouteData( - request: Request, - matches: AgnosticDataRouteMatch[], - isRouteRequest: boolean, - pendingActionError?: RouteData - ): Promise< - | Omit - | Response - > { - let matchesToLoad = getLoaderMatchesUntilBoundary( - matches, - Object.keys(pendingActionError || {})[0] - ).filter((m) => m.route.loader); - - // Short circuit if we have no loaders to run - if (matchesToLoad.length === 0) { - return { - matches, - loaderData: {}, - errors: pendingActionError || null, - statusCode: 200, - loaderHeaders: {}, - }; - } - - let results = await Promise.all([ - ...matchesToLoad.map((m) => - callLoaderOrAction("loader", request, m, true, isRouteRequest) - ), - ]); - - if (request.signal.aborted) { - let method = isRouteRequest ? "queryRoute" : "query"; - throw new Error(`${method}() call aborted`); - } - - // Can't do anything with these without the Remix side of things, so just - // cancel them for now - results.forEach((result) => { - if (isDeferredResult(result)) { - result.deferredData.cancel(); - } - }); - - // Process and commit output from loaders - let context = processRouteLoaderData( - matches, - matchesToLoad, - results, - pendingActionError - ); - - return { - ...context, - matches, - }; - } - - function matchRequest( - req: Request, - routeId?: string - ): { - location: Location; - matches: AgnosticDataRouteMatch[]; - routeMatch?: AgnosticDataRouteMatch; - shortCircuitState?: Omit; - } { - let url = new URL(req.url); - let location = createLocation("", createPath(url), null, "default"); - let matches = matchRoutes(dataRoutes, location); - if (matches && routeId) { - matches = matches.filter((m) => m.route.id === routeId); - } - - // Short circuit with a 404 if we match nothing - if (!matches) { - let { - matches: notFoundMatches, - route, - error, - } = getNotFoundMatches(dataRoutes); - return { - location, - matches: notFoundMatches, - shortCircuitState: { - matches: notFoundMatches, - loaderData: {}, - actionData: null, - errors: { - [route.id]: error, - }, - statusCode: 404, - loaderHeaders: {}, - actionHeaders: {}, - }, - }; - } - - return { location, matches }; - } - - 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: 500, - errors: { - [context._deepestRenderedBoundaryId || routes[0].id]: error, - }, - }; - return newContext; -} - -// Normalize navigation options by converting formMethod=GET formData objects to -// URLSearchParams so they behave identically to links with query params -function normalizeNavigateOptions( - to: To, - opts?: RouterNavigateOptions, - isFetcher = false -): { - path: string; - submission?: Submission; - error?: ErrorResponse; -} { - let path = typeof to === "string" ? to : createPath(to); - - // Return location verbatim on non-submission navigations - if (!opts || (!("formMethod" in opts) && !("formData" in opts))) { - return { path }; - } - - // Create a Submission on non-GET navigations - if (opts.formMethod != null && opts.formMethod !== "get") { - return { - path, - submission: { - formMethod: opts.formMethod, - formAction: createHref(parsePath(path)), - formEncType: - (opts && opts.formEncType) || "application/x-www-form-urlencoded", - formData: opts.formData, - }, - }; - } - - // No formData to flatten for GET submission - if (!opts.formData) { - return { path }; - } - - // Flatten submission onto URLSearchParams for GET submissions - let parsedPath = parsePath(path); - try { - let searchParams = convertFormDataToSearchParams(opts.formData); - // Since fetcher GET submissions only run a single loader (as opposed to - // navigation GET submissions which run all loaders), we need to preserve - // any incoming ?index params - if ( - isFetcher && - parsedPath.search && - hasNakedIndexQuery(parsedPath.search) - ) { - searchParams.append("index", ""); - } - parsedPath.search = `?${searchParams}`; - } catch (e) { - return { - path, - error: new ErrorResponse( - 400, - "Bad Request", - "Cannot submit binary form data using GET" - ), - }; - } - - return { path: createPath(parsedPath) }; -} - -function getLoaderRedirect( - state: RouterState, - redirect: RedirectResult -): Navigation { - let { formMethod, formAction, formEncType, formData } = state.navigation; - let navigation: NavigationStates["Loading"] = { - state: "loading", - location: createLocation(state.location, redirect.location), - formMethod: formMethod || undefined, - formAction: formAction || undefined, - formEncType: formEncType || undefined, - formData: formData || undefined, - }; - return navigation; -} - -// Filter out all routes 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 -) { - let boundaryMatches = matches; - if (boundaryId) { - let index = matches.findIndex((m) => m.route.id === boundaryId); - if (index >= 0) { - boundaryMatches = matches.slice(0, index); - } - } - return boundaryMatches; -} - -function getMatchesToLoad( - state: RouterState, - matches: AgnosticDataRouteMatch[], - submission: Submission | undefined, - location: Location, - isRevalidationRequired: boolean, - cancelledDeferredRoutes: string[], - cancelledFetcherLoads: string[], - pendingActionData?: RouteData, - pendingError?: RouteData, - fetchLoadMatches?: Map -): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] { - let actionResult = pendingError - ? Object.values(pendingError)[0] - : pendingActionData - ? Object.values(pendingActionData)[0] - : null; - - // Pick navigation matches that are net-new or qualify for revalidation - let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined; - let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId); - let navigationMatches = boundaryMatches.filter( - (match, index) => - match.route.loader != null && - (isNewLoader(state.loaderData, state.matches[index], match) || - // If this route had a pending deferred cancelled it must be revalidated - cancelledDeferredRoutes.some((id) => id === match.route.id) || - shouldRevalidateLoader( - state.location, - state.matches[index], - submission, - location, - match, - isRevalidationRequired, - actionResult - )) - ); - - // Pick fetcher.loads that need to be revalidated - let revalidatingFetchers: RevalidatingFetcher[] = []; - fetchLoadMatches && - fetchLoadMatches.forEach(([href, match], key) => { - // This fetcher was cancelled from a prior action submission - force reload - if (cancelledFetcherLoads.includes(key)) { - revalidatingFetchers.push([key, href, match]); - } else if (isRevalidationRequired) { - let shouldRevalidate = shouldRevalidateLoader( - href, - match, - submission, - href, - match, - isRevalidationRequired, - actionResult - ); - if (shouldRevalidate) { - revalidatingFetchers.push([key, href, match]); - } - } - }); - - return [navigationMatches, revalidatingFetchers]; -} - -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 && - currentPath.endsWith("*") && - currentMatch.params["*"] !== match.params["*"]) - ); -} - -function shouldRevalidateLoader( - currentLocation: string | Location, - currentMatch: AgnosticDataRouteMatch, - submission: Submission | undefined, - location: string | Location, - match: AgnosticDataRouteMatch, - isRevalidationRequired: boolean, - actionResult: DataResult | undefined -) { - let currentUrl = createURL(currentLocation); - let currentParams = currentMatch.params; - let nextUrl = createURL(location); - let nextParams = match.params; - - // This is the default implementation as to 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 - // Note that fetchers always provide the same current/next locations so the - // URL-based checks here don't apply to fetcher shouldRevalidate calls - let defaultShouldRevalidate = - isNewRouteInstance(currentMatch, match) || - // Clicked the same link, resubmitted a GET form - currentUrl.toString() === nextUrl.toString() || - // Search params affect all loaders - currentUrl.search !== nextUrl.search || - // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate - isRevalidationRequired; - - if (match.route.shouldRevalidate) { - let routeChoice = match.route.shouldRevalidate({ - currentUrl, - currentParams, - nextUrl, - nextParams, - ...submission, - actionResult, - defaultShouldRevalidate, - }); - if (typeof routeChoice === "boolean") { - return routeChoice; - } - } - - return defaultShouldRevalidate; -} - -async function callLoaderOrAction( - type: "loader" | "action", - request: Request, - match: AgnosticDataRouteMatch, - skipRedirects: boolean = false, - isRouteRequest: boolean = false -): Promise { - let resultType; - let result; - - // Setup a promise we can race against so that abort signals short circuit - let reject: () => void; - let abortPromise = new Promise((_, r) => (reject = r)); - let onReject = () => reject(); - request.signal.addEventListener("abort", onReject); - - try { - let handler = match.route[type]; - invariant( - handler, - `Could not find the ${type} to run on the "${match.route.id}" route` - ); - - result = await Promise.race([ - handler({ request, params: match.params }), - abortPromise, - ]); - } catch (e) { - resultType = ResultType.error; - result = e; - } finally { - request.signal.removeEventListener("abort", onReject); - } - - if (result instanceof Response) { - // Process redirects - let status = result.status; - let location = result.headers.get("Location"); - - // For SSR single-route requests, we want to hand Responses back directly - // without unwrapping - if (isRouteRequest) { - throw result; - } - - if (status >= 300 && status <= 399 && location != null) { - // Don't process redirects in the router during SSR document requests. - // Instead, throw the Response and let the server handle it with an HTTP - // redirect - if (skipRedirects) { - throw result; - } - return { - type: ResultType.redirect, - status, - location, - revalidate: result.headers.get("X-Remix-Revalidate") !== null, - }; - } - - let data: any; - let contentType = result.headers.get("Content-Type"); - if (contentType && contentType.startsWith("application/json")) { - data = await result.json(); - } else { - data = await result.text(); - } - - if (resultType === ResultType.error) { - return { - type: resultType, - error: new ErrorResponse(status, result.statusText, data), - headers: result.headers, - }; - } - - return { - type: ResultType.data, - data, - statusCode: result.status, - headers: result.headers, - }; - } - - if (resultType === ResultType.error) { - return { type: resultType, error: result }; - } - - if (result instanceof DeferredData) { - return { type: ResultType.deferred, deferredData: result }; - } - - return { type: ResultType.data, data: result }; -} - -function createRequest( - location: string | Location, - signal: AbortSignal, - submission?: Submission -): Request { - let url = createURL(location).toString(); - let init: RequestInit = { signal }; - - if (submission) { - let { formMethod, formEncType, formData } = submission; - init.method = formMethod.toUpperCase(); - init.body = - formEncType === "application/x-www-form-urlencoded" - ? convertFormDataToSearchParams(formData) - : formData; - } - - // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) - return new Request(url, init); -} - -function convertFormDataToSearchParams(formData: FormData): URLSearchParams { - let searchParams = new URLSearchParams(); - - for (let [key, value] of formData.entries()) { - invariant( - typeof value === "string", - 'File inputs are not supported with encType "application/x-www-form-urlencoded", ' + - 'please use "multipart/form-data" instead.' - ); - searchParams.append(key, value); - } - - return searchParams; -} - -function processRouteLoaderData( - matches: AgnosticDataRouteMatch[], - matchesToLoad: AgnosticDataRouteMatch[], - results: DataResult[], - pendingError: RouteData | undefined, - activeDeferreds?: Map -): { - loaderData: RouterState["loaderData"]; - errors: RouterState["errors"] | null; - statusCode: number; - loaderHeaders: Record; -} { - // 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 = {}; - - // Process loader results into state.loaderData/state.errors - results.forEach((result, index) => { - let id = matchesToLoad[index].route.id; - invariant( - !isRedirectResult(result), - "Cannot handle redirect results in processLoaderData" - ); - if (isErrorResult(result)) { - // Look upwards from the matched route for the closest ancestor - // error boundary, defaulting to the root match - let boundaryMatch = findNearestBoundary(matches, id); - 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) { - error = Object.values(pendingError)[0]; - pendingError = undefined; - } - errors = Object.assign(errors || {}, { - [boundaryMatch.route.id]: error, - }); - // 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 && activeDeferreds.set(id, result.deferredData); - loaderData[id] = result.deferredData.data; - // TODO: Add statusCode/headers once we wire up streaming in Remix - } 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 != null && - 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 - if (pendingError) { - errors = pendingError; - } - - return { - loaderData, - errors, - statusCode: statusCode || 200, - loaderHeaders, - }; -} - -function processLoaderData( - state: RouterState, - matches: AgnosticDataRouteMatch[], - matchesToLoad: AgnosticDataRouteMatch[], - results: DataResult[], - pendingError: RouteData | undefined, - revalidatingFetchers: RevalidatingFetcher[], - fetcherResults: DataResult[], - activeDeferreds: Map -): { - loaderData: RouterState["loaderData"]; - errors?: RouterState["errors"]; -} { - let { loaderData, errors } = processRouteLoaderData( - matches, - matchesToLoad, - results, - pendingError, - activeDeferreds - ); - - // Process results from our revalidating fetchers - for (let index = 0; index < revalidatingFetchers.length; index++) { - let [key, , match] = revalidatingFetchers[index]; - invariant( - fetcherResults !== undefined && fetcherResults[index] !== undefined, - "Did not find corresponding fetcher result" - ); - let result = fetcherResults[index]; - - // Process fetcher non-redirect errors - 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 - throw new Error("Unhandled fetcher revalidation redirect"); - } else if (isDeferredResult(result)) { - // Should never get here, deferred data should be awaited for fetchers - // in resolveDeferredResults - throw new Error("Unhandled fetcher deferred data"); - } else { - let doneFetcher: FetcherStates["Idle"] = { - state: "idle", - data: result.data, - formMethod: undefined, - formAction: undefined, - formEncType: undefined, - formData: undefined, - }; - state.fetchers.set(key, doneFetcher); - } - } - - return { loaderData, errors }; -} - -function mergeLoaderData( - loaderData: RouteData, - newLoaderData: RouteData, - matches: AgnosticDataRouteMatch[] -): RouteData { - let mergedLoaderData = { ...newLoaderData }; - matches.forEach((match) => { - let id = match.route.id; - if (newLoaderData[id] === undefined && loaderData[id] !== undefined) { - mergedLoaderData[id] = loaderData[id]; - } - }); - return mergedLoaderData; -} - -// 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 getNotFoundMatches(routes: AgnosticDataRouteObject[]): { - matches: AgnosticDataRouteMatch[]; - route: AgnosticDataRouteObject; - error: ErrorResponse; -} { - // Prefer a root layout route if present, otherwise shim in a route object - let route = routes.find( - (r) => r.index || r.path === "" || r.path === "/" - ) || { - id: "__shim-404-route__", - }; - - return { - matches: [ - { - params: {}, - pathname: "", - pathnameBase: "", - route, - }, - ], - route, - error: new ErrorResponse(404, "Not Found", null), - }; -} - -function getMethodNotAllowedResult(path: Location | string): ErrorResult { - let href = typeof path === "string" ? path : createHref(path); - console.warn( - "You're trying to submit to a route that does not have an action. To " + - "fix this, please add an `action` function to the route for " + - `[${href}]` - ); - return { - type: ResultType.error, - error: new ErrorResponse( - 405, - "Method Not Allowed", - `No action found for [${href}]` - ), - }; -} - -// Find any returned redirect errors, starting from the lowest match -function findRedirect(results: DataResult[]): RedirectResult | undefined { - for (let i = results.length - 1; i >= 0; i--) { - let result = results[i]; - if (isRedirectResult(result)) { - return result; - } - } -} - -// Create an href to represent a "server" URL without the hash -function createHref(location: Partial | Location | URL) { - return (location.pathname || "") + (location.search || ""); -} - -function isHashChangeOnly(a: Location, b: Location): boolean { - return ( - a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash - ); -} - -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; -} - -async function resolveDeferredResults( - currentMatches: AgnosticDataRouteMatch[], - matchesToLoad: AgnosticDataRouteMatch[], - results: DataResult[], - signal: AbortSignal, - isFetcher: boolean, - currentLoaderData?: RouteData -) { - for (let index = 0; index < results.length; index++) { - let result = results[index]; - let match = matchesToLoad[index]; - 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) && (isFetcher || 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, isFetcher).then((result) => { - if (result) { - results[index] = result || results[index]; - } - }); - } - } -} - -async function resolveDeferredData( - result: DeferredResult, - signal: AbortSignal, - unwrap = false -): Promise { - 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 === ""); -} - -// Note: This should match the format exported by useMatches, so if you change -// this please also change that :) Eventually we'll DRY this up -function createUseMatchesMatch( - match: AgnosticDataRouteMatch, - loaderData: RouteData -): UseMatchesMatch { - let { route, pathname, params } = match; - return { - id: route.id, - pathname, - params, - data: loaderData[route.id] as unknown, - handle: route.handle as unknown, - }; -} - -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 matches.slice(-2)[0]; - } - return matches.slice(-1)[0]; -} - -function createURL(location: Location | string): URL { - let base = - typeof window !== "undefined" && typeof window.location !== "undefined" - ? window.location.origin - : "unknown://unknown"; - let href = typeof location === "string" ? location : createHref(location); - return new URL(href, base); -} -//#endregion diff --git a/node_modules/@remix-run/router/utils.ts b/node_modules/@remix-run/router/utils.ts deleted file mode 100644 index 7fe1cec1..00000000 --- a/node_modules/@remix-run/router/utils.ts +++ /dev/null @@ -1,1204 +0,0 @@ -import type { Location, Path, To } from "./history"; -import { parsePath } 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: any; - statusCode?: number; - headers?: Headers; -} - -/** - * Successful defer() result from a loader or action - */ -export interface DeferredResult { - type: ResultType.deferred; - deferredData: DeferredData; -} - -/** - * Redirect result from a loader or action - */ -export interface RedirectResult { - type: ResultType.redirect; - status: number; - location: string; - revalidate: boolean; -} - -/** - * Unsuccessful result from a loader or action - */ -export interface ErrorResult { - type: ResultType.error; - error: any; - headers?: Headers; -} - -/** - * Result from a loader or action - potentially successful or unsuccessful - */ -export type DataResult = - | SuccessResult - | DeferredResult - | RedirectResult - | ErrorResult; - -export type FormMethod = "get" | "post" | "put" | "patch" | "delete"; -export type FormEncType = - | "application/x-www-form-urlencoded" - | "multipart/form-data"; - -/** - * @private - * Internal interface to pass around for action submissions, not intended for - * external consumption - */ -export interface Submission { - formMethod: Exclude; - formAction: string; - formEncType: FormEncType; - formData: FormData; -} - -/** - * @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 { - request: Request; - params: Params; -} - -/** - * Arguments passed to loader functions - */ -export interface LoaderFunctionArgs extends DataFunctionArgs {} - -/** - * Arguments passed to action functions - */ -export interface ActionFunctionArgs extends DataFunctionArgs {} - -/** - * Route loader function signature - */ -export interface LoaderFunction { - (args: LoaderFunctionArgs): Promise | Response | Promise | any; -} - -/** - * Route action function signature - */ -export interface ActionFunction { - (args: ActionFunctionArgs): Promise | Response | Promise | any; -} - -/** - * 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: { - currentUrl: URL; - currentParams: AgnosticDataRouteMatch["params"]; - nextUrl: URL; - nextParams: AgnosticDataRouteMatch["params"]; - formMethod?: Submission["formMethod"]; - formAction?: Submission["formAction"]; - formEncType?: Submission["formEncType"]; - formData?: Submission["formData"]; - actionResult?: DataResult; - defaultShouldRevalidate: boolean; - }): boolean; -} - -/** - * Base RouteObject with common props shared by all types of routes - */ -type AgnosticBaseRouteObject = { - caseSensitive?: boolean; - path?: string; - id?: string; - loader?: LoaderFunction; - action?: ActionFunction; - hasErrorBoundary?: boolean; - shouldRevalidate?: ShouldRevalidateFunction; - handle?: any; -}; - -/** - * 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; - -// Recursive helper for finding path parameters in the absence of wildcards -type _PathParam = - // split path into individual path segments - Path extends `${infer L}/${infer R}` - ? _PathParam | _PathParam - : // find params after `:` - Path extends `${string}:${infer Param}` - ? 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" | "*" - */ -type PathParam = - // check if path is just a wildcard - Path extends "*" - ? "*" - : // look for wildcard at the end of the path - Path extends `${infer Rest}/*` - ? "*" | _PathParam - : // look for params in the absence of wildcards - _PathParam; - -// 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 = - // if could not find path params, fallback to `string` - [PathParam] extends [never] ? string : PathParam; - -/** - * The parameters that were parsed from the URL path. - */ -export type Params = { - 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; - /** - * 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 {} - -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[], - parentPath: number[] = [], - allIds: Set = new Set() -): AgnosticDataRouteObject[] { - return routes.map((route, index) => { - let treePath = [...parentPath, index]; - let id = typeof route.id === "string" ? route.id : treePath.join("-"); - invariant( - route.index !== true || !route.children, - `Cannot specify children on an index route` - ); - invariant( - !allIds.has(id), - `Found a route id collision on id "${id}". Route ` + - "id's must be globally unique within Data Router usages" - ); - allIds.add(id); - - if (isIndexRoute(route)) { - let indexRoute: AgnosticDataIndexRouteObject = { ...route, id }; - return indexRoute; - } else { - let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = { - ...route, - id, - children: route.children - ? convertRoutesToDataRoutes(route.children, treePath, allIds) - : undefined, - }; - return pathOrLayoutRoute; - } - }); -} - -/** - * Matches the given routes to a location and returns the match data. - * - * @see https://reactrouter.com/docs/en/v6/utils/match-routes - */ -export function matchRoutes< - RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject ->( - routes: RouteObjectType[], - locationArg: Partial | string, - basename = "/" -): AgnosticRouteMatch[] | 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; - for (let i = 0; matches == null && i < branches.length; ++i) { - matches = matchRouteBranch(branches[i], pathname); - } - - return matches; -} - -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[]; -} - -function flattenRoutes< - RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject ->( - routes: RouteObjectType[], - branches: RouteBranch[] = [], - parentsMeta: RouteMeta[] = [], - parentPath = "" -): RouteBranch[] { - routes.forEach((route, index) => { - let meta: RouteMeta = { - relativePath: route.path || "", - 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 }); - }); - - return branches; -} - -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, - pathname: string -): AgnosticRouteMatch[] | null { - let { routesMeta } = branch; - - let matchedParams = {}; - let matchedPathname = "/"; - let matches: AgnosticRouteMatch[] = []; - for (let i = 0; i < routesMeta.length; ++i) { - let meta = routesMeta[i]; - let end = i === routesMeta.length - 1; - let remainingPathname = - matchedPathname === "/" - ? pathname - : pathname.slice(matchedPathname.length) || "/"; - let match = matchPath( - { path: meta.relativePath, caseSensitive: meta.caseSensitive, end }, - remainingPathname - ); - - if (!match) return null; - - Object.assign(matchedParams, match.params); - - let route = meta.route; - - matches.push({ - // TODO: Can this as be avoided? - params: matchedParams as Params, - 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/docs/en/v6/utils/generate-path - */ -export function generatePath( - path: Path, - params: { - [key in PathParam]: string; - } = {} as any -): string { - return path - .replace(/:(\w+)/g, (_, key: PathParam) => { - invariant(params[key] != null, `Missing ":${key}" param`); - return params[key]!; - }) - .replace(/(\/?)\*/, (_, prefix, __, str) => { - const star = "*" as PathParam; - - if (params[star] == null) { - // If no splat was provided, trim the trailing slash _unless_ it's - // the entire path - return str === "/*" ? "/" : ""; - } - - // Apply the splat - return `${prefix}${params[star]}`; - }); -} - -/** - * A PathPattern is used to match on some portion of a URL pathname. - */ -export interface PathPattern { - /** - * 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 { - /** - * The names and values of dynamic parameters in the URL. - */ - params: Params; - /** - * 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 = { - -readonly [P in keyof T]: T[P]; -}; - -/** - * Performs pattern matching on a URL pathname and returns information about - * the match. - * - * @see https://reactrouter.com/docs/en/v6/utils/match-path - */ -export function matchPath< - ParamKey extends ParamParseKey, - Path extends string ->( - pattern: PathPattern | Path, - pathname: string -): PathMatch | null { - if (typeof pattern === "string") { - pattern = { path: pattern, caseSensitive: false, end: true }; - } - - let [matcher, paramNames] = 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 = paramNames.reduce>( - (memo, paramName, 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"); - } - - memo[paramName] = safelyDecodeURIComponent( - captureGroups[index] || "", - paramName - ); - return memo; - }, - {} - ); - - return { - params, - pathname: matchedPathname, - pathnameBase, - pattern, - }; -} - -function compilePath( - path: string, - caseSensitive = false, - end = true -): [RegExp, string[]] { - 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 paramNames: string[] = []; - 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) => { - paramNames.push(paramName); - return "([^\\/]+)"; - }); - - if (path.endsWith("*")) { - paramNames.push("*"); - 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, paramNames]; -} - -function safelyDecodeURIComponent(value: string, paramName: string) { - try { - return decodeURIComponent(value); - } catch (error) { - warning( - false, - `The value for the URL param "${paramName}" will not be decoded because` + - ` the string "${value}" is a malformed URL segment. This is probably` + - ` due to a bad percent encoding (${error}).` - ); - - return value; - } -} - -/** - * @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) || "/"; -} - -/** - * @private - */ -export function invariant(value: boolean, message?: string): asserts value; -export function invariant( - 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); - } -} - -/** - * @private - */ -export function warning(cond: any, message: string): void { - if (!cond) { - // eslint-disable-next-line no-console - if (typeof console !== "undefined") console.warn(message); - - try { - // Welcome to debugging React Router! - // - // 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) {} - } -} - -/** - * Returns a resolved path object relative to the given pathname. - * - * @see https://reactrouter.com/docs/en/v6/utils/resolve-path - */ -export function resolvePath(to: To, fromPathname = "/"): Path { - let { - pathname: toPathname, - search = "", - hash = "", - } = typeof to === "string" ? parsePath(to) : to; - - let pathname = toPathname - ? toPathname.startsWith("/") - ? toPathname - : resolvePathname(toPathname, fromPathname) - : fromPathname; - - return { - pathname, - search: normalizeSearch(search), - hash: normalizeHash(hash), - }; -} - -function resolvePathname(relativePath: 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 -) { - return ( - `Cannot include a '${char}' character in a manually specified ` + - `\`to.${field}\` field [${JSON.stringify( - path - )}]. Please separate it out to the ` + - `\`to.${dest}\` field. Alternatively you may provide the full path as ` + - `a string in and the router will parse it for you.` - ); -} - -/** - * @private - */ -export function resolveTo( - toArg: To, - routePathnames: string[], - locationPathname: string, - isPathRelative = false -): Path { - let to: Partial; - 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 `` 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 (isPathRelative || toPathname == null) { - from = locationPathname; - } else { - let routePathnameIndex = routePathnames.length - 1; - - if (toPathname.startsWith("..")) { - let toSegments = toPathname.split("/"); - - // Each leading .. segment means "go up one route" instead of "go up one - // URL segment". This is a key difference from how works and a - // major reason we call this a "to" value instead of a "href". - while (toSegments[0] === "..") { - toSegments.shift(); - routePathnameIndex -= 1; - } - - to.pathname = toSegments.join("/"); - } - - // If there are more ".." segments than parent routes, resolve relative to - // the root / URL. - 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; -} - -/** - * @private - */ -export const joinPaths = (paths: string[]): string => - paths.join("/").replace(/\/\/+/g, "/"); - -/** - * @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, - init?: number | ResponseInit -) => Response; - -/** - * This is a shortcut for creating `application/json` responses. Converts `data` - * to JSON and sets the `Content-Type` header. - */ -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 interface TrackedPromise extends Promise { - _tracked?: boolean; - _data?: any; - _error?: any; -} - -export class AbortedDeferredError extends Error {} - -export class DeferredData { - private pendingKeys: Set = new Set(); - private controller: AbortController; - private abortPromise: Promise; - private unlistenAbortSignal: () => void; - private subscriber?: (aborted: boolean) => void = undefined; - data: Record; - - constructor(data: Record) { - 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), - }), - {} - ); - } - - private trackPromise( - key: string | number, - value: Promise | unknown - ): TrackedPromise | unknown { - if (!(value instanceof Promise)) { - return value; - } - - this.pendingKeys.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, null, 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 | number, - 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.pendingKeys.delete(key); - - if (this.done) { - // Nothing left to abort! - this.unlistenAbortSignal(); - } - - const subscriber = this.subscriber; - if (error) { - Object.defineProperty(promise, "_error", { get: () => error }); - subscriber && subscriber(false); - return Promise.reject(error); - } - - Object.defineProperty(promise, "_data", { get: () => data }); - subscriber && subscriber(false); - return data; - } - - subscribe(fn: (aborted: boolean) => void) { - this.subscriber = fn; - } - - cancel() { - this.controller.abort(); - this.pendingKeys.forEach((v, k) => this.pendingKeys.delete(k)); - let subscriber = this.subscriber; - subscriber && subscriber(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.pendingKeys.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), - }), - {} - ); - } -} - -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 function defer(data: Record) { - return new DeferredData(data); -} - -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, - }); -}; - -/** - * @private - * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies - */ -export class ErrorResponse { - status: number; - statusText: string; - data: any; - - constructor(status: number, statusText: string | undefined, data: any) { - this.status = status; - this.statusText = statusText || ""; - this.data = data; - } -} - -/** - * Check if the given error is an ErrorResponse generated from a 4xx/5xx - * Response throw from an action/loader - */ -export function isRouteErrorResponse(e: any): e is ErrorResponse { - return e instanceof ErrorResponse; -} diff --git a/node_modules/js-tokens/CHANGELOG.md b/node_modules/js-tokens/CHANGELOG.md deleted file mode 100644 index 755e6f6e..00000000 --- a/node_modules/js-tokens/CHANGELOG.md +++ /dev/null @@ -1,151 +0,0 @@ -### Version 4.0.0 (2018-01-28) ### - -- Added: Support for ES2018. The only change needed was recognizing the `s` - regex flag. -- Changed: _All_ tokens returned by the `matchToToken` function now have a - `closed` property. It is set to `undefined` for the tokens where “closed” - doesn’t make sense. This means that all tokens objects have the same shape, - which might improve performance. - -These are the breaking changes: - -- `'/a/s'.match(jsTokens)` no longer returns `['/', 'a', '/', 's']`, but - `['/a/s']`. (There are of course other variations of this.) -- Code that rely on some token objects not having the `closed` property could - now behave differently. - - -### Version 3.0.2 (2017-06-28) ### - -- No code changes. Just updates to the readme. - - -### Version 3.0.1 (2017-01-30) ### - -- Fixed: ES2015 unicode escapes with more than 6 hex digits are now matched - correctly. - - -### Version 3.0.0 (2017-01-11) ### - -This release contains one breaking change, that should [improve performance in -V8][v8-perf]: - -> So how can you, as a JavaScript developer, ensure that your RegExps are fast? -> If you are not interested in hooking into RegExp internals, make sure that -> neither the RegExp instance, nor its prototype is modified in order to get the -> best performance: -> -> ```js -> var re = /./g; -> re.exec(''); // Fast path. -> re.new_property = 'slow'; -> ``` - -This module used to export a single regex, with `.matchToToken` bolted -on, just like in the above example. This release changes the exports of -the module to avoid this issue. - -Before: - -```js -import jsTokens from "js-tokens" -// or: -var jsTokens = require("js-tokens") -var matchToToken = jsTokens.matchToToken -``` - -After: - -```js -import jsTokens, {matchToToken} from "js-tokens" -// or: -var jsTokens = require("js-tokens").default -var matchToToken = require("js-tokens").matchToToken -``` - -[v8-perf]: http://v8project.blogspot.se/2017/01/speeding-up-v8-regular-expressions.html - - -### Version 2.0.0 (2016-06-19) ### - -- Added: Support for ES2016. In other words, support for the `**` exponentiation - operator. - -These are the breaking changes: - -- `'**'.match(jsTokens)` no longer returns `['*', '*']`, but `['**']`. -- `'**='.match(jsTokens)` no longer returns `['*', '*=']`, but `['**=']`. - - -### Version 1.0.3 (2016-03-27) ### - -- Improved: Made the regex ever so slightly smaller. -- Updated: The readme. - - -### Version 1.0.2 (2015-10-18) ### - -- Improved: Limited npm package contents for a smaller download. Thanks to - @zertosh! - - -### Version 1.0.1 (2015-06-20) ### - -- Fixed: Declared an undeclared variable. - - -### Version 1.0.0 (2015-02-26) ### - -- Changed: Merged the 'operator' and 'punctuation' types into 'punctuator'. That - type is now equivalent to the Punctuator token in the ECMAScript - specification. (Backwards-incompatible change.) -- Fixed: A `-` followed by a number is now correctly matched as a punctuator - followed by a number. It used to be matched as just a number, but there is no - such thing as negative number literals. (Possibly backwards-incompatible - change.) - - -### Version 0.4.1 (2015-02-21) ### - -- Added: Support for the regex `u` flag. - - -### Version 0.4.0 (2015-02-21) ### - -- Improved: `jsTokens.matchToToken` performance. -- Added: Support for octal and binary number literals. -- Added: Support for template strings. - - -### Version 0.3.1 (2015-01-06) ### - -- Fixed: Support for unicode spaces. They used to be allowed in names (which is - very confusing), and some unicode newlines were wrongly allowed in strings and - regexes. - - -### Version 0.3.0 (2014-12-19) ### - -- Changed: The `jsTokens.names` array has been replaced with the - `jsTokens.matchToToken` function. The capturing groups of `jsTokens` are no - longer part of the public API; instead use said function. See this [gist] for - an example. (Backwards-incompatible change.) -- Changed: The empty string is now considered an “invalid” token, instead an - “empty” token (its own group). (Backwards-incompatible change.) -- Removed: component support. (Backwards-incompatible change.) - -[gist]: https://gist.github.com/lydell/be49dbf80c382c473004 - - -### Version 0.2.0 (2014-06-19) ### - -- Changed: Match ES6 function arrows (`=>`) as an operator, instead of its own - category (“functionArrow”), for simplicity. (Backwards-incompatible change.) -- Added: ES6 splats (`...`) are now matched as an operator (instead of three - punctuations). (Backwards-incompatible change.) - - -### Version 0.1.0 (2014-03-08) ### - -- Initial release. diff --git a/node_modules/js-tokens/LICENSE b/node_modules/js-tokens/LICENSE deleted file mode 100644 index 54aef52f..00000000 --- a/node_modules/js-tokens/LICENSE +++ /dev/null @@ -1,21 +0,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. diff --git a/node_modules/js-tokens/README.md b/node_modules/js-tokens/README.md deleted file mode 100644 index 00cdf163..00000000 --- a/node_modules/js-tokens/README.md +++ /dev/null @@ -1,240 +0,0 @@ -Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) -======== - -A regex that tokenizes JavaScript. - -```js -var jsTokens = require("js-tokens").default - -var jsString = "var foo=opts.foo;\n..." - -jsString.match(jsTokens) -// ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] -``` - - -Installation -============ - -`npm install js-tokens` - -```js -import jsTokens from "js-tokens" -// or: -var jsTokens = require("js-tokens").default -``` - - -Usage -===== - -### `jsTokens` ### - -A regex with the `g` flag that matches JavaScript tokens. - -The regex _always_ matches, even invalid JavaScript and the empty string. - -The next match is always directly after the previous. - -### `var token = matchToToken(match)` ### - -```js -import {matchToToken} from "js-tokens" -// or: -var matchToToken = require("js-tokens").matchToToken -``` - -Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: -String, value: String}` object. The following types are available: - -- string -- comment -- regex -- number -- name -- punctuator -- whitespace -- invalid - -Multi-line comments and strings also have a `closed` property indicating if the -token was closed or not (see below). - -Comments and strings both come in several flavors. To distinguish them, check if -the token starts with `//`, `/*`, `'`, `"` or `` ` ``. - -Names are ECMAScript IdentifierNames, that is, including both identifiers and -keywords. You may use [is-keyword-js] to tell them apart. - -Whitespace includes both line terminators and other whitespace. - -[is-keyword-js]: https://github.com/crissdev/is-keyword-js - - -ECMAScript support -================== - -The intention is to always support the latest ECMAScript version whose feature -set has been finalized. - -If adding support for a newer version requires changes, a new version with a -major verion bump will be released. - -Currently, ECMAScript 2018 is supported. - - -Invalid code handling -===================== - -Unterminated strings are still matched as strings. JavaScript strings cannot -contain (unescaped) newlines, so unterminated strings simply end at the end of -the line. Unterminated template strings can contain unescaped newlines, though, -so they go on to the end of input. - -Unterminated multi-line comments are also still matched as comments. They -simply go on to the end of the input. - -Unterminated regex literals are likely matched as division and whatever is -inside the regex. - -Invalid ASCII characters have their own capturing group. - -Invalid non-ASCII characters are treated as names, to simplify the matching of -names (except unicode spaces which are treated as whitespace). Note: See also -the [ES2018](#es2018) section. - -Regex literals may contain invalid regex syntax. They are still matched as -regex literals. They may also contain repeated regex flags, to keep the regex -simple. - -Strings may contain invalid escape sequences. - - -Limitations -=========== - -Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be -perfect. But that’s not the point either. - -You may compare jsTokens with [esprima] by using `esprima-compare.js`. -See `npm run esprima-compare`! - -[esprima]: http://esprima.org/ - -### Template string interpolation ### - -Template strings are matched as single tokens, from the starting `` ` `` to the -ending `` ` ``, including interpolations (whose tokens are not matched -individually). - -Matching template string interpolations requires recursive balancing of `{` and -`}`—something that JavaScript regexes cannot do. Only one level of nesting is -supported. - -### Division and regex literals collision ### - -Consider this example: - -```js -var g = 9.82 -var number = bar / 2/g - -var regex = / 2/g -``` - -A human can easily understand that in the `number` line we’re dealing with -division, and in the `regex` line we’re dealing with a regex literal. How come? -Because humans can look at the whole code to put the `/` characters in context. -A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also -look backwards. See the [ES2018](#es2018) section). - -When the `jsTokens` regex scans throught the above, it will see the following -at the end of both the `number` and `regex` rows: - -```js -/ 2/g -``` - -It is then impossible to know if that is a regex literal, or part of an -expression dealing with division. - -Here is a similar case: - -```js -foo /= 2/g -foo(/= 2/g) -``` - -The first line divides the `foo` variable with `2/g`. The second line calls the -`foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only -sees forwards, it cannot tell the two cases apart. - -There are some cases where we _can_ tell division and regex literals apart, -though. - -First off, we have the simple cases where there’s only one slash in the line: - -```js -var foo = 2/g -foo /= 2 -``` - -Regex literals cannot contain newlines, so the above cases are correctly -identified as division. Things are only problematic when there are more than -one non-comment slash in a single line. - -Secondly, not every character is a valid regex flag. - -```js -var number = bar / 2/e -``` - -The above example is also correctly identified as division, because `e` is not a -valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` -(any letter) as flags, but it is not worth it since it increases the amount of -ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are -allowed. This means that the above example will be identified as division as -long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 -characters long. - -Lastly, we can look _forward_ for information. - -- If the token following what looks like a regex literal is not valid after a - regex literal, but is valid in a division expression, then the regex literal - is treated as division instead. For example, a flagless regex cannot be - followed by a string, number or name, but all of those three can be the - denominator of a division. -- Generally, if what looks like a regex literal is followed by an operator, the - regex literal is treated as division instead. This is because regexes are - seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division - could likely be part of such an expression. - -Please consult the regex source and the test cases for precise information on -when regex or division is matched (should you need to know). In short, you -could sum it up as: - -If the end of a statement looks like a regex literal (even if it isn’t), it -will be treated as one. Otherwise it should work as expected (if you write sane -code). - -### ES2018 ### - -ES2018 added some nice regex improvements to the language. - -- [Unicode property escapes] should allow telling names and invalid non-ASCII - characters apart without blowing up the regex size. -- [Lookbehind assertions] should allow matching telling division and regex - literals apart in more cases. -- [Named capture groups] might simplify some things. - -These things would be nice to do, but are not critical. They probably have to -wait until the oldest maintained Node.js LTS release supports those features. - -[Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html -[Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html -[Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html - - -License -======= - -[MIT](LICENSE). diff --git a/node_modules/js-tokens/index.js b/node_modules/js-tokens/index.js deleted file mode 100644 index b23a4a0e..00000000 --- a/node_modules/js-tokens/index.js +++ /dev/null @@ -1,23 +0,0 @@ -// 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 -} diff --git a/node_modules/js-tokens/package.json b/node_modules/js-tokens/package.json deleted file mode 100644 index 66752fab..00000000 --- a/node_modules/js-tokens/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "js-tokens", - "version": "4.0.0", - "author": "Simon Lydell", - "license": "MIT", - "description": "A regex that tokenizes JavaScript.", - "keywords": [ - "JavaScript", - "js", - "token", - "tokenize", - "regex" - ], - "files": [ - "index.js" - ], - "repository": "lydell/js-tokens", - "scripts": { - "test": "mocha --ui tdd", - "esprima-compare": "node esprima-compare ./index.js everything.js/es5.js", - "build": "node generate-index.js", - "dev": "npm run build && npm test" - }, - "devDependencies": { - "coffeescript": "2.1.1", - "esprima": "4.0.0", - "everything.js": "1.0.3", - "mocha": "5.0.0" - } -} diff --git a/node_modules/loose-envify/LICENSE b/node_modules/loose-envify/LICENSE deleted file mode 100644 index fbafb487..00000000 --- a/node_modules/loose-envify/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Andres Suarez - -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. diff --git a/node_modules/loose-envify/README.md b/node_modules/loose-envify/README.md deleted file mode 100644 index 7f4e07b0..00000000 --- a/node_modules/loose-envify/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# loose-envify - -[![Build Status](https://travis-ci.org/zertosh/loose-envify.svg?branch=master)](https://travis-ci.org/zertosh/loose-envify) - -Fast (and loose) selective `process.env` replacer using [js-tokens](https://github.com/lydell/js-tokens) instead of an AST. Works just like [envify](https://github.com/hughsk/envify) but much faster. - -## Gotchas - -* Doesn't handle broken syntax. -* Doesn't look inside embedded expressions in template strings. - - **this won't work:** - ```js - console.log(`the current env is ${process.env.NODE_ENV}`); - ``` -* Doesn't replace oddly-spaced or oddly-commented expressions. - - **this won't work:** - ```js - console.log(process./*won't*/env./*work*/NODE_ENV); - ``` - -## Usage/Options - -loose-envify has the exact same interface as [envify](https://github.com/hughsk/envify), including the CLI. - -## Benchmark - -``` -envify: - - $ for i in {1..5}; do node bench/bench.js 'envify'; done - 708ms - 727ms - 791ms - 719ms - 720ms - -loose-envify: - - $ for i in {1..5}; do node bench/bench.js '../'; done - 51ms - 52ms - 52ms - 52ms - 52ms -``` diff --git a/node_modules/loose-envify/cli.js b/node_modules/loose-envify/cli.js deleted file mode 100644 index c0b63cb1..00000000 --- a/node_modules/loose-envify/cli.js +++ /dev/null @@ -1,16 +0,0 @@ -#!/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); -} diff --git a/node_modules/loose-envify/custom.js b/node_modules/loose-envify/custom.js deleted file mode 100644 index 6389bfac..00000000 --- a/node_modules/loose-envify/custom.js +++ /dev/null @@ -1,4 +0,0 @@ -// envify compatibility -'use strict'; - -module.exports = require('./loose-envify'); diff --git a/node_modules/loose-envify/index.js b/node_modules/loose-envify/index.js deleted file mode 100644 index 8cd8305d..00000000 --- a/node_modules/loose-envify/index.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('./loose-envify')(process.env); diff --git a/node_modules/loose-envify/loose-envify.js b/node_modules/loose-envify/loose-envify.js deleted file mode 100644 index b5a5be22..00000000 --- a/node_modules/loose-envify/loose-envify.js +++ /dev/null @@ -1,36 +0,0 @@ -'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(); -}; diff --git a/node_modules/loose-envify/package.json b/node_modules/loose-envify/package.json deleted file mode 100644 index 5e3d0e27..00000000 --- a/node_modules/loose-envify/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "loose-envify", - "version": "1.4.0", - "description": "Fast (and loose) selective `process.env` replacer using js-tokens instead of an AST", - "keywords": [ - "environment", - "variables", - "browserify", - "browserify-transform", - "transform", - "source", - "configuration" - ], - "homepage": "https://github.com/zertosh/loose-envify", - "license": "MIT", - "author": "Andres Suarez ", - "main": "index.js", - "bin": { - "loose-envify": "cli.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/zertosh/loose-envify.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "dependencies": { - "js-tokens": "^3.0.0 || ^4.0.0" - }, - "devDependencies": { - "browserify": "^13.1.1", - "envify": "^3.4.0", - "tap": "^8.0.0" - } -} diff --git a/node_modules/loose-envify/replace.js b/node_modules/loose-envify/replace.js deleted file mode 100644 index ec15e81c..00000000 --- a/node_modules/loose-envify/replace.js +++ /dev/null @@ -1,65 +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; diff --git a/node_modules/react-dom/LICENSE b/node_modules/react-dom/LICENSE deleted file mode 100644 index b96dcb04..00000000 --- a/node_modules/react-dom/LICENSE +++ /dev/null @@ -1,21 +0,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. diff --git a/node_modules/react-dom/README.md b/node_modules/react-dom/README.md deleted file mode 100644 index ecba5cfb..00000000 --- a/node_modules/react-dom/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# `react-dom` - -This package serves as the entry point to the DOM and server renderers for React. It is intended to be paired with the generic React package, which is shipped as `react` to npm. - -## Installation - -```sh -npm install react react-dom -``` - -## Usage - -### In the browser - -```js -import { createRoot } from 'react-dom/client'; - -function App() { - return
Hello World
; -} - -const root = createRoot(document.getElementById('root')); -root.render(); -``` - -### On the server - -```js -import { renderToPipeableStream } from 'react-dom/server'; - -function App() { - return
Hello World
; -} - -function handleRequest(res) { - // ... in your server handler ... - const stream = renderToPipeableStream(, { - onShellReady() { - res.statusCode = 200; - res.setHeader('Content-type', 'text/html'); - stream.pipe(res); - }, - // ... - }); -} -``` - -## API - -### `react-dom` - -See https://reactjs.org/docs/react-dom.html - -### `react-dom/client` - -See https://reactjs.org/docs/react-dom-client.html - -### `react-dom/server` - -See https://reactjs.org/docs/react-dom-server.html diff --git a/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js b/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js deleted file mode 100644 index 11c25e08..00000000 --- a/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js +++ /dev/null @@ -1,7018 +0,0 @@ -/** - * @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.2.0'; - -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 = '"'; - break; - - case 38: - // & - escape = '&'; - break; - - case 39: - // ' - escape = '''; // modified from escape-html; used to be ''' - - break; - - case 60: - // < - escape = '<'; - break; - - case 62: - // > - escape = '>'; - 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(''); -var startScriptSrc = stringToPrecomputedChunk(''); -/** - * 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 '); -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('")'); -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(')'); -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 "" - // but we have a user-provided "displayName" - // splice it in to make the stack more readable. - - - if (fn.displayName && _frame.includes('')) { - _frame = _frame.replace('', 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 - - 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) { - // - 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: -// -// <> <> -//
-// -// -// -// -// -// 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. -// -// -// -// -// -// 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 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 (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 directly is not supported and will be removed in ' + 'a future major release. Did you mean to render 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 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; - })(); -} diff --git a/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js b/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js deleted file mode 100644 index eca01a04..00000000 --- a/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js +++ /dev/null @@ -1,93 +0,0 @@ -/** - * @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