From 7d87f5597c0125f319a047d2c5571ac4da972004 Mon Sep 17 00:00:00 2001 From: bobgus39 Date: Tue, 16 Jan 2024 17:08:03 +0100 Subject: [PATCH] 8 --- .gitignore | 3 +- dist/assets/index-3xO65pgW.css | 1 + dist/assets/index-wnzOmW71.js | 70 + dist/index.html | 18 + dist/vite.svg | 1 + ...b.com!bobgus39!marielWebPage.github.io.git | 2 +- .../@ampproject/remapping/dist/remapping.mjs | 191 + .../remapping/dist/remapping.mjs.map | 1 + .../remapping/dist/remapping.umd.js | 196 + .../remapping/dist/remapping.umd.js.map | 1 + .../dist/types/build-source-map-tree.d.ts | 14 + .../remapping/dist/types/remapping.d.ts | 19 + .../remapping/dist/types/source-map-tree.d.ts | 42 + .../remapping/dist/types/source-map.d.ts | 17 + .../remapping/dist/types/types.d.ts | 14 + .../eslintrc/dist/eslintrc-universal.cjs | 1104 + .../eslintrc/dist/eslintrc-universal.cjs.map | 1 + .../@eslint/eslintrc/dist/eslintrc.cjs | 4344 + .../@eslint/eslintrc/dist/eslintrc.cjs.map | 1 + .../module-importer/dist/module-importer.cjs | 22 + .../dist/module-importer.d.cts | 27 + .../module-importer/dist/module-importer.d.ts | 2 + .../module-importer/dist/module-importer.js | 18 + .../gen-mapping/dist/gen-mapping.mjs | 230 + .../gen-mapping/dist/gen-mapping.mjs.map | 1 + .../gen-mapping/dist/gen-mapping.umd.js | 236 + .../gen-mapping/dist/gen-mapping.umd.js.map | 1 + .../gen-mapping/dist/types/gen-mapping.d.ts | 90 + .../dist/types/sourcemap-segment.d.ts | 12 + .../gen-mapping/dist/types/types.d.ts | 35 + .../resolve-uri/dist/resolve-uri.mjs | 242 + .../resolve-uri/dist/resolve-uri.mjs.map | 1 + .../resolve-uri/dist/resolve-uri.umd.js | 250 + .../resolve-uri/dist/resolve-uri.umd.js.map | 1 + .../resolve-uri/dist/types/resolve-uri.d.ts | 4 + .../@jridgewell/set-array/dist/set-array.mjs | 48 + .../set-array/dist/set-array.mjs.map | 1 + .../set-array/dist/set-array.umd.js | 58 + .../set-array/dist/set-array.umd.js.map | 1 + .../set-array/dist/types/set-array.d.ts | 26 + .../sourcemap-codec/dist/sourcemap-codec.mjs | 164 + .../dist/sourcemap-codec.mjs.map | 1 + .../dist/sourcemap-codec.umd.js | 175 + .../dist/sourcemap-codec.umd.js.map | 1 + .../dist/types/sourcemap-codec.d.ts | 6 + .../trace-mapping/dist/trace-mapping.mjs | 552 + .../trace-mapping/dist/trace-mapping.mjs.map | 1 + .../trace-mapping/dist/trace-mapping.umd.js | 560 + .../dist/trace-mapping.umd.js.map | 1 + .../trace-mapping/dist/types/any-map.d.ts | 8 + .../dist/types/binary-search.d.ts | 32 + .../trace-mapping/dist/types/by-source.d.ts | 7 + .../trace-mapping/dist/types/resolve.d.ts | 1 + .../trace-mapping/dist/types/sort.d.ts | 2 + .../dist/types/sourcemap-segment.d.ts | 16 + .../dist/types/strip-filename.d.ts | 4 + .../dist/types/trace-mapping.d.ts | 74 + .../trace-mapping/dist/types/types.d.ts | 92 + .../@remix-run/router/dist/history.d.ts | 250 + .../@remix-run/router/dist/index.d.ts | 9 + .../@remix-run/router/dist/router.cjs.js | 4840 ++ .../@remix-run/router/dist/router.cjs.js.map | 1 + .../@remix-run/router/dist/router.d.ts | 507 + node_modules/@remix-run/router/dist/router.js | 4299 + .../@remix-run/router/dist/router.js.map | 1 + .../@remix-run/router/dist/router.umd.js | 4846 ++ .../@remix-run/router/dist/router.umd.js.map | 1 + .../@remix-run/router/dist/router.umd.min.js | 12 + .../router/dist/router.umd.min.js.map | 1 + .../@remix-run/router/dist/utils.d.ts | 502 + .../@vitejs/plugin-react/dist/index.cjs | 295 + .../@vitejs/plugin-react/dist/index.d.cts | 54 + .../@vitejs/plugin-react/dist/index.d.mts | 54 + .../@vitejs/plugin-react/dist/index.d.ts | 54 + .../@vitejs/plugin-react/dist/index.mjs | 286 + .../@vitejs/plugin-react/dist/refreshUtils.js | 71 + node_modules/acorn/dist/acorn.d.mts | 857 + node_modules/acorn/dist/acorn.d.ts | 857 + node_modules/acorn/dist/acorn.js | 6002 ++ node_modules/acorn/dist/acorn.mjs | 5973 ++ node_modules/acorn/dist/bin.js | 90 + node_modules/ajv/dist/ajv.bundle.js | 7189 ++ node_modules/ajv/dist/ajv.min.js | 3 + node_modules/ajv/dist/ajv.min.js.map | 1 + node_modules/async/dist/async.js | 6062 ++ node_modules/async/dist/async.min.js | 1 + node_modules/async/dist/async.mjs | 5949 ++ .../caniuse-lite/dist/lib/statuses.js | 9 + .../caniuse-lite/dist/lib/supported.js | 9 + .../caniuse-lite/dist/unpacker/agents.js | 47 + .../dist/unpacker/browserVersions.js | 1 + .../caniuse-lite/dist/unpacker/browsers.js | 1 + .../caniuse-lite/dist/unpacker/feature.js | 52 + .../caniuse-lite/dist/unpacker/features.js | 6 + .../caniuse-lite/dist/unpacker/index.js | 4 + .../caniuse-lite/dist/unpacker/region.js | 22 + node_modules/escalade/dist/index.js | 22 + node_modules/escalade/dist/index.mjs | 22 + .../eslint-scope/dist/eslint-scope.cjs | 2240 + .../dist/eslint-visitor-keys.cjs | 384 + .../dist/eslint-visitor-keys.d.cts | 27 + .../eslint-visitor-keys/dist/index.d.ts | 16 + .../dist/visitor-keys.d.ts | 12 + node_modules/espree/dist/espree.cjs | 883 + node_modules/esquery/dist/esquery.esm.js | 4020 + node_modules/esquery/dist/esquery.esm.min.js | 2 + .../esquery/dist/esquery.esm.min.js.map | 1 + node_modules/esquery/dist/esquery.js | 4028 + node_modules/esquery/dist/esquery.lite.js | 3318 + node_modules/esquery/dist/esquery.lite.min.js | 2 + .../esquery/dist/esquery.lite.min.js.map | 1 + node_modules/esquery/dist/esquery.min.js | 2 + node_modules/esquery/dist/esquery.min.js.map | 1 + node_modules/js-yaml/dist/js-yaml.js | 3874 + node_modules/js-yaml/dist/js-yaml.min.js | 2 + node_modules/js-yaml/dist/js-yaml.mjs | 3851 + node_modules/json5/dist/index.js | 1737 + node_modules/json5/dist/index.min.js | 1 + node_modules/json5/dist/index.min.mjs | 1 + node_modules/json5/dist/index.mjs | 1426 + .../leaflet/dist/images/layers-2x.png | Bin 0 -> 1259 bytes node_modules/leaflet/dist/images/layers.png | Bin 0 -> 696 bytes .../leaflet/dist/images/marker-icon-2x.png | Bin 0 -> 2464 bytes .../leaflet/dist/images/marker-icon.png | Bin 0 -> 1466 bytes .../leaflet/dist/images/marker-shadow.png | Bin 0 -> 618 bytes node_modules/leaflet/dist/leaflet-src.esm.js | 14419 ++++ .../leaflet/dist/leaflet-src.esm.js.map | 1 + node_modules/leaflet/dist/leaflet-src.js | 14512 ++++ node_modules/leaflet/dist/leaflet-src.js.map | 1 + node_modules/leaflet/dist/leaflet.css | 661 + node_modules/leaflet/dist/leaflet.js | 6 + node_modules/leaflet/dist/leaflet.js.map | 1 + node_modules/object.assign/dist/browser.js | 1141 + node_modules/react-router-dom/dist/dom.d.ts | 104 + node_modules/react-router-dom/dist/index.d.ts | 316 + node_modules/react-router-dom/dist/index.js | 1423 + .../react-router-dom/dist/index.js.map | 1 + node_modules/react-router-dom/dist/main.js | 19 + .../dist/react-router-dom.development.js | 1464 + .../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 | 31 + node_modules/react-router-dom/dist/server.js | 314 + node_modules/react-router-dom/dist/server.mjs | 289 + .../dist/umd/react-router-dom.development.js | 1760 + .../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/dist/index.d.ts | 25 + node_modules/react-router/dist/index.js | 1435 + node_modules/react-router/dist/index.js.map | 1 + .../react-router/dist/lib/components.d.ts | 157 + .../react-router/dist/lib/context.d.ts | 102 + node_modules/react-router/dist/lib/hooks.d.ts | 181 + node_modules/react-router/dist/main.js | 19 + .../dist/react-router.development.js | 1331 + .../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 | 1553 + .../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/rollup/dist/bin/rollup | 1719 + node_modules/rollup/dist/es/getLogFilter.js | 64 + node_modules/rollup/dist/es/package.json | 1 + node_modules/rollup/dist/es/parseAst.js | 12 + node_modules/rollup/dist/es/rollup.js | 18 + .../rollup/dist/es/shared/node-entry.js | 20063 +++++ .../rollup/dist/es/shared/parseAst.js | 2154 + node_modules/rollup/dist/es/shared/watch.js | 4864 ++ node_modules/rollup/dist/getLogFilter.d.ts | 5 + node_modules/rollup/dist/getLogFilter.js | 69 + node_modules/rollup/dist/loadConfigFile.d.ts | 20 + node_modules/rollup/dist/loadConfigFile.js | 30 + node_modules/rollup/dist/native.js | 102 + node_modules/rollup/dist/parseAst.d.ts | 4 + node_modules/rollup/dist/parseAst.js | 22 + node_modules/rollup/dist/rollup.d.ts | 990 + node_modules/rollup/dist/rollup.js | 100 + .../rollup/dist/shared/fsevents-importer.js | 37 + node_modules/rollup/dist/shared/index.js | 4571 ++ .../rollup/dist/shared/loadConfigFile.js | 546 + node_modules/rollup/dist/shared/parseAst.js | 2350 + node_modules/rollup/dist/shared/rollup.js | 20056 +++++ node_modules/rollup/dist/shared/watch-cli.js | 562 + node_modules/rollup/dist/shared/watch.js | 323 + node_modules/uri-js/dist/es5/uri.all.d.ts | 59 + node_modules/uri-js/dist/es5/uri.all.js | 1443 + node_modules/uri-js/dist/es5/uri.all.js.map | 1 + node_modules/uri-js/dist/es5/uri.all.min.d.ts | 59 + node_modules/uri-js/dist/es5/uri.all.min.js | 3 + .../uri-js/dist/es5/uri.all.min.js.map | 1 + node_modules/uri-js/dist/esnext/index.d.ts | 1 + node_modules/uri-js/dist/esnext/index.js | 17 + node_modules/uri-js/dist/esnext/index.js.map | 1 + .../uri-js/dist/esnext/regexps-iri.d.ts | 3 + .../uri-js/dist/esnext/regexps-iri.js | 3 + .../uri-js/dist/esnext/regexps-iri.js.map | 1 + .../uri-js/dist/esnext/regexps-uri.d.ts | 4 + .../uri-js/dist/esnext/regexps-uri.js | 42 + .../uri-js/dist/esnext/regexps-uri.js.map | 1 + .../uri-js/dist/esnext/schemes/http.d.ts | 3 + .../uri-js/dist/esnext/schemes/http.js | 28 + .../uri-js/dist/esnext/schemes/http.js.map | 1 + .../uri-js/dist/esnext/schemes/https.d.ts | 3 + .../uri-js/dist/esnext/schemes/https.js | 9 + .../uri-js/dist/esnext/schemes/https.js.map | 1 + .../uri-js/dist/esnext/schemes/mailto.d.ts | 12 + .../uri-js/dist/esnext/schemes/mailto.js | 148 + .../uri-js/dist/esnext/schemes/mailto.js.map | 1 + .../uri-js/dist/esnext/schemes/urn-uuid.d.ts | 7 + .../uri-js/dist/esnext/schemes/urn-uuid.js | 23 + .../dist/esnext/schemes/urn-uuid.js.map | 1 + .../uri-js/dist/esnext/schemes/urn.d.ts | 10 + .../uri-js/dist/esnext/schemes/urn.js | 49 + .../uri-js/dist/esnext/schemes/urn.js.map | 1 + .../uri-js/dist/esnext/schemes/ws.d.ts | 7 + node_modules/uri-js/dist/esnext/schemes/ws.js | 41 + .../uri-js/dist/esnext/schemes/ws.js.map | 1 + .../uri-js/dist/esnext/schemes/wss.d.ts | 3 + .../uri-js/dist/esnext/schemes/wss.js | 9 + .../uri-js/dist/esnext/schemes/wss.js.map | 1 + node_modules/uri-js/dist/esnext/uri.d.ts | 59 + node_modules/uri-js/dist/esnext/uri.js | 480 + node_modules/uri-js/dist/esnext/uri.js.map | 1 + node_modules/uri-js/dist/esnext/util.d.ts | 6 + node_modules/uri-js/dist/esnext/util.js | 36 + node_modules/uri-js/dist/esnext/util.js.map | 1 + node_modules/vite/dist/client/client.mjs | 784 + node_modules/vite/dist/client/client.mjs.map | 1 + node_modules/vite/dist/client/env.mjs | 30 + node_modules/vite/dist/client/env.mjs.map | 1 + .../vite/dist/node-cjs/publicUtils.cjs | 6085 ++ .../vite/dist/node/chunks/dep-8a-6Quh6.js | 561 + .../vite/dist/node/chunks/dep-V3BH7oO1.js | 68436 ++++++++++++++++ .../vite/dist/node/chunks/dep-ggdMrszO.js | 914 + .../vite/dist/node/chunks/dep-kjUoH5nk.js | 7930 ++ .../vite/dist/node/chunks/dep-oIJQVJc7.js | 7646 ++ node_modules/vite/dist/node/cli.js | 929 + node_modules/vite/dist/node/constants.js | 127 + node_modules/vite/dist/node/index.d.ts | 3347 + node_modules/vite/dist/node/index.js | 160 + 244 files changed, 283668 insertions(+), 3 deletions(-) create mode 100644 dist/assets/index-3xO65pgW.css create mode 100644 dist/assets/index-wnzOmW71.js create mode 100644 dist/index.html create mode 100644 dist/vite.svg create mode 100644 node_modules/@ampproject/remapping/dist/remapping.mjs create mode 100644 node_modules/@ampproject/remapping/dist/remapping.mjs.map create mode 100644 node_modules/@ampproject/remapping/dist/remapping.umd.js create mode 100644 node_modules/@ampproject/remapping/dist/remapping.umd.js.map create mode 100644 node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts create mode 100644 node_modules/@ampproject/remapping/dist/types/remapping.d.ts create mode 100644 node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts create mode 100644 node_modules/@ampproject/remapping/dist/types/source-map.d.ts create mode 100644 node_modules/@ampproject/remapping/dist/types/types.d.ts create mode 100644 node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs create mode 100644 node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs.map create mode 100644 node_modules/@eslint/eslintrc/dist/eslintrc.cjs create mode 100644 node_modules/@eslint/eslintrc/dist/eslintrc.cjs.map create mode 100644 node_modules/@humanwhocodes/module-importer/dist/module-importer.cjs create mode 100644 node_modules/@humanwhocodes/module-importer/dist/module-importer.d.cts create mode 100644 node_modules/@humanwhocodes/module-importer/dist/module-importer.d.ts create mode 100644 node_modules/@humanwhocodes/module-importer/dist/module-importer.js create mode 100644 node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs create mode 100644 node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map create mode 100644 node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js create mode 100644 node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map create mode 100644 node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts create mode 100644 node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts create mode 100644 node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts create mode 100644 node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs create mode 100644 node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map create mode 100644 node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js create mode 100644 node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map create mode 100644 node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts create mode 100644 node_modules/@jridgewell/set-array/dist/set-array.mjs create mode 100644 node_modules/@jridgewell/set-array/dist/set-array.mjs.map create mode 100644 node_modules/@jridgewell/set-array/dist/set-array.umd.js create mode 100644 node_modules/@jridgewell/set-array/dist/set-array.umd.js.map create mode 100644 node_modules/@jridgewell/set-array/dist/types/set-array.d.ts create mode 100644 node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs create mode 100644 node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map create mode 100644 node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js create mode 100644 node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map create mode 100644 node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts create mode 100644 node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs create mode 100644 node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map create mode 100644 node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js create mode 100644 node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map create mode 100644 node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts create mode 100644 node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts create mode 100644 node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts create mode 100644 node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts create mode 100644 node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts create mode 100644 node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts create mode 100644 node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts create mode 100644 node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts create mode 100644 node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts create mode 100644 node_modules/@remix-run/router/dist/history.d.ts create mode 100644 node_modules/@remix-run/router/dist/index.d.ts create mode 100644 node_modules/@remix-run/router/dist/router.cjs.js create mode 100644 node_modules/@remix-run/router/dist/router.cjs.js.map create mode 100644 node_modules/@remix-run/router/dist/router.d.ts create mode 100644 node_modules/@remix-run/router/dist/router.js create mode 100644 node_modules/@remix-run/router/dist/router.js.map create mode 100644 node_modules/@remix-run/router/dist/router.umd.js create mode 100644 node_modules/@remix-run/router/dist/router.umd.js.map create mode 100644 node_modules/@remix-run/router/dist/router.umd.min.js create mode 100644 node_modules/@remix-run/router/dist/router.umd.min.js.map create mode 100644 node_modules/@remix-run/router/dist/utils.d.ts create mode 100644 node_modules/@vitejs/plugin-react/dist/index.cjs create mode 100644 node_modules/@vitejs/plugin-react/dist/index.d.cts create mode 100644 node_modules/@vitejs/plugin-react/dist/index.d.mts create mode 100644 node_modules/@vitejs/plugin-react/dist/index.d.ts create mode 100644 node_modules/@vitejs/plugin-react/dist/index.mjs create mode 100644 node_modules/@vitejs/plugin-react/dist/refreshUtils.js create mode 100644 node_modules/acorn/dist/acorn.d.mts create mode 100644 node_modules/acorn/dist/acorn.d.ts create mode 100644 node_modules/acorn/dist/acorn.js create mode 100644 node_modules/acorn/dist/acorn.mjs create mode 100644 node_modules/acorn/dist/bin.js create mode 100644 node_modules/ajv/dist/ajv.bundle.js create mode 100644 node_modules/ajv/dist/ajv.min.js create mode 100644 node_modules/ajv/dist/ajv.min.js.map create mode 100644 node_modules/async/dist/async.js create mode 100644 node_modules/async/dist/async.min.js create mode 100644 node_modules/async/dist/async.mjs create mode 100644 node_modules/caniuse-lite/dist/lib/statuses.js create mode 100644 node_modules/caniuse-lite/dist/lib/supported.js create mode 100644 node_modules/caniuse-lite/dist/unpacker/agents.js create mode 100644 node_modules/caniuse-lite/dist/unpacker/browserVersions.js create mode 100644 node_modules/caniuse-lite/dist/unpacker/browsers.js create mode 100644 node_modules/caniuse-lite/dist/unpacker/feature.js create mode 100644 node_modules/caniuse-lite/dist/unpacker/features.js create mode 100644 node_modules/caniuse-lite/dist/unpacker/index.js create mode 100644 node_modules/caniuse-lite/dist/unpacker/region.js create mode 100644 node_modules/escalade/dist/index.js create mode 100644 node_modules/escalade/dist/index.mjs create mode 100644 node_modules/eslint-scope/dist/eslint-scope.cjs create mode 100644 node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs create mode 100644 node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts create mode 100644 node_modules/eslint-visitor-keys/dist/index.d.ts create mode 100644 node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts create mode 100644 node_modules/espree/dist/espree.cjs create mode 100644 node_modules/esquery/dist/esquery.esm.js create mode 100644 node_modules/esquery/dist/esquery.esm.min.js create mode 100644 node_modules/esquery/dist/esquery.esm.min.js.map create mode 100644 node_modules/esquery/dist/esquery.js create mode 100644 node_modules/esquery/dist/esquery.lite.js create mode 100644 node_modules/esquery/dist/esquery.lite.min.js create mode 100644 node_modules/esquery/dist/esquery.lite.min.js.map create mode 100644 node_modules/esquery/dist/esquery.min.js create mode 100644 node_modules/esquery/dist/esquery.min.js.map create mode 100644 node_modules/js-yaml/dist/js-yaml.js create mode 100644 node_modules/js-yaml/dist/js-yaml.min.js create mode 100644 node_modules/js-yaml/dist/js-yaml.mjs create mode 100644 node_modules/json5/dist/index.js create mode 100644 node_modules/json5/dist/index.min.js create mode 100644 node_modules/json5/dist/index.min.mjs create mode 100644 node_modules/json5/dist/index.mjs create mode 100644 node_modules/leaflet/dist/images/layers-2x.png create mode 100644 node_modules/leaflet/dist/images/layers.png create mode 100644 node_modules/leaflet/dist/images/marker-icon-2x.png create mode 100644 node_modules/leaflet/dist/images/marker-icon.png create mode 100644 node_modules/leaflet/dist/images/marker-shadow.png create mode 100644 node_modules/leaflet/dist/leaflet-src.esm.js create mode 100644 node_modules/leaflet/dist/leaflet-src.esm.js.map create mode 100644 node_modules/leaflet/dist/leaflet-src.js create mode 100644 node_modules/leaflet/dist/leaflet-src.js.map create mode 100644 node_modules/leaflet/dist/leaflet.css create mode 100644 node_modules/leaflet/dist/leaflet.js create mode 100644 node_modules/leaflet/dist/leaflet.js.map create mode 100644 node_modules/object.assign/dist/browser.js create mode 100644 node_modules/react-router-dom/dist/dom.d.ts create mode 100644 node_modules/react-router-dom/dist/index.d.ts create mode 100644 node_modules/react-router-dom/dist/index.js create mode 100644 node_modules/react-router-dom/dist/index.js.map create mode 100644 node_modules/react-router-dom/dist/main.js create mode 100644 node_modules/react-router-dom/dist/react-router-dom.development.js create mode 100644 node_modules/react-router-dom/dist/react-router-dom.development.js.map create mode 100644 node_modules/react-router-dom/dist/react-router-dom.production.min.js create mode 100644 node_modules/react-router-dom/dist/react-router-dom.production.min.js.map create mode 100644 node_modules/react-router-dom/dist/server.d.ts create mode 100644 node_modules/react-router-dom/dist/server.js create mode 100644 node_modules/react-router-dom/dist/server.mjs create mode 100644 node_modules/react-router-dom/dist/umd/react-router-dom.development.js create mode 100644 node_modules/react-router-dom/dist/umd/react-router-dom.development.js.map create mode 100644 node_modules/react-router-dom/dist/umd/react-router-dom.production.min.js create mode 100644 node_modules/react-router-dom/dist/umd/react-router-dom.production.min.js.map create mode 100644 node_modules/react-router/dist/index.d.ts create mode 100644 node_modules/react-router/dist/index.js create mode 100644 node_modules/react-router/dist/index.js.map create mode 100644 node_modules/react-router/dist/lib/components.d.ts create mode 100644 node_modules/react-router/dist/lib/context.d.ts create mode 100644 node_modules/react-router/dist/lib/hooks.d.ts create mode 100644 node_modules/react-router/dist/main.js create mode 100644 node_modules/react-router/dist/react-router.development.js create mode 100644 node_modules/react-router/dist/react-router.development.js.map create mode 100644 node_modules/react-router/dist/react-router.production.min.js create mode 100644 node_modules/react-router/dist/react-router.production.min.js.map create mode 100644 node_modules/react-router/dist/umd/react-router.development.js create mode 100644 node_modules/react-router/dist/umd/react-router.development.js.map create mode 100644 node_modules/react-router/dist/umd/react-router.production.min.js create mode 100644 node_modules/react-router/dist/umd/react-router.production.min.js.map create mode 100644 node_modules/rollup/dist/bin/rollup create mode 100644 node_modules/rollup/dist/es/getLogFilter.js create mode 100644 node_modules/rollup/dist/es/package.json create mode 100644 node_modules/rollup/dist/es/parseAst.js create mode 100644 node_modules/rollup/dist/es/rollup.js create mode 100644 node_modules/rollup/dist/es/shared/node-entry.js create mode 100644 node_modules/rollup/dist/es/shared/parseAst.js create mode 100644 node_modules/rollup/dist/es/shared/watch.js create mode 100644 node_modules/rollup/dist/getLogFilter.d.ts create mode 100644 node_modules/rollup/dist/getLogFilter.js create mode 100644 node_modules/rollup/dist/loadConfigFile.d.ts create mode 100644 node_modules/rollup/dist/loadConfigFile.js create mode 100644 node_modules/rollup/dist/native.js create mode 100644 node_modules/rollup/dist/parseAst.d.ts create mode 100644 node_modules/rollup/dist/parseAst.js create mode 100644 node_modules/rollup/dist/rollup.d.ts create mode 100644 node_modules/rollup/dist/rollup.js create mode 100644 node_modules/rollup/dist/shared/fsevents-importer.js create mode 100644 node_modules/rollup/dist/shared/index.js create mode 100644 node_modules/rollup/dist/shared/loadConfigFile.js create mode 100644 node_modules/rollup/dist/shared/parseAst.js create mode 100644 node_modules/rollup/dist/shared/rollup.js create mode 100644 node_modules/rollup/dist/shared/watch-cli.js create mode 100644 node_modules/rollup/dist/shared/watch.js create mode 100644 node_modules/uri-js/dist/es5/uri.all.d.ts create mode 100644 node_modules/uri-js/dist/es5/uri.all.js create mode 100644 node_modules/uri-js/dist/es5/uri.all.js.map create mode 100644 node_modules/uri-js/dist/es5/uri.all.min.d.ts create mode 100644 node_modules/uri-js/dist/es5/uri.all.min.js create mode 100644 node_modules/uri-js/dist/es5/uri.all.min.js.map create mode 100644 node_modules/uri-js/dist/esnext/index.d.ts create mode 100644 node_modules/uri-js/dist/esnext/index.js create mode 100644 node_modules/uri-js/dist/esnext/index.js.map create mode 100644 node_modules/uri-js/dist/esnext/regexps-iri.d.ts create mode 100644 node_modules/uri-js/dist/esnext/regexps-iri.js create mode 100644 node_modules/uri-js/dist/esnext/regexps-iri.js.map create mode 100644 node_modules/uri-js/dist/esnext/regexps-uri.d.ts create mode 100644 node_modules/uri-js/dist/esnext/regexps-uri.js create mode 100644 node_modules/uri-js/dist/esnext/regexps-uri.js.map create mode 100644 node_modules/uri-js/dist/esnext/schemes/http.d.ts create mode 100644 node_modules/uri-js/dist/esnext/schemes/http.js create mode 100644 node_modules/uri-js/dist/esnext/schemes/http.js.map create mode 100644 node_modules/uri-js/dist/esnext/schemes/https.d.ts create mode 100644 node_modules/uri-js/dist/esnext/schemes/https.js create mode 100644 node_modules/uri-js/dist/esnext/schemes/https.js.map create mode 100644 node_modules/uri-js/dist/esnext/schemes/mailto.d.ts create mode 100644 node_modules/uri-js/dist/esnext/schemes/mailto.js create mode 100644 node_modules/uri-js/dist/esnext/schemes/mailto.js.map create mode 100644 node_modules/uri-js/dist/esnext/schemes/urn-uuid.d.ts create mode 100644 node_modules/uri-js/dist/esnext/schemes/urn-uuid.js create mode 100644 node_modules/uri-js/dist/esnext/schemes/urn-uuid.js.map create mode 100644 node_modules/uri-js/dist/esnext/schemes/urn.d.ts create mode 100644 node_modules/uri-js/dist/esnext/schemes/urn.js create mode 100644 node_modules/uri-js/dist/esnext/schemes/urn.js.map create mode 100644 node_modules/uri-js/dist/esnext/schemes/ws.d.ts create mode 100644 node_modules/uri-js/dist/esnext/schemes/ws.js create mode 100644 node_modules/uri-js/dist/esnext/schemes/ws.js.map create mode 100644 node_modules/uri-js/dist/esnext/schemes/wss.d.ts create mode 100644 node_modules/uri-js/dist/esnext/schemes/wss.js create mode 100644 node_modules/uri-js/dist/esnext/schemes/wss.js.map create mode 100644 node_modules/uri-js/dist/esnext/uri.d.ts create mode 100644 node_modules/uri-js/dist/esnext/uri.js create mode 100644 node_modules/uri-js/dist/esnext/uri.js.map create mode 100644 node_modules/uri-js/dist/esnext/util.d.ts create mode 100644 node_modules/uri-js/dist/esnext/util.js create mode 100644 node_modules/uri-js/dist/esnext/util.js.map create mode 100644 node_modules/vite/dist/client/client.mjs create mode 100644 node_modules/vite/dist/client/client.mjs.map create mode 100644 node_modules/vite/dist/client/env.mjs create mode 100644 node_modules/vite/dist/client/env.mjs.map create mode 100644 node_modules/vite/dist/node-cjs/publicUtils.cjs create mode 100644 node_modules/vite/dist/node/chunks/dep-8a-6Quh6.js create mode 100644 node_modules/vite/dist/node/chunks/dep-V3BH7oO1.js create mode 100644 node_modules/vite/dist/node/chunks/dep-ggdMrszO.js create mode 100644 node_modules/vite/dist/node/chunks/dep-kjUoH5nk.js create mode 100644 node_modules/vite/dist/node/chunks/dep-oIJQVJc7.js create mode 100644 node_modules/vite/dist/node/cli.js create mode 100644 node_modules/vite/dist/node/constants.js create mode 100644 node_modules/vite/dist/node/index.d.ts create mode 100644 node_modules/vite/dist/node/index.js diff --git a/.gitignore b/.gitignore index 1c83a0f..c363b3e 100644 --- a/.gitignore +++ b/.gitignore @@ -8,8 +8,7 @@ pnpm-debug.log* lerna-debug.log* -dist -dist-ssr + *.local # Editor directories and files diff --git a/dist/assets/index-3xO65pgW.css b/dist/assets/index-3xO65pgW.css new file mode 100644 index 0000000..abc62af --- /dev/null +++ b/dist/assets/index-3xO65pgW.css @@ -0,0 +1 @@ +.btn{background-color:#000}.header{width:100%;height:68px;background-color:#fff;position:relative;top:1em;right:20px;padding:0 20px;display:flex;justify-content:space-between}.labelMenu{cursor:pointer;background-color:#fff}li{list-style:none}.imgHeader{cursor:pointer}.menu{position:absolute;top:30px;right:-20px;width:150px;height:100vh;color:#eeecec;background-color:#fff;display:flex;flex-direction:column;gap:2em;z-index:10}.activated{color:#e6e0e0;background-color:#696565;border-radius:1em;text-decoration:none}.menuNav{text-decoration:none}.menuIcon{width:2em}@media (min-width: 760px){.menu{position:relative;top:0;right:40px;width:auto;height:auto;color:#eeecec;background-color:#fff;display:flex;flex-wrap:wrap;gap:2em;z-index:10}.menuIcon{opacity:0%}}.leaflet-pane,.leaflet-tile,.leaflet-marker-icon,.leaflet-marker-shadow,.leaflet-tile-container,.leaflet-pane>svg,.leaflet-pane>canvas,.leaflet-zoom-box,.leaflet-image-layer,.leaflet-layer{position:absolute;left:0;top:0}.leaflet-container{overflow:hidden}.leaflet-tile,.leaflet-marker-icon,.leaflet-marker-shadow{-webkit-user-select:none;-moz-user-select:none;user-select:none;-webkit-user-drag:none}.leaflet-tile::selection{background:transparent}.leaflet-safari .leaflet-tile{image-rendering:-webkit-optimize-contrast}.leaflet-safari .leaflet-tile-container{width:1600px;height:1600px;-webkit-transform-origin:0 0}.leaflet-marker-icon,.leaflet-marker-shadow{display:block}.leaflet-container .leaflet-overlay-pane svg{max-width:none!important;max-height:none!important}.leaflet-container .leaflet-marker-pane img,.leaflet-container .leaflet-shadow-pane img,.leaflet-container .leaflet-tile-pane img,.leaflet-container img.leaflet-image-layer,.leaflet-container .leaflet-tile{max-width:none!important;max-height:none!important;width:auto;padding:0}.leaflet-container img.leaflet-tile{mix-blend-mode:plus-lighter}.leaflet-container.leaflet-touch-zoom{-ms-touch-action:pan-x pan-y;touch-action:pan-x pan-y}.leaflet-container.leaflet-touch-drag{-ms-touch-action:pinch-zoom;touch-action:none;touch-action:pinch-zoom}.leaflet-container.leaflet-touch-drag.leaflet-touch-zoom{-ms-touch-action:none;touch-action:none}.leaflet-container{-webkit-tap-highlight-color:transparent}.leaflet-container a{-webkit-tap-highlight-color:rgba(51,181,229,.4)}.leaflet-tile{filter:inherit;visibility:hidden}.leaflet-tile-loaded{visibility:inherit}.leaflet-zoom-box{width:0;height:0;-moz-box-sizing:border-box;box-sizing:border-box;z-index:800}.leaflet-overlay-pane svg{-moz-user-select:none}.leaflet-pane{z-index:400}.leaflet-tile-pane{z-index:200}.leaflet-overlay-pane{z-index:400}.leaflet-shadow-pane{z-index:500}.leaflet-marker-pane{z-index:600}.leaflet-tooltip-pane{z-index:650}.leaflet-popup-pane{z-index:700}.leaflet-map-pane canvas{z-index:100}.leaflet-map-pane svg{z-index:200}.leaflet-vml-shape{width:1px;height:1px}.lvml{behavior:url(#default#VML);display:inline-block;position:absolute}.leaflet-control{position:relative;z-index:800;pointer-events:visiblePainted;pointer-events:auto}.leaflet-top,.leaflet-bottom{position:absolute;z-index:1000;pointer-events:none}.leaflet-top{top:0}.leaflet-right{right:0}.leaflet-bottom{bottom:0}.leaflet-left{left:0}.leaflet-control{float:left;clear:both}.leaflet-right .leaflet-control{float:right}.leaflet-top .leaflet-control{margin-top:10px}.leaflet-bottom .leaflet-control{margin-bottom:10px}.leaflet-left .leaflet-control{margin-left:10px}.leaflet-right .leaflet-control{margin-right:10px}.leaflet-fade-anim .leaflet-popup{opacity:0;-webkit-transition:opacity .2s linear;-moz-transition:opacity .2s linear;transition:opacity .2s linear}.leaflet-fade-anim .leaflet-map-pane .leaflet-popup{opacity:1}.leaflet-zoom-animated{-webkit-transform-origin:0 0;-ms-transform-origin:0 0;transform-origin:0 0}svg.leaflet-zoom-animated{will-change:transform}.leaflet-zoom-anim .leaflet-zoom-animated{-webkit-transition:-webkit-transform .25s cubic-bezier(0,0,.25,1);-moz-transition:-moz-transform .25s cubic-bezier(0,0,.25,1);transition:transform .25s cubic-bezier(0,0,.25,1)}.leaflet-zoom-anim .leaflet-tile,.leaflet-pan-anim .leaflet-tile{-webkit-transition:none;-moz-transition:none;transition:none}.leaflet-zoom-anim .leaflet-zoom-hide{visibility:hidden}.leaflet-interactive{cursor:pointer}.leaflet-grab{cursor:-webkit-grab;cursor:-moz-grab;cursor:grab}.leaflet-crosshair,.leaflet-crosshair .leaflet-interactive{cursor:crosshair}.leaflet-popup-pane,.leaflet-control{cursor:auto}.leaflet-dragging .leaflet-grab,.leaflet-dragging .leaflet-grab .leaflet-interactive,.leaflet-dragging .leaflet-marker-draggable{cursor:move;cursor:-webkit-grabbing;cursor:-moz-grabbing;cursor:grabbing}.leaflet-marker-icon,.leaflet-marker-shadow,.leaflet-image-layer,.leaflet-pane>svg path,.leaflet-tile-container{pointer-events:none}.leaflet-marker-icon.leaflet-interactive,.leaflet-image-layer.leaflet-interactive,.leaflet-pane>svg path.leaflet-interactive,svg.leaflet-image-layer.leaflet-interactive path{pointer-events:visiblePainted;pointer-events:auto}.leaflet-container{background:#ddd;outline-offset:1px}.leaflet-container a{color:#0078a8}.leaflet-zoom-box{border:2px dotted #38f;background:#ffffff80}.leaflet-container{font-family:Helvetica Neue,Arial,Helvetica,sans-serif;font-size:12px;font-size:.75rem;line-height:1.5}.leaflet-bar{box-shadow:0 1px 5px #000000a6;border-radius:4px}.leaflet-bar a{background-color:#fff;border-bottom:1px solid #ccc;width:26px;height:26px;line-height:26px;display:block;text-align:center;text-decoration:none;color:#000}.leaflet-bar a,.leaflet-control-layers-toggle{background-position:50% 50%;background-repeat:no-repeat;display:block}.leaflet-bar a:hover,.leaflet-bar a:focus{background-color:#f4f4f4}.leaflet-bar a:first-child{border-top-left-radius:4px;border-top-right-radius:4px}.leaflet-bar a:last-child{border-bottom-left-radius:4px;border-bottom-right-radius:4px;border-bottom:none}.leaflet-bar a.leaflet-disabled{cursor:default;background-color:#f4f4f4;color:#bbb}.leaflet-touch .leaflet-bar a{width:30px;height:30px;line-height:30px}.leaflet-touch .leaflet-bar a:first-child{border-top-left-radius:2px;border-top-right-radius:2px}.leaflet-touch .leaflet-bar a:last-child{border-bottom-left-radius:2px;border-bottom-right-radius:2px}.leaflet-control-zoom-in,.leaflet-control-zoom-out{font:700 18px Lucida Console,Monaco,monospace;text-indent:1px}.leaflet-touch .leaflet-control-zoom-in,.leaflet-touch .leaflet-control-zoom-out{font-size:22px}.leaflet-control-layers{box-shadow:0 1px 5px #0006;background:#fff;border-radius:5px}.leaflet-control-layers-toggle{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAQAAAADQ4RFAAACf0lEQVR4AY1UM3gkARTePdvdoTxXKc+qTl3aU5U6b2Kbkz3Gtq3Zw6ziLGNPzrYx7946Tr6/ee/XeCQ4D3ykPtL5tHno4n0d/h3+xfuWHGLX81cn7r0iTNzjr7LrlxCqPtkbTQEHeqOrTy4Yyt3VCi/IOB0v7rVC7q45Q3Gr5K6jt+3Gl5nCoDD4MtO+j96Wu8atmhGqcNGHObuf8OM/x3AMx38+4Z2sPqzCxRFK2aF2e5Jol56XTLyggAMTL56XOMoS1W4pOyjUcGGQdZxU6qRh7B9Zp+PfpOFlqt0zyDZckPi1ttmIp03jX8gyJ8a/PG2yutpS/Vol7peZIbZcKBAEEheEIAgFbDkz5H6Zrkm2hVWGiXKiF4Ycw0RWKdtC16Q7qe3X4iOMxruonzegJzWaXFrU9utOSsLUmrc0YjeWYjCW4PDMADElpJSSQ0vQvA1Tm6/JlKnqFs1EGyZiFCqnRZTEJJJiKRYzVYzJck2Rm6P4iH+cmSY0YzimYa8l0EtTODFWhcMIMVqdsI2uiTvKmTisIDHJ3od5GILVhBCarCfVRmo4uTjkhrhzkiBV7SsaqS+TzrzM1qpGGUFt28pIySQHR6h7F6KSwGWm97ay+Z+ZqMcEjEWebE7wxCSQwpkhJqoZA5ivCdZDjJepuJ9IQjGGUmuXJdBFUygxVqVsxFsLMbDe8ZbDYVCGKxs+W080max1hFCarCfV+C1KATwcnvE9gRRuMP2prdbWGowm1KB1y+zwMMENkM755cJ2yPDtqhTI6ED1M/82yIDtC/4j4BijjeObflpO9I9MwXTCsSX8jWAFeHr05WoLTJ5G8IQVS/7vwR6ohirYM7f6HzYpogfS3R2OAAAAAElFTkSuQmCC);width:36px;height:36px}.leaflet-retina .leaflet-control-layers-toggle{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADQAAAA0CAQAAABvcdNgAAAEsklEQVR4AWL4TydIhpZK1kpWOlg0w3ZXP6D2soBtG42jeI6ZmQTHzAxiTbSJsYLjO9HhP+WOmcuhciVnmHVQcJnp7DFvScowZorad/+V/fVzMdMT2g9Cv9guXGv/7pYOrXh2U+RRR3dSd9JRx6bIFc/ekqHI29JC6pJ5ZEh1yWkhkbcFeSjxgx3L2m1cb1C7bceyxA+CNjT/Ifff+/kDk2u/w/33/IeCMOSaWZ4glosqT3DNnNZQ7Cs58/3Ce5HL78iZH/vKVIaYlqzfdLu8Vi7dnvUbEza5Idt36tquZFldl6N5Z/POLof0XLK61mZCmJSWjVF9tEjUluu74IUXvgttuVIHE7YxSkaYhJZam7yiM9Pv82JYfl9nptxZaxMJE4YSPty+vF0+Y2up9d3wwijfjZbabqm/3bZ9ecKHsiGmRflnn1MW4pjHf9oLufyn2z3y1D6n8g8TZhxyzipLNPnAUpsOiuWimg52psrTZYnOWYNDTMuWBWa0tJb4rgq1UvmutpaYEbZlwU3CLJm/ayYjHW5/h7xWLn9Hh1vepDkyf7dE7MtT5LR4e7yYpHrkhOUpEfssBLq2pPhAqoSWKUkk7EDqkmK6RrCEzqDjhNDWNE+XSMvkJRDWlZTmCW0l0PHQGRZY5t1L83kT0Y3l2SItk5JAWHl2dCOBm+fPu3fo5/3v61RMCO9Jx2EEYYhb0rmNQMX/vm7gqOEJLcXTGw3CAuRNeyaPWwjR8PRqKQ1PDA/dpv+on9Shox52WFnx0KY8onHayrJzm87i5h9xGw/tfkev0jGsQizqezUKjk12hBMKJ4kbCqGPVNXudyyrShovGw5CgxsRICxF6aRmSjlBnHRzg7Gx8fKqEubI2rahQYdR1YgDIRQO7JvQyD52hoIQx0mxa0ODtW2Iozn1le2iIRdzwWewedyZzewidueOGqlsn1MvcnQpuVwLGG3/IR1hIKxCjelIDZ8ldqWz25jWAsnldEnK0Zxro19TGVb2ffIZEsIO89EIEDvKMPrzmBOQcKQ+rroye6NgRRxqR4U8EAkz0CL6uSGOm6KQCdWjvjRiSP1BPalCRS5iQYiEIvxuBMJEWgzSoHADcVMuN7IuqqTeyUPq22qFimFtxDyBBJEwNyt6TM88blFHao/6tWWhuuOM4SAK4EI4QmFHA+SEyWlp4EQoJ13cYGzMu7yszEIBOm2rVmHUNqwAIQabISNMRstmdhNWcFLsSm+0tjJH1MdRxO5Nx0WDMhCtgD6OKgZeljJqJKc9po8juskR9XN0Y1lZ3mWjLR9JCO1jRDMd0fpYC2VnvjBSEFg7wBENc0R9HFlb0xvF1+TBEpF68d+DHR6IOWVv2BECtxo46hOFUBd/APU57WIoEwJhIi2CdpyZX0m93BZicktMj1AS9dClteUFAUNUIEygRZCtik5zSxI9MubTBH1GOiHsiLJ3OCoSZkILa9PxiN0EbvhsAo8tdAf9Seepd36lGWHmtNANTv5Jd0z4QYyeo/UEJqxKRpg5LZx6btLPsOaEmdMyxYdlc8LMaJnikDlhclqmPiQnTEpLUIZEwkRagjYkEibQErwhkTAKCLQEbUgkzJQWc/0PstHHcfEdQ+UAAAAASUVORK5CYII=);background-size:26px 26px}.leaflet-touch .leaflet-control-layers-toggle{width:44px;height:44px}.leaflet-control-layers .leaflet-control-layers-list,.leaflet-control-layers-expanded .leaflet-control-layers-toggle{display:none}.leaflet-control-layers-expanded .leaflet-control-layers-list{display:block;position:relative}.leaflet-control-layers-expanded{padding:6px 10px 6px 6px;color:#333;background:#fff}.leaflet-control-layers-scrollbar{overflow-y:scroll;overflow-x:hidden;padding-right:5px}.leaflet-control-layers-selector{margin-top:2px;position:relative;top:1px}.leaflet-control-layers label{display:block;font-size:13px;font-size:1.08333em}.leaflet-control-layers-separator{height:0;border-top:1px solid #ddd;margin:5px -10px 5px -6px}.leaflet-default-icon-path{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAApCAYAAADAk4L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awhOKMLkrQLyVpZg8rHFW7E2uHOL888IBPlNZ1FPzstSJM694fWr6RwpvcJK60+0HCILTBzZLFNdtAzJaohze60T8qBzyh5ZuOg5e7uwQppofEmf2++DYvmySqGBuKaicF1blQjhuHdvCIMvp8whTTfZzI7RldpwtSzL+F1+wkdZ2TBOW2gIF88PBTzD/gpeREAMEbxnJcaJHNHrpzji0gQCS6hdkEeYt9DF/2qPcEC8RM28Hwmr3sdNyht00byAut2k3gufWNtgtOEOFGUwcXWNDbdNbpgBGxEvKkOQsxivJx33iow0Vw5S6SVTrpVq11ysA2Rp7gTfPfktc6zhtXBBC+adRLshf6sG2RfHPZ5EAc4sVZ83yCN00Fk/4kggu40ZTvIEm5g24qtU4KjBrx/BTTH8ifVASAG7gKrnWxJDcU7x8X6Ecczhm3o6YicvsLXWfh3Ch1W0k8x0nXF+0fFxgt4phz8QvypiwCCFKMqXCnqXExjq10beH+UUA7+nG6mdG/Pu0f3LgFcGrl2s0kNNjpmoJ9o4B29CMO8dMT4Q5ox8uitF6fqsrJOr8qnwNbRzv6hSnG5wP+64C7h9lp30hKNtKdWjtdkbuPA19nJ7Tz3zR/ibgARbhb4AlhavcBebmTHcFl2fvYEnW0ox9xMxKBS8btJ+KiEbq9zA4RthQXDhPa0T9TEe69gWupwc6uBUphquXgf+/FrIjweHQS4/pduMe5ERUMHUd9xv8ZR98CxkS4F2n3EUrUZ10EYNw7BWm9x1GiPssi3GgiGRDKWRYZfXlON+dfNbM+GgIwYdwAAAAASUVORK5CYII=)}.leaflet-container .leaflet-control-attribution{background:#fff;background:#fffc;margin:0}.leaflet-control-attribution,.leaflet-control-scale-line{padding:0 5px;color:#333;line-height:1.4}.leaflet-control-attribution a{text-decoration:none}.leaflet-control-attribution a:hover,.leaflet-control-attribution a:focus{text-decoration:underline}.leaflet-attribution-flag{display:inline!important;vertical-align:baseline!important;width:1em;height:.6669em}.leaflet-left .leaflet-control-scale{margin-left:5px}.leaflet-bottom .leaflet-control-scale{margin-bottom:5px}.leaflet-control-scale-line{border:2px solid #777;border-top:none;line-height:1.1;padding:2px 5px 1px;white-space:nowrap;-moz-box-sizing:border-box;box-sizing:border-box;background:#fffc;text-shadow:1px 1px #fff}.leaflet-control-scale-line:not(:first-child){border-top:2px solid #777;border-bottom:none;margin-top:-2px}.leaflet-control-scale-line:not(:first-child):not(:last-child){border-bottom:2px solid #777}.leaflet-touch .leaflet-control-attribution,.leaflet-touch .leaflet-control-layers,.leaflet-touch .leaflet-bar{box-shadow:none}.leaflet-touch .leaflet-control-layers,.leaflet-touch .leaflet-bar{border:2px solid rgba(0,0,0,.2);background-clip:padding-box}.leaflet-popup{position:absolute;text-align:center;margin-bottom:20px}.leaflet-popup-content-wrapper{padding:1px;text-align:left;border-radius:12px}.leaflet-popup-content{margin:13px 24px 13px 20px;line-height:1.3;font-size:13px;font-size:1.08333em;min-height:1px}.leaflet-popup-content p{margin:1.3em 0}.leaflet-popup-tip-container{width:40px;height:20px;position:absolute;left:50%;margin-top:-1px;margin-left:-20px;overflow:hidden;pointer-events:none}.leaflet-popup-tip{width:17px;height:17px;padding:1px;margin:-10px auto 0;pointer-events:auto;-webkit-transform:rotate(45deg);-moz-transform:rotate(45deg);-ms-transform:rotate(45deg);transform:rotate(45deg)}.leaflet-popup-content-wrapper,.leaflet-popup-tip{background:#fff;color:#333;box-shadow:0 3px 14px #0006}.leaflet-container a.leaflet-popup-close-button{position:absolute;top:0;right:0;border:none;text-align:center;width:24px;height:24px;font:16px/24px Tahoma,Verdana,sans-serif;color:#757575;text-decoration:none;background:transparent}.leaflet-container a.leaflet-popup-close-button:hover,.leaflet-container a.leaflet-popup-close-button:focus{color:#585858}.leaflet-popup-scrolled{overflow:auto}.leaflet-oldie .leaflet-popup-content-wrapper{-ms-zoom:1}.leaflet-oldie .leaflet-popup-tip{width:24px;margin:0 auto;-ms-filter:"progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";filter:progid:DXImageTransform.Microsoft.Matrix(M11=.70710678,M12=.70710678,M21=-.70710678,M22=.70710678)}.leaflet-oldie .leaflet-control-zoom,.leaflet-oldie .leaflet-control-layers,.leaflet-oldie .leaflet-popup-content-wrapper,.leaflet-oldie .leaflet-popup-tip{border:1px solid #999}.leaflet-div-icon{background:#fff;border:1px solid #666}.leaflet-tooltip{position:absolute;padding:6px;background-color:#fff;border:1px solid #fff;border-radius:3px;color:#222;white-space:nowrap;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;pointer-events:none;box-shadow:0 1px 3px #0006}.leaflet-tooltip.leaflet-interactive{cursor:pointer;pointer-events:auto}.leaflet-tooltip-top:before,.leaflet-tooltip-bottom:before,.leaflet-tooltip-left:before,.leaflet-tooltip-right:before{position:absolute;pointer-events:none;border:6px solid transparent;background:transparent;content:""}.leaflet-tooltip-bottom{margin-top:6px}.leaflet-tooltip-top{margin-top:-6px}.leaflet-tooltip-bottom:before,.leaflet-tooltip-top:before{left:50%;margin-left:-6px}.leaflet-tooltip-top:before{bottom:0;margin-bottom:-12px;border-top-color:#fff}.leaflet-tooltip-bottom:before{top:0;margin-top:-12px;margin-left:-6px;border-bottom-color:#fff}.leaflet-tooltip-left{margin-left:-6px}.leaflet-tooltip-right{margin-left:6px}.leaflet-tooltip-left:before,.leaflet-tooltip-right:before{top:50%;margin-top:-6px}.leaflet-tooltip-left:before{right:0;margin-right:-12px;border-left-color:#fff}.leaflet-tooltip-right:before{left:0;margin-left:-12px;border-right-color:#fff}@media print{.leaflet-control{-webkit-print-color-adjust:exact;print-color-adjust:exact}}@media (max-width: 600px){.modal{width:25rem;display:flex;flex-direction:column;align-items:center;color:#d1cfcf;background-color:#000;gap:auto;text-align:center}.imgModal{width:25rem;height:25rem}.modal h3{position:relative;color:#8b5d05;margin-bottom:0}}.modal{width:350px;display:flex;flex-direction:column;align-items:center;color:#d1cfcf;background-color:#000;gap:auto;text-align:center}.imgModal{width:350px;height:350px}.modal h3{position:relative;color:#8b5d05;margin-bottom:0}.body{display:flex;flex-direction:column;align-items:center;gap:4em;width:100%;height:auto}.contact{display:flex;flex-direction:column;align-items:center}.portada{display:flex;flex-direction:column;align-items:center;width:100%}.location{display:flex;flex-direction:column;align-items:center;width:60%;height:20em;z-index:4}.whatsapp{width:2em}.text{text-align:center;display:flex;flex-direction:column;align-items:center}.btnCart{color:#fff;background-color:#c27575;border:none;width:10em;height:3em}.btnCart:hover{color:#fff;background-color:#ebc6c6;border:none}.btnCart:active{color:#fff;background-color:#615c5c;transition:.3s}.textOver{color:#fff;position:absolute;z-index:1;text-align:center;display:flex;flex-direction:column;gap:5em}.modals{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:4rem;padding:2em;width:100%;background-color:#e7e0d7}.portada img{width:100%}.imgContact img{height:2em;padding:7px}.whatsappContainer{position:fixed;bottom:20px;right:20px;cursor:pointer}.btn{border-radius:2em;cursor:pointer}.dates{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:4rem;padding:2em;width:100%;background-color:#e7e0d7}@media (min-width: 760px){.fornMariu{font-size:xx-large}.btnCart{font-size:large}}footer{background-color:#f7f1e5;height:4em;padding:1.5em;margin-left:-1em;width:100%;display:flex;text-align:center;justify-content:center}.products{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:4em;padding:2em 3em 3em}h2{padding:2em;display:flex;flex-direction:column;align-items:center} diff --git a/dist/assets/index-wnzOmW71.js b/dist/assets/index-wnzOmW71.js new file mode 100644 index 0000000..ba2606e --- /dev/null +++ b/dist/assets/index-wnzOmW71.js @@ -0,0 +1,70 @@ +function a_(e,t){for(var i=0;io[a]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))o(a);new MutationObserver(a=>{for(const l of a)if(l.type==="childList")for(const c of l.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&o(c)}).observe(document,{childList:!0,subtree:!0});function i(a){const l={};return a.integrity&&(l.integrity=a.integrity),a.referrerPolicy&&(l.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?l.credentials="include":a.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function o(a){if(a.ep)return;a.ep=!0;const l=i(a);fetch(a.href,l)}})();var l_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function u_(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var oh={exports:{}},os={},sh={exports:{}},J={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var zr=Symbol.for("react.element"),c_=Symbol.for("react.portal"),f_=Symbol.for("react.fragment"),h_=Symbol.for("react.strict_mode"),d_=Symbol.for("react.profiler"),p_=Symbol.for("react.provider"),m_=Symbol.for("react.context"),__=Symbol.for("react.forward_ref"),v_=Symbol.for("react.suspense"),g_=Symbol.for("react.memo"),y_=Symbol.for("react.lazy"),Uc=Symbol.iterator;function w_(e){return e===null||typeof e!="object"?null:(e=Uc&&e[Uc]||e["@@iterator"],typeof e=="function"?e:null)}var ah={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},lh=Object.assign,uh={};function Si(e,t,i){this.props=e,this.context=t,this.refs=uh,this.updater=i||ah}Si.prototype.isReactComponent={};Si.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Si.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function ch(){}ch.prototype=Si.prototype;function Ol(e,t,i){this.props=e,this.context=t,this.refs=uh,this.updater=i||ah}var Il=Ol.prototype=new ch;Il.constructor=Ol;lh(Il,Si.prototype);Il.isPureReactComponent=!0;var Wc=Array.isArray,fh=Object.prototype.hasOwnProperty,Rl={current:null},hh={key:!0,ref:!0,__self:!0,__source:!0};function dh(e,t,i){var o,a={},l=null,c=null;if(t!=null)for(o in t.ref!==void 0&&(c=t.ref),t.key!==void 0&&(l=""+t.key),t)fh.call(t,o)&&!hh.hasOwnProperty(o)&&(a[o]=t[o]);var d=arguments.length-2;if(d===1)a.children=i;else if(1>>1,ee=M[Q];if(0>>1;Qa(ne,R))Ka(Qe,ne)?(M[Q]=Qe,M[K]=R,Q=K):(M[Q]=ne,M[se]=R,Q=se);else if(Ka(Qe,R))M[Q]=Qe,M[K]=R,Q=K;else break e}}return b}function a(M,b){var R=M.sortIndex-b.sortIndex;return R!==0?R:M.id-b.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var c=Date,d=c.now();e.unstable_now=function(){return c.now()-d}}var p=[],m=[],x=1,w=null,P=3,C=!1,A=!1,E=!1,j=typeof setTimeout=="function"?setTimeout:null,g=typeof clearTimeout=="function"?clearTimeout:null,_=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function y(M){for(var b=i(m);b!==null;){if(b.callback===null)o(m);else if(b.startTime<=M)o(m),b.sortIndex=b.expirationTime,t(p,b);else break;b=i(m)}}function T(M){if(E=!1,y(M),!A)if(i(p)!==null)A=!0,ze(B);else{var b=i(m);b!==null&&Ot(T,b.startTime-M)}}function B(M,b){A=!1,E&&(E=!1,g(W),W=-1),C=!0;var R=P;try{for(y(b),w=i(p);w!==null&&(!(w.expirationTime>b)||M&&!ae());){var Q=w.callback;if(typeof Q=="function"){w.callback=null,P=w.priorityLevel;var ee=Q(w.expirationTime<=b);b=e.unstable_now(),typeof ee=="function"?w.callback=ee:w===i(p)&&o(p),y(b)}else o(p);w=i(p)}if(w!==null)var ke=!0;else{var se=i(m);se!==null&&Ot(T,se.startTime-b),ke=!1}return ke}finally{w=null,P=R,C=!1}}var F=!1,U=null,W=-1,re=5,X=-1;function ae(){return!(e.unstable_now()-XM||125Q?(M.sortIndex=R,t(m,M),i(p)===null&&M===i(m)&&(E?(g(W),W=-1):E=!0,Ot(T,R-Q))):(M.sortIndex=ee,t(p,M),A||C||(A=!0,ze(B))),M},e.unstable_shouldYield=ae,e.unstable_wrapCallback=function(M){var b=P;return function(){var R=P;P=b;try{return M.apply(this,arguments)}finally{P=R}}}})(vh);_h.exports=vh;var N_=_h.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var gh=O,tt=N_;function I(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,i=1;i"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ia=Object.prototype.hasOwnProperty,O_=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Vc={},Qc={};function I_(e){return Ia.call(Qc,e)?!0:Ia.call(Vc,e)?!1:O_.test(e)?Qc[e]=!0:(Vc[e]=!0,!1)}function R_(e,t,i,o){if(i!==null&&i.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return o?!1:i!==null?!i.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function B_(e,t,i,o){if(t===null||typeof t>"u"||R_(e,t,i,o))return!0;if(o)return!1;if(i!==null)switch(i.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Ve(e,t,i,o,a,l,c){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=o,this.attributeNamespace=a,this.mustUseProperty=i,this.propertyName=e,this.type=t,this.sanitizeURL=l,this.removeEmptyString=c}var Re={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Re[e]=new Ve(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Re[t]=new Ve(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Re[e]=new Ve(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Re[e]=new Ve(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Re[e]=new Ve(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Re[e]=new Ve(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Re[e]=new Ve(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Re[e]=new Ve(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Re[e]=new Ve(e,5,!1,e.toLowerCase(),null,!1,!1)});var jl=/[\-:]([a-z])/g;function Zl(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(jl,Zl);Re[t]=new Ve(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(jl,Zl);Re[t]=new Ve(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(jl,Zl);Re[t]=new Ve(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Re[e]=new Ve(e,1,!1,e.toLowerCase(),null,!1,!1)});Re.xlinkHref=new Ve("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Re[e]=new Ve(e,1,!1,e.toLowerCase(),null,!0,!0)});function Dl(e,t,i,o){var a=Re.hasOwnProperty(t)?Re[t]:null;(a!==null?a.type!==0:o||!(2d||a[c]!==l[d]){var p=` +`+a[c].replace(" at new "," at ");return e.displayName&&p.includes("")&&(p=p.replace("",e.displayName)),p}while(1<=c&&0<=d);break}}}finally{la=!1,Error.prepareStackTrace=i}return(e=e?e.displayName||e.name:"")?Yi(e):""}function j_(e){switch(e.tag){case 5:return Yi(e.type);case 16:return Yi("Lazy");case 13:return Yi("Suspense");case 19:return Yi("SuspenseList");case 0:case 2:case 15:return e=ua(e.type,!1),e;case 11:return e=ua(e.type.render,!1),e;case 1:return e=ua(e.type,!0),e;default:return""}}function Za(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case $n:return"Fragment";case Jn:return"Portal";case Ra:return"Profiler";case Fl:return"StrictMode";case Ba:return"Suspense";case ja:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case xh:return(e.displayName||"Context")+".Consumer";case wh:return(e._context.displayName||"Context")+".Provider";case Ul:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Wl:return t=e.displayName||null,t!==null?t:Za(e.type)||"Memo";case Jt:t=e._payload,e=e._init;try{return Za(e(t))}catch{}}return null}function Z_(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Za(t);case 8:return t===Fl?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function mn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Sh(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function D_(e){var t=Sh(e)?"checked":"value",i=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),o=""+e[t];if(!e.hasOwnProperty(t)&&typeof i<"u"&&typeof i.get=="function"&&typeof i.set=="function"){var a=i.get,l=i.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(c){o=""+c,l.call(this,c)}}),Object.defineProperty(e,t,{enumerable:i.enumerable}),{getValue:function(){return o},setValue:function(c){o=""+c},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function ro(e){e._valueTracker||(e._valueTracker=D_(e))}function kh(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var i=t.getValue(),o="";return e&&(o=Sh(e)?e.checked?"true":"false":e.value),e=o,e!==i?(t.setValue(e),!0):!1}function No(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Da(e,t){var i=t.checked;return _e({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:i??e._wrapperState.initialChecked})}function Kc(e,t){var i=t.defaultValue==null?"":t.defaultValue,o=t.checked!=null?t.checked:t.defaultChecked;i=mn(t.value!=null?t.value:i),e._wrapperState={initialChecked:o,initialValue:i,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Lh(e,t){t=t.checked,t!=null&&Dl(e,"checked",t,!1)}function Fa(e,t){Lh(e,t);var i=mn(t.value),o=t.type;if(i!=null)o==="number"?(i===0&&e.value===""||e.value!=i)&&(e.value=""+i):e.value!==""+i&&(e.value=""+i);else if(o==="submit"||o==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Ua(e,t.type,i):t.hasOwnProperty("defaultValue")&&Ua(e,t.type,mn(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Gc(e,t,i){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var o=t.type;if(!(o!=="submit"&&o!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,i||t===e.value||(e.value=t),e.defaultValue=t}i=e.name,i!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,i!==""&&(e.name=i)}function Ua(e,t,i){(t!=="number"||No(e.ownerDocument)!==e)&&(i==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+i&&(e.defaultValue=""+i))}var qi=Array.isArray;function ci(e,t,i,o){if(e=e.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=oo.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function hr(e,t){if(t){var i=e.firstChild;if(i&&i===e.lastChild&&i.nodeType===3){i.nodeValue=t;return}}e.textContent=t}var er={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},F_=["Webkit","ms","Moz","O"];Object.keys(er).forEach(function(e){F_.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),er[t]=er[e]})});function Th(e,t,i){return t==null||typeof t=="boolean"||t===""?"":i||typeof t!="number"||t===0||er.hasOwnProperty(e)&&er[e]?(""+t).trim():t+"px"}function Mh(e,t){e=e.style;for(var i in t)if(t.hasOwnProperty(i)){var o=i.indexOf("--")===0,a=Th(i,t[i],o);i==="float"&&(i="cssFloat"),o?e.setProperty(i,a):e[i]=a}}var U_=_e({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Va(e,t){if(t){if(U_[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(I(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(I(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(I(61))}if(t.style!=null&&typeof t.style!="object")throw Error(I(62))}}function Qa(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var ba=null;function Hl(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Ka=null,fi=null,hi=null;function qc(e){if(e=Ir(e)){if(typeof Ka!="function")throw Error(I(280));var t=e.stateNode;t&&(t=cs(t),Ka(e.stateNode,e.type,t))}}function zh(e){fi?hi?hi.push(e):hi=[e]:fi=e}function Nh(){if(fi){var e=fi,t=hi;if(hi=fi=null,qc(e),t)for(e=0;e>>=0,e===0?32:31-(J_(e)/$_|0)|0}var so=64,ao=4194304;function Ji(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Bo(e,t){var i=e.pendingLanes;if(i===0)return 0;var o=0,a=e.suspendedLanes,l=e.pingedLanes,c=i&268435455;if(c!==0){var d=c&~a;d!==0?o=Ji(d):(l&=c,l!==0&&(o=Ji(l)))}else c=i&~a,c!==0?o=Ji(c):l!==0&&(o=Ji(l));if(o===0)return 0;if(t!==0&&t!==o&&!(t&a)&&(a=o&-o,l=t&-t,a>=l||a===16&&(l&4194240)!==0))return t;if(o&4&&(o|=i&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=o;0i;i++)t.push(e);return t}function Nr(e,t,i){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-xt(t),e[t]=i}function iv(e,t){var i=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var o=e.eventTimes;for(e=e.expirationTimes;0=nr),af=" ",lf=!1;function Jh(e,t){switch(e){case"keyup":return zv.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function $h(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ei=!1;function Ov(e,t){switch(e){case"compositionend":return $h(t);case"keypress":return t.which!==32?null:(lf=!0,af);case"textInput":return e=t.data,e===af&&lf?null:e;default:return null}}function Iv(e,t){if(ei)return e==="compositionend"||!ql&&Jh(e,t)?(e=Yh(),So=Gl=nn=null,ei=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:i,offset:t-e};e=o}e:{for(;i;){if(i.nextSibling){i=i.nextSibling;break e}i=i.parentNode}i=void 0}i=hf(i)}}function id(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?id(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function rd(){for(var e=window,t=No();t instanceof e.HTMLIFrameElement;){try{var i=typeof t.contentWindow.location.href=="string"}catch{i=!1}if(i)e=t.contentWindow;else break;t=No(e.document)}return t}function Jl(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Hv(e){var t=rd(),i=e.focusedElem,o=e.selectionRange;if(t!==i&&i&&i.ownerDocument&&id(i.ownerDocument.documentElement,i)){if(o!==null&&Jl(i)){if(t=o.start,e=o.end,e===void 0&&(e=t),"selectionStart"in i)i.selectionStart=t,i.selectionEnd=Math.min(e,i.value.length);else if(e=(t=i.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var a=i.textContent.length,l=Math.min(o.start,a);o=o.end===void 0?l:Math.min(o.end,a),!e.extend&&l>o&&(a=o,o=l,l=a),a=df(i,l);var c=df(i,o);a&&c&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==c.node||e.focusOffset!==c.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),e.removeAllRanges(),l>o?(e.addRange(t),e.extend(c.node,c.offset)):(t.setEnd(c.node,c.offset),e.addRange(t)))}}for(t=[],e=i;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof i.focus=="function"&&i.focus(),i=0;i=document.documentMode,ti=null,$a=null,rr=null,el=!1;function pf(e,t,i){var o=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;el||ti==null||ti!==No(o)||(o=ti,"selectionStart"in o&&Jl(o)?o={start:o.selectionStart,end:o.selectionEnd}:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection(),o={anchorNode:o.anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset}),rr&&gr(rr,o)||(rr=o,o=Do($a,"onSelect"),0ri||(e.current=sl[ri],sl[ri]=null,ri--)}function ue(e,t){ri++,sl[ri]=e.current,e.current=t}var _n={},De=gn(_n),Xe=gn(!1),In=_n;function vi(e,t){var i=e.type.contextTypes;if(!i)return _n;var o=e.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===t)return o.__reactInternalMemoizedMaskedChildContext;var a={},l;for(l in i)a[l]=t[l];return o&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function Ye(e){return e=e.childContextTypes,e!=null}function Uo(){fe(Xe),fe(De)}function xf(e,t,i){if(De.current!==_n)throw Error(I(168));ue(De,t),ue(Xe,i)}function dd(e,t,i){var o=e.stateNode;if(t=t.childContextTypes,typeof o.getChildContext!="function")return i;o=o.getChildContext();for(var a in o)if(!(a in t))throw Error(I(108,Z_(e)||"Unknown",a));return _e({},i,o)}function Wo(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||_n,In=De.current,ue(De,e),ue(Xe,Xe.current),!0}function Pf(e,t,i){var o=e.stateNode;if(!o)throw Error(I(169));i?(e=dd(e,t,In),o.__reactInternalMemoizedMergedChildContext=e,fe(Xe),fe(De),ue(De,e)):fe(Xe),ue(Xe,i)}var Dt=null,fs=!1,Sa=!1;function pd(e){Dt===null?Dt=[e]:Dt.push(e)}function tg(e){fs=!0,pd(e)}function yn(){if(!Sa&&Dt!==null){Sa=!0;var e=0,t=oe;try{var i=Dt;for(oe=1;e>=c,a-=c,Ft=1<<32-xt(t)+a|i<W?(re=U,U=null):re=U.sibling;var X=P(g,U,y[W],T);if(X===null){U===null&&(U=re);break}e&&U&&X.alternate===null&&t(g,U),_=l(X,_,W),F===null?B=X:F.sibling=X,F=X,U=re}if(W===y.length)return i(g,U),he&&Cn(g,W),B;if(U===null){for(;WW?(re=U,U=null):re=U.sibling;var ae=P(g,U,X.value,T);if(ae===null){U===null&&(U=re);break}e&&U&&ae.alternate===null&&t(g,U),_=l(ae,_,W),F===null?B=ae:F.sibling=ae,F=ae,U=re}if(X.done)return i(g,U),he&&Cn(g,W),B;if(U===null){for(;!X.done;W++,X=y.next())X=w(g,X.value,T),X!==null&&(_=l(X,_,W),F===null?B=X:F.sibling=X,F=X);return he&&Cn(g,W),B}for(U=o(g,U);!X.done;W++,X=y.next())X=C(U,g,W,X.value,T),X!==null&&(e&&X.alternate!==null&&U.delete(X.key===null?W:X.key),_=l(X,_,W),F===null?B=X:F.sibling=X,F=X);return e&&U.forEach(function(Ce){return t(g,Ce)}),he&&Cn(g,W),B}function j(g,_,y,T){if(typeof y=="object"&&y!==null&&y.type===$n&&y.key===null&&(y=y.props.children),typeof y=="object"&&y!==null){switch(y.$$typeof){case io:e:{for(var B=y.key,F=_;F!==null;){if(F.key===B){if(B=y.type,B===$n){if(F.tag===7){i(g,F.sibling),_=a(F,y.props.children),_.return=g,g=_;break e}}else if(F.elementType===B||typeof B=="object"&&B!==null&&B.$$typeof===Jt&&Tf(B)===F.type){i(g,F.sibling),_=a(F,y.props),_.ref=Ki(g,F,y),_.return=g,g=_;break e}i(g,F);break}else t(g,F);F=F.sibling}y.type===$n?(_=On(y.props.children,g.mode,T,y.key),_.return=g,g=_):(T=zo(y.type,y.key,y.props,null,g.mode,T),T.ref=Ki(g,_,y),T.return=g,g=T)}return c(g);case Jn:e:{for(F=y.key;_!==null;){if(_.key===F)if(_.tag===4&&_.stateNode.containerInfo===y.containerInfo&&_.stateNode.implementation===y.implementation){i(g,_.sibling),_=a(_,y.children||[]),_.return=g,g=_;break e}else{i(g,_);break}else t(g,_);_=_.sibling}_=za(y,g.mode,T),_.return=g,g=_}return c(g);case Jt:return F=y._init,j(g,_,F(y._payload),T)}if(qi(y))return A(g,_,y,T);if(Wi(y))return E(g,_,y,T);mo(g,y)}return typeof y=="string"&&y!==""||typeof y=="number"?(y=""+y,_!==null&&_.tag===6?(i(g,_.sibling),_=a(_,y),_.return=g,g=_):(i(g,_),_=Ma(y,g.mode,T),_.return=g,g=_),c(g)):i(g,_)}return j}var yi=Pd(!0),Sd=Pd(!1),Rr={},Nt=gn(Rr),Pr=gn(Rr),Sr=gn(Rr);function zn(e){if(e===Rr)throw Error(I(174));return e}function au(e,t){switch(ue(Sr,t),ue(Pr,e),ue(Nt,Rr),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Ha(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Ha(t,e)}fe(Nt),ue(Nt,t)}function wi(){fe(Nt),fe(Pr),fe(Sr)}function kd(e){zn(Sr.current);var t=zn(Nt.current),i=Ha(t,e.type);t!==i&&(ue(Pr,e),ue(Nt,i))}function lu(e){Pr.current===e&&(fe(Nt),fe(Pr))}var pe=gn(0);function Go(e){for(var t=e;t!==null;){if(t.tag===13){var i=t.memoizedState;if(i!==null&&(i=i.dehydrated,i===null||i.data==="$?"||i.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var ka=[];function uu(){for(var e=0;ei?i:4,e(!0);var o=La.transition;La.transition={};try{e(!1),t()}finally{oe=i,La.transition=o}}function Fd(){return pt().memoizedState}function og(e,t,i){var o=hn(e);if(i={lane:o,action:i,hasEagerState:!1,eagerState:null,next:null},Ud(e))Wd(t,i);else if(i=gd(e,t,i,o),i!==null){var a=We();Pt(i,e,o,a),Hd(i,t,o)}}function sg(e,t,i){var o=hn(e),a={lane:o,action:i,hasEagerState:!1,eagerState:null,next:null};if(Ud(e))Wd(t,a);else{var l=e.alternate;if(e.lanes===0&&(l===null||l.lanes===0)&&(l=t.lastRenderedReducer,l!==null))try{var c=t.lastRenderedState,d=l(c,i);if(a.hasEagerState=!0,a.eagerState=d,St(d,c)){var p=t.interleaved;p===null?(a.next=a,ou(t)):(a.next=p.next,p.next=a),t.interleaved=a;return}}catch{}finally{}i=gd(e,t,a,o),i!==null&&(a=We(),Pt(i,e,o,a),Hd(i,t,o))}}function Ud(e){var t=e.alternate;return e===me||t!==null&&t===me}function Wd(e,t){or=Xo=!0;var i=e.pending;i===null?t.next=t:(t.next=i.next,i.next=t),e.pending=t}function Hd(e,t,i){if(i&4194240){var o=t.lanes;o&=e.pendingLanes,i|=o,t.lanes=i,Ql(e,i)}}var Yo={readContext:dt,useCallback:Be,useContext:Be,useEffect:Be,useImperativeHandle:Be,useInsertionEffect:Be,useLayoutEffect:Be,useMemo:Be,useReducer:Be,useRef:Be,useState:Be,useDebugValue:Be,useDeferredValue:Be,useTransition:Be,useMutableSource:Be,useSyncExternalStore:Be,useId:Be,unstable_isNewReconciler:!1},ag={readContext:dt,useCallback:function(e,t){return Tt().memoizedState=[e,t===void 0?null:t],e},useContext:dt,useEffect:zf,useImperativeHandle:function(e,t,i){return i=i!=null?i.concat([e]):null,Co(4194308,4,Rd.bind(null,t,e),i)},useLayoutEffect:function(e,t){return Co(4194308,4,e,t)},useInsertionEffect:function(e,t){return Co(4,2,e,t)},useMemo:function(e,t){var i=Tt();return t=t===void 0?null:t,e=e(),i.memoizedState=[e,t],e},useReducer:function(e,t,i){var o=Tt();return t=i!==void 0?i(t):t,o.memoizedState=o.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},o.queue=e,e=e.dispatch=og.bind(null,me,e),[o.memoizedState,e]},useRef:function(e){var t=Tt();return e={current:e},t.memoizedState=e},useState:Mf,useDebugValue:pu,useDeferredValue:function(e){return Tt().memoizedState=e},useTransition:function(){var e=Mf(!1),t=e[0];return e=rg.bind(null,e[1]),Tt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,i){var o=me,a=Tt();if(he){if(i===void 0)throw Error(I(407));i=i()}else{if(i=t(),Me===null)throw Error(I(349));Bn&30||Cd(o,t,i)}a.memoizedState=i;var l={value:i,getSnapshot:t};return a.queue=l,zf(Td.bind(null,o,l,e),[e]),o.flags|=2048,Er(9,Ad.bind(null,o,l,i,t),void 0,null),i},useId:function(){var e=Tt(),t=Me.identifierPrefix;if(he){var i=Ut,o=Ft;i=(o&~(1<<32-xt(o)-1)).toString(32)+i,t=":"+t+"R"+i,i=kr++,0<\/script>",e=e.removeChild(e.firstChild)):typeof o.is=="string"?e=c.createElement(i,{is:o.is}):(e=c.createElement(i),i==="select"&&(c=e,o.multiple?c.multiple=!0:o.size&&(c.size=o.size))):e=c.createElementNS(e,i),e[Mt]=t,e[xr]=o,Jd(e,t,!1,!1),t.stateNode=e;e:{switch(c=Qa(i,o),i){case"dialog":ce("cancel",e),ce("close",e),a=o;break;case"iframe":case"object":case"embed":ce("load",e),a=o;break;case"video":case"audio":for(a=0;a<$i.length;a++)ce($i[a],e);a=o;break;case"source":ce("error",e),a=o;break;case"img":case"image":case"link":ce("error",e),ce("load",e),a=o;break;case"details":ce("toggle",e),a=o;break;case"input":Kc(e,o),a=Da(e,o),ce("invalid",e);break;case"option":a=o;break;case"select":e._wrapperState={wasMultiple:!!o.multiple},a=_e({},o,{value:void 0}),ce("invalid",e);break;case"textarea":Xc(e,o),a=Wa(e,o),ce("invalid",e);break;default:a=o}Va(i,a),d=a;for(l in d)if(d.hasOwnProperty(l)){var p=d[l];l==="style"?Mh(e,p):l==="dangerouslySetInnerHTML"?(p=p?p.__html:void 0,p!=null&&Ah(e,p)):l==="children"?typeof p=="string"?(i!=="textarea"||p!=="")&&hr(e,p):typeof p=="number"&&hr(e,""+p):l!=="suppressContentEditableWarning"&&l!=="suppressHydrationWarning"&&l!=="autoFocus"&&(fr.hasOwnProperty(l)?p!=null&&l==="onScroll"&&ce("scroll",e):p!=null&&Dl(e,l,p,c))}switch(i){case"input":ro(e),Gc(e,o,!1);break;case"textarea":ro(e),Yc(e);break;case"option":o.value!=null&&e.setAttribute("value",""+mn(o.value));break;case"select":e.multiple=!!o.multiple,l=o.value,l!=null?ci(e,!!o.multiple,l,!1):o.defaultValue!=null&&ci(e,!!o.multiple,o.defaultValue,!0);break;default:typeof a.onClick=="function"&&(e.onclick=Fo)}switch(i){case"button":case"input":case"select":case"textarea":o=!!o.autoFocus;break e;case"img":o=!0;break e;default:o=!1}}o&&(t.flags|=4)}t.ref!==null&&(t.flags|=512,t.flags|=2097152)}return je(t),null;case 6:if(e&&t.stateNode!=null)ep(e,t,e.memoizedProps,o);else{if(typeof o!="string"&&t.stateNode===null)throw Error(I(166));if(i=zn(Sr.current),zn(Nt.current),po(t)){if(o=t.stateNode,i=t.memoizedProps,o[Mt]=t,(l=o.nodeValue!==i)&&(e=et,e!==null))switch(e.tag){case 3:ho(o.nodeValue,i,(e.mode&1)!==0);break;case 5:e.memoizedProps.suppressHydrationWarning!==!0&&ho(o.nodeValue,i,(e.mode&1)!==0)}l&&(t.flags|=4)}else o=(i.nodeType===9?i:i.ownerDocument).createTextNode(o),o[Mt]=t,t.stateNode=o}return je(t),null;case 13:if(fe(pe),o=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(he&&$e!==null&&t.mode&1&&!(t.flags&128))vd(),gi(),t.flags|=98560,l=!1;else if(l=po(t),o!==null&&o.dehydrated!==null){if(e===null){if(!l)throw Error(I(318));if(l=t.memoizedState,l=l!==null?l.dehydrated:null,!l)throw Error(I(317));l[Mt]=t}else gi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;je(t),l=!1}else wt!==null&&(Ll(wt),wt=null),l=!0;if(!l)return t.flags&65536?t:null}return t.flags&128?(t.lanes=i,t):(o=o!==null,o!==(e!==null&&e.memoizedState!==null)&&o&&(t.child.flags|=8192,t.mode&1&&(e===null||pe.current&1?Ee===0&&(Ee=3):xu())),t.updateQueue!==null&&(t.flags|=4),je(t),null);case 4:return wi(),vl(e,t),e===null&&yr(t.stateNode.containerInfo),je(t),null;case 10:return ru(t.type._context),je(t),null;case 17:return Ye(t.type)&&Uo(),je(t),null;case 19:if(fe(pe),l=t.memoizedState,l===null)return je(t),null;if(o=(t.flags&128)!==0,c=l.rendering,c===null)if(o)Gi(l,!1);else{if(Ee!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(c=Go(e),c!==null){for(t.flags|=128,Gi(l,!1),o=c.updateQueue,o!==null&&(t.updateQueue=o,t.flags|=4),t.subtreeFlags=0,o=i,i=t.child;i!==null;)l=i,e=o,l.flags&=14680066,c=l.alternate,c===null?(l.childLanes=0,l.lanes=e,l.child=null,l.subtreeFlags=0,l.memoizedProps=null,l.memoizedState=null,l.updateQueue=null,l.dependencies=null,l.stateNode=null):(l.childLanes=c.childLanes,l.lanes=c.lanes,l.child=c.child,l.subtreeFlags=0,l.deletions=null,l.memoizedProps=c.memoizedProps,l.memoizedState=c.memoizedState,l.updateQueue=c.updateQueue,l.type=c.type,e=c.dependencies,l.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext}),i=i.sibling;return ue(pe,pe.current&1|2),t.child}e=e.sibling}l.tail!==null&&we()>Pi&&(t.flags|=128,o=!0,Gi(l,!1),t.lanes=4194304)}else{if(!o)if(e=Go(c),e!==null){if(t.flags|=128,o=!0,i=e.updateQueue,i!==null&&(t.updateQueue=i,t.flags|=4),Gi(l,!0),l.tail===null&&l.tailMode==="hidden"&&!c.alternate&&!he)return je(t),null}else 2*we()-l.renderingStartTime>Pi&&i!==1073741824&&(t.flags|=128,o=!0,Gi(l,!1),t.lanes=4194304);l.isBackwards?(c.sibling=t.child,t.child=c):(i=l.last,i!==null?i.sibling=c:t.child=c,l.last=c)}return l.tail!==null?(t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=we(),t.sibling=null,i=pe.current,ue(pe,o?i&1|2:i&1),t):(je(t),null);case 22:case 23:return wu(),o=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==o&&(t.flags|=8192),o&&t.mode&1?Je&1073741824&&(je(t),t.subtreeFlags&6&&(t.flags|=8192)):je(t),null;case 24:return null;case 25:return null}throw Error(I(156,t.tag))}function mg(e,t){switch(eu(t),t.tag){case 1:return Ye(t.type)&&Uo(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return wi(),fe(Xe),fe(De),uu(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return lu(t),null;case 13:if(fe(pe),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(I(340));gi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return fe(pe),null;case 4:return wi(),null;case 10:return ru(t.type._context),null;case 22:case 23:return wu(),null;case 24:return null;default:return null}}var vo=!1,Ze=!1,_g=typeof WeakSet=="function"?WeakSet:Set,D=null;function li(e,t){var i=e.ref;if(i!==null)if(typeof i=="function")try{i(null)}catch(o){ve(e,t,o)}else i.current=null}function gl(e,t,i){try{i()}catch(o){ve(e,t,o)}}var Ff=!1;function vg(e,t){if(tl=jo,e=rd(),Jl(e)){if("selectionStart"in e)var i={start:e.selectionStart,end:e.selectionEnd};else e:{i=(i=e.ownerDocument)&&i.defaultView||window;var o=i.getSelection&&i.getSelection();if(o&&o.rangeCount!==0){i=o.anchorNode;var a=o.anchorOffset,l=o.focusNode;o=o.focusOffset;try{i.nodeType,l.nodeType}catch{i=null;break e}var c=0,d=-1,p=-1,m=0,x=0,w=e,P=null;t:for(;;){for(var C;w!==i||a!==0&&w.nodeType!==3||(d=c+a),w!==l||o!==0&&w.nodeType!==3||(p=c+o),w.nodeType===3&&(c+=w.nodeValue.length),(C=w.firstChild)!==null;)P=w,w=C;for(;;){if(w===e)break t;if(P===i&&++m===a&&(d=c),P===l&&++x===o&&(p=c),(C=w.nextSibling)!==null)break;w=P,P=w.parentNode}w=C}i=d===-1||p===-1?null:{start:d,end:p}}else i=null}i=i||{start:0,end:0}}else i=null;for(nl={focusedElem:e,selectionRange:i},jo=!1,D=t;D!==null;)if(t=D,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,D=e;else for(;D!==null;){t=D;try{var A=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(A!==null){var E=A.memoizedProps,j=A.memoizedState,g=t.stateNode,_=g.getSnapshotBeforeUpdate(t.elementType===t.type?E:gt(t.type,E),j);g.__reactInternalSnapshotBeforeUpdate=_}break;case 3:var y=t.stateNode.containerInfo;y.nodeType===1?y.textContent="":y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(I(163))}}catch(T){ve(t,t.return,T)}if(e=t.sibling,e!==null){e.return=t.return,D=e;break}D=t.return}return A=Ff,Ff=!1,A}function sr(e,t,i){var o=t.updateQueue;if(o=o!==null?o.lastEffect:null,o!==null){var a=o=o.next;do{if((a.tag&e)===e){var l=a.destroy;a.destroy=void 0,l!==void 0&&gl(t,i,l)}a=a.next}while(a!==o)}}function ps(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var i=t=t.next;do{if((i.tag&e)===e){var o=i.create;i.destroy=o()}i=i.next}while(i!==t)}}function yl(e){var t=e.ref;if(t!==null){var i=e.stateNode;switch(e.tag){case 5:e=i;break;default:e=i}typeof t=="function"?t(e):t.current=e}}function tp(e){var t=e.alternate;t!==null&&(e.alternate=null,tp(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Mt],delete t[xr],delete t[ol],delete t[$v],delete t[eg])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function np(e){return e.tag===5||e.tag===3||e.tag===4}function Uf(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||np(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function wl(e,t,i){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?i.nodeType===8?i.parentNode.insertBefore(e,t):i.insertBefore(e,t):(i.nodeType===8?(t=i.parentNode,t.insertBefore(e,i)):(t=i,t.appendChild(e)),i=i._reactRootContainer,i!=null||t.onclick!==null||(t.onclick=Fo));else if(o!==4&&(e=e.child,e!==null))for(wl(e,t,i),e=e.sibling;e!==null;)wl(e,t,i),e=e.sibling}function xl(e,t,i){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?i.insertBefore(e,t):i.appendChild(e);else if(o!==4&&(e=e.child,e!==null))for(xl(e,t,i),e=e.sibling;e!==null;)xl(e,t,i),e=e.sibling}var Oe=null,yt=!1;function qt(e,t,i){for(i=i.child;i!==null;)ip(e,t,i),i=i.sibling}function ip(e,t,i){if(zt&&typeof zt.onCommitFiberUnmount=="function")try{zt.onCommitFiberUnmount(ss,i)}catch{}switch(i.tag){case 5:Ze||li(i,t);case 6:var o=Oe,a=yt;Oe=null,qt(e,t,i),Oe=o,yt=a,Oe!==null&&(yt?(e=Oe,i=i.stateNode,e.nodeType===8?e.parentNode.removeChild(i):e.removeChild(i)):Oe.removeChild(i.stateNode));break;case 18:Oe!==null&&(yt?(e=Oe,i=i.stateNode,e.nodeType===8?Pa(e.parentNode,i):e.nodeType===1&&Pa(e,i),_r(e)):Pa(Oe,i.stateNode));break;case 4:o=Oe,a=yt,Oe=i.stateNode.containerInfo,yt=!0,qt(e,t,i),Oe=o,yt=a;break;case 0:case 11:case 14:case 15:if(!Ze&&(o=i.updateQueue,o!==null&&(o=o.lastEffect,o!==null))){a=o=o.next;do{var l=a,c=l.destroy;l=l.tag,c!==void 0&&(l&2||l&4)&&gl(i,t,c),a=a.next}while(a!==o)}qt(e,t,i);break;case 1:if(!Ze&&(li(i,t),o=i.stateNode,typeof o.componentWillUnmount=="function"))try{o.props=i.memoizedProps,o.state=i.memoizedState,o.componentWillUnmount()}catch(d){ve(i,t,d)}qt(e,t,i);break;case 21:qt(e,t,i);break;case 22:i.mode&1?(Ze=(o=Ze)||i.memoizedState!==null,qt(e,t,i),Ze=o):qt(e,t,i);break;default:qt(e,t,i)}}function Wf(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var i=e.stateNode;i===null&&(i=e.stateNode=new _g),t.forEach(function(o){var a=Eg.bind(null,e,o);i.has(o)||(i.add(o),o.then(a,a))})}}function vt(e,t){var i=t.deletions;if(i!==null)for(var o=0;oa&&(a=c),o&=~l}if(o=a,o=we()-o,o=(120>o?120:480>o?480:1080>o?1080:1920>o?1920:3e3>o?3e3:4320>o?4320:1960*yg(o/1960))-o,10e?16:e,rn===null)var o=!1;else{if(e=rn,rn=null,$o=0,te&6)throw Error(I(331));var a=te;for(te|=4,D=e.current;D!==null;){var l=D,c=l.child;if(D.flags&16){var d=l.deletions;if(d!==null){for(var p=0;pwe()-gu?Nn(e,0):vu|=i),qe(e,t)}function fp(e,t){t===0&&(e.mode&1?(t=ao,ao<<=1,!(ao&130023424)&&(ao=4194304)):t=1);var i=We();e=Qt(e,t),e!==null&&(Nr(e,t,i),qe(e,i))}function Lg(e){var t=e.memoizedState,i=0;t!==null&&(i=t.retryLane),fp(e,i)}function Eg(e,t){var i=0;switch(e.tag){case 13:var o=e.stateNode,a=e.memoizedState;a!==null&&(i=a.retryLane);break;case 19:o=e.stateNode;break;default:throw Error(I(314))}o!==null&&o.delete(t),fp(e,i)}var hp;hp=function(e,t,i){if(e!==null)if(e.memoizedProps!==t.pendingProps||Xe.current)Ge=!0;else{if(!(e.lanes&i)&&!(t.flags&128))return Ge=!1,dg(e,t,i);Ge=!!(e.flags&131072)}else Ge=!1,he&&t.flags&1048576&&md(t,Vo,t.index);switch(t.lanes=0,t.tag){case 2:var o=t.type;Ao(e,t),e=t.pendingProps;var a=vi(t,De.current);pi(t,i),a=fu(null,t,o,e,a,i);var l=hu();return t.flags|=1,typeof a=="object"&&a!==null&&typeof a.render=="function"&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Ye(o)?(l=!0,Wo(t)):l=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,su(t),a.updater=hs,t.stateNode=a,a._reactInternals=t,fl(t,o,e,i),t=pl(null,t,o,!0,l,i)):(t.tag=0,he&&l&&$l(t),Ue(null,t,a,i),t=t.child),t;case 16:o=t.elementType;e:{switch(Ao(e,t),e=t.pendingProps,a=o._init,o=a(o._payload),t.type=o,a=t.tag=Ag(o),e=gt(o,e),a){case 0:t=dl(null,t,o,e,i);break e;case 1:t=jf(null,t,o,e,i);break e;case 11:t=Rf(null,t,o,e,i);break e;case 14:t=Bf(null,t,o,gt(o.type,e),i);break e}throw Error(I(306,o,""))}return t;case 0:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:gt(o,a),dl(e,t,o,a,i);case 1:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:gt(o,a),jf(e,t,o,a,i);case 3:e:{if(Xd(t),e===null)throw Error(I(387));o=t.pendingProps,l=t.memoizedState,a=l.element,yd(e,t),Ko(t,o,null,i);var c=t.memoizedState;if(o=c.element,l.isDehydrated)if(l={element:o,isDehydrated:!1,cache:c.cache,pendingSuspenseBoundaries:c.pendingSuspenseBoundaries,transitions:c.transitions},t.updateQueue.baseState=l,t.memoizedState=l,t.flags&256){a=xi(Error(I(423)),t),t=Zf(e,t,o,i,a);break e}else if(o!==a){a=xi(Error(I(424)),t),t=Zf(e,t,o,i,a);break e}else for($e=un(t.stateNode.containerInfo.firstChild),et=t,he=!0,wt=null,i=Sd(t,null,o,i),t.child=i;i;)i.flags=i.flags&-3|4096,i=i.sibling;else{if(gi(),o===a){t=bt(e,t,i);break e}Ue(e,t,o,i)}t=t.child}return t;case 5:return kd(t),e===null&&ll(t),o=t.type,a=t.pendingProps,l=e!==null?e.memoizedProps:null,c=a.children,il(o,a)?c=null:l!==null&&il(o,l)&&(t.flags|=32),Gd(e,t),Ue(e,t,c,i),t.child;case 6:return e===null&&ll(t),null;case 13:return Yd(e,t,i);case 4:return au(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=yi(t,null,o,i):Ue(e,t,o,i),t.child;case 11:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:gt(o,a),Rf(e,t,o,a,i);case 7:return Ue(e,t,t.pendingProps,i),t.child;case 8:return Ue(e,t,t.pendingProps.children,i),t.child;case 12:return Ue(e,t,t.pendingProps.children,i),t.child;case 10:e:{if(o=t.type._context,a=t.pendingProps,l=t.memoizedProps,c=a.value,ue(Qo,o._currentValue),o._currentValue=c,l!==null)if(St(l.value,c)){if(l.children===a.children&&!Xe.current){t=bt(e,t,i);break e}}else for(l=t.child,l!==null&&(l.return=t);l!==null;){var d=l.dependencies;if(d!==null){c=l.child;for(var p=d.firstContext;p!==null;){if(p.context===o){if(l.tag===1){p=Wt(-1,i&-i),p.tag=2;var m=l.updateQueue;if(m!==null){m=m.shared;var x=m.pending;x===null?p.next=p:(p.next=x.next,x.next=p),m.pending=p}}l.lanes|=i,p=l.alternate,p!==null&&(p.lanes|=i),ul(l.return,i,t),d.lanes|=i;break}p=p.next}}else if(l.tag===10)c=l.type===t.type?null:l.child;else if(l.tag===18){if(c=l.return,c===null)throw Error(I(341));c.lanes|=i,d=c.alternate,d!==null&&(d.lanes|=i),ul(c,i,t),c=l.sibling}else c=l.child;if(c!==null)c.return=l;else for(c=l;c!==null;){if(c===t){c=null;break}if(l=c.sibling,l!==null){l.return=c.return,c=l;break}c=c.return}l=c}Ue(e,t,a.children,i),t=t.child}return t;case 9:return a=t.type,o=t.pendingProps.children,pi(t,i),a=dt(a),o=o(a),t.flags|=1,Ue(e,t,o,i),t.child;case 14:return o=t.type,a=gt(o,t.pendingProps),a=gt(o.type,a),Bf(e,t,o,a,i);case 15:return bd(e,t,t.type,t.pendingProps,i);case 17:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:gt(o,a),Ao(e,t),t.tag=1,Ye(o)?(e=!0,Wo(t)):e=!1,pi(t,i),xd(t,o,a),fl(t,o,a,i),pl(null,t,o,!0,e,i);case 19:return qd(e,t,i);case 22:return Kd(e,t,i)}throw Error(I(156,t.tag))};function dp(e,t){return Dh(e,t)}function Cg(e,t,i,o){this.tag=e,this.key=i,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=o,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ft(e,t,i,o){return new Cg(e,t,i,o)}function Pu(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Ag(e){if(typeof e=="function")return Pu(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Ul)return 11;if(e===Wl)return 14}return 2}function dn(e,t){var i=e.alternate;return i===null?(i=ft(e.tag,t,e.key,e.mode),i.elementType=e.elementType,i.type=e.type,i.stateNode=e.stateNode,i.alternate=e,e.alternate=i):(i.pendingProps=t,i.type=e.type,i.flags=0,i.subtreeFlags=0,i.deletions=null),i.flags=e.flags&14680064,i.childLanes=e.childLanes,i.lanes=e.lanes,i.child=e.child,i.memoizedProps=e.memoizedProps,i.memoizedState=e.memoizedState,i.updateQueue=e.updateQueue,t=e.dependencies,i.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},i.sibling=e.sibling,i.index=e.index,i.ref=e.ref,i}function zo(e,t,i,o,a,l){var c=2;if(o=e,typeof e=="function")Pu(e)&&(c=1);else if(typeof e=="string")c=5;else e:switch(e){case $n:return On(i.children,a,l,t);case Fl:c=8,a|=8;break;case Ra:return e=ft(12,i,t,a|2),e.elementType=Ra,e.lanes=l,e;case Ba:return e=ft(13,i,t,a),e.elementType=Ba,e.lanes=l,e;case ja:return e=ft(19,i,t,a),e.elementType=ja,e.lanes=l,e;case Ph:return _s(i,a,l,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case wh:c=10;break e;case xh:c=9;break e;case Ul:c=11;break e;case Wl:c=14;break e;case Jt:c=16,o=null;break e}throw Error(I(130,e==null?e:typeof e,""))}return t=ft(c,i,t,a),t.elementType=e,t.type=o,t.lanes=l,t}function On(e,t,i,o){return e=ft(7,e,o,t),e.lanes=i,e}function _s(e,t,i,o){return e=ft(22,e,o,t),e.elementType=Ph,e.lanes=i,e.stateNode={isHidden:!1},e}function Ma(e,t,i){return e=ft(6,e,null,t),e.lanes=i,e}function za(e,t,i){return t=ft(4,e.children!==null?e.children:[],e.key,t),t.lanes=i,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Tg(e,t,i,o,a){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=fa(0),this.expirationTimes=fa(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=fa(0),this.identifierPrefix=o,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function Su(e,t,i,o,a,l,c,d,p){return e=new Tg(e,t,i,d,p),t===1?(t=1,l===!0&&(t|=8)):t=0,l=ft(3,null,null,t),e.current=l,l.stateNode=e,l.memoizedState={element:o,isDehydrated:i,cache:null,transitions:null,pendingSuspenseBoundaries:null},su(l),e}function Mg(e,t,i){var o=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(vp)}catch(e){console.error(e)}}vp(),mh.exports=nt;var gp=mh.exports,Yf=gp;Oa.createRoot=Yf.createRoot,Oa.hydrateRoot=Yf.hydrateRoot;/** + * @remix-run/router v1.14.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 Ar(){return Ar=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function Cu(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Bg(){return Math.random().toString(36).substr(2,8)}function Jf(e,t){return{usr:e.state,key:e.key,idx:t}}function El(e,t,i,o){return i===void 0&&(i=null),Ar({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?Ei(t):t,{state:i,key:t&&t.key||o||Bg()})}function ns(e){let{pathname:t="/",search:i="",hash:o=""}=e;return i&&i!=="?"&&(t+=i.charAt(0)==="?"?i:"?"+i),o&&o!=="#"&&(t+=o.charAt(0)==="#"?o:"#"+o),t}function Ei(e){let t={};if(e){let i=e.indexOf("#");i>=0&&(t.hash=e.substr(i),e=e.substr(0,i));let o=e.indexOf("?");o>=0&&(t.search=e.substr(o),e=e.substr(0,o)),e&&(t.pathname=e)}return t}function jg(e,t,i,o){o===void 0&&(o={});let{window:a=document.defaultView,v5Compat:l=!1}=o,c=a.history,d=on.Pop,p=null,m=x();m==null&&(m=0,c.replaceState(Ar({},c.state,{idx:m}),""));function x(){return(c.state||{idx:null}).idx}function w(){d=on.Pop;let j=x(),g=j==null?null:j-m;m=j,p&&p({action:d,location:E.location,delta:g})}function P(j,g){d=on.Push;let _=El(E.location,j,g);i&&i(_,j),m=x()+1;let y=Jf(_,m),T=E.createHref(_);try{c.pushState(y,"",T)}catch(B){if(B instanceof DOMException&&B.name==="DataCloneError")throw B;a.location.assign(T)}l&&p&&p({action:d,location:E.location,delta:1})}function C(j,g){d=on.Replace;let _=El(E.location,j,g);i&&i(_,j),m=x();let y=Jf(_,m),T=E.createHref(_);c.replaceState(y,"",T),l&&p&&p({action:d,location:E.location,delta:0})}function A(j){let g=a.location.origin!=="null"?a.location.origin:a.location.href,_=typeof j=="string"?j:ns(j);return ge(g,"No window.location.(origin|href) available to create URL for href: "+_),new URL(_,g)}let E={get action(){return d},get location(){return e(a,c)},listen(j){if(p)throw new Error("A history only accepts one active listener");return a.addEventListener(qf,w),p=j,()=>{a.removeEventListener(qf,w),p=null}},createHref(j){return t(a,j)},createURL:A,encodeLocation(j){let g=A(j);return{pathname:g.pathname,search:g.search,hash:g.hash}},push:P,replace:C,go(j){return c.go(j)}};return E}var $f;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})($f||($f={}));function Zg(e,t,i){i===void 0&&(i="/");let o=typeof t=="string"?Ei(t):t,a=Tr(o.pathname||"/",i);if(a==null)return null;let l=yp(e);Dg(l);let c=null;for(let d=0;c==null&&d{let p={relativePath:d===void 0?l.path||"":d,caseSensitive:l.caseSensitive===!0,childrenIndex:c,route:l};p.relativePath.startsWith("/")&&(ge(p.relativePath.startsWith(o),'Absolute route path "'+p.relativePath+'" nested under path '+('"'+o+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),p.relativePath=p.relativePath.slice(o.length));let m=pn([o,p.relativePath]),x=i.concat(p);l.children&&l.children.length>0&&(ge(l.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+m+'".')),yp(l.children,t,x,m)),!(l.path==null&&!l.index)&&t.push({path:m,score:bg(m,l.index),routesMeta:x})};return e.forEach((l,c)=>{var d;if(l.path===""||!((d=l.path)!=null&&d.includes("?")))a(l,c);else for(let p of wp(l.path))a(l,c,p)}),t}function wp(e){let t=e.split("/");if(t.length===0)return[];let[i,...o]=t,a=i.endsWith("?"),l=i.replace(/\?$/,"");if(o.length===0)return a?[l,""]:[l];let c=wp(o.join("/")),d=[];return d.push(...c.map(p=>p===""?l:[l,p].join("/"))),a&&d.push(...c),d.map(p=>e.startsWith("/")&&p===""?"/":p)}function Dg(e){e.sort((t,i)=>t.score!==i.score?i.score-t.score:Kg(t.routesMeta.map(o=>o.childrenIndex),i.routesMeta.map(o=>o.childrenIndex)))}const Fg=/^:[\w-]+$/,Ug=3,Wg=2,Hg=1,Vg=10,Qg=-2,eh=e=>e==="*";function bg(e,t){let i=e.split("/"),o=i.length;return i.some(eh)&&(o+=Qg),t&&(o+=Wg),i.filter(a=>!eh(a)).reduce((a,l)=>a+(Fg.test(l)?Ug:l===""?Hg:Vg),o)}function Kg(e,t){return e.length===t.length&&e.slice(0,-1).every((o,a)=>o===t[a])?e[e.length-1]-t[t.length-1]:0}function Gg(e,t){let{routesMeta:i}=e,o={},a="/",l=[];for(let c=0;c{let{paramName:P,isOptional:C}=x;if(P==="*"){let E=d[w]||"";c=l.slice(0,l.length-E.length).replace(/(.)\/+$/,"$1")}const A=d[w];return C&&!A?m[P]=void 0:m[P]=qg(A||"",P),m},{}),pathname:l,pathnameBase:c,pattern:e}}function Xg(e,t,i){t===void 0&&(t=!1),i===void 0&&(i=!0),Cu(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let o=[],a="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(c,d,p)=>(o.push({paramName:d,isOptional:p!=null}),p?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(o.push({paramName:"*"}),a+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):i?a+="\\/*$":e!==""&&e!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),o]}function Yg(e){try{return decodeURI(e)}catch(t){return Cu(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function qg(e,t){try{return decodeURIComponent(e)}catch(i){return Cu(!1,'The value for the URL param "'+t+'" will not be decoded because'+(' the string "'+e+'" is a malformed URL segment. This is probably')+(" due to a bad percent encoding ("+i+").")),e}}function Tr(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let i=t.endsWith("/")?t.length-1:t.length,o=e.charAt(i);return o&&o!=="/"?null:e.slice(i)||"/"}function Jg(e,t){t===void 0&&(t="/");let{pathname:i,search:o="",hash:a=""}=typeof e=="string"?Ei(e):e;return{pathname:i?i.startsWith("/")?i:$g(i,t):t,search:ny(o),hash:iy(a)}}function $g(e,t){let i=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(a=>{a===".."?i.length>1&&i.pop():a!=="."&&i.push(a)}),i.length>1?i.join("/"):"/"}function Na(e,t,i,o){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(o)+"]. Please separate it out to the ")+("`to."+i+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function ey(e){return e.filter((t,i)=>i===0||t.route.path&&t.route.path.length>0)}function xp(e,t){let i=ey(e);return t?i.map((o,a)=>a===e.length-1?o.pathname:o.pathnameBase):i.map(o=>o.pathnameBase)}function Pp(e,t,i,o){o===void 0&&(o=!1);let a;typeof e=="string"?a=Ei(e):(a=Ar({},e),ge(!a.pathname||!a.pathname.includes("?"),Na("?","pathname","search",a)),ge(!a.pathname||!a.pathname.includes("#"),Na("#","pathname","hash",a)),ge(!a.search||!a.search.includes("#"),Na("#","search","hash",a)));let l=e===""||a.pathname==="",c=l?"/":a.pathname,d;if(c==null)d=i;else{let w=t.length-1;if(!o&&c.startsWith("..")){let P=c.split("/");for(;P[0]==="..";)P.shift(),w-=1;a.pathname=P.join("/")}d=w>=0?t[w]:"/"}let p=Jg(a,d),m=c&&c!=="/"&&c.endsWith("/"),x=(l||c===".")&&i.endsWith("/");return!p.pathname.endsWith("/")&&(m||x)&&(p.pathname+="/"),p}const pn=e=>e.join("/").replace(/\/\/+/g,"/"),ty=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),ny=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,iy=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function ry(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Sp=["post","put","patch","delete"];new Set(Sp);const oy=["get",...Sp];new Set(oy);/** + * React Router v6.21.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 Mr(){return Mr=Object.assign?Object.assign.bind():function(e){for(var t=1;t{d.current=!0}),O.useCallback(function(m,x){if(x===void 0&&(x={}),!d.current)return;if(typeof m=="number"){o.go(m);return}let w=Pp(m,JSON.parse(c),l,x.relative==="path");e==null&&t!=="/"&&(w.pathname=w.pathname==="/"?t:pn([t,w.pathname])),(x.replace?o.replace:o.push)(w,x.state,x)},[t,o,c,l,e])}function Ss(e,t){let{relative:i}=t===void 0?{}:t,{future:o}=O.useContext(wn),{matches:a}=O.useContext(Un),{pathname:l}=Ci(),c=JSON.stringify(xp(a,o.v7_relativeSplatPath));return O.useMemo(()=>Pp(e,JSON.parse(c),l,i==="path"),[e,c,l,i])}function uy(e,t){return cy(e,t)}function cy(e,t,i,o){Br()||ge(!1);let{navigator:a}=O.useContext(wn),{matches:l}=O.useContext(Un),c=l[l.length-1],d=c?c.params:{};c&&c.pathname;let p=c?c.pathnameBase:"/";c&&c.route;let m=Ci(),x;if(t){var w;let j=typeof t=="string"?Ei(t):t;p==="/"||(w=j.pathname)!=null&&w.startsWith(p)||ge(!1),x=j}else x=m;let P=x.pathname||"/",C=p==="/"?P:P.slice(p.length)||"/",A=Zg(e,{pathname:C}),E=my(A&&A.map(j=>Object.assign({},j,{params:Object.assign({},d,j.params),pathname:pn([p,a.encodeLocation?a.encodeLocation(j.pathname).pathname:j.pathname]),pathnameBase:j.pathnameBase==="/"?p:pn([p,a.encodeLocation?a.encodeLocation(j.pathnameBase).pathname:j.pathnameBase])})),l,i,o);return t&&E?O.createElement(Ps.Provider,{value:{location:Mr({pathname:"/",search:"",hash:"",state:null,key:"default"},x),navigationType:on.Pop}},E):E}function fy(){let e=yy(),t=ry(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),i=e instanceof Error?e.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return O.createElement(O.Fragment,null,O.createElement("h2",null,"Unexpected Application Error!"),O.createElement("h3",{style:{fontStyle:"italic"}},t),i?O.createElement("pre",{style:a},i):null,null)}const hy=O.createElement(fy,null);class dy extends O.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,i){return i.location!==t.location||i.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:i.error,location:i.location,revalidation:t.revalidation||i.revalidation}}componentDidCatch(t,i){console.error("React Router caught the following error during render",t,i)}render(){return this.state.error!==void 0?O.createElement(Un.Provider,{value:this.props.routeContext},O.createElement(Lp.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function py(e){let{routeContext:t,match:i,children:o}=e,a=O.useContext(xs);return a&&a.static&&a.staticContext&&(i.route.errorElement||i.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=i.route.id),O.createElement(Un.Provider,{value:t},o)}function my(e,t,i,o){var a;if(t===void 0&&(t=[]),i===void 0&&(i=null),o===void 0&&(o=null),e==null){var l;if((l=i)!=null&&l.errors)e=i.matches;else return null}let c=e,d=(a=i)==null?void 0:a.errors;if(d!=null){let x=c.findIndex(w=>w.route.id&&(d==null?void 0:d[w.route.id]));x>=0||ge(!1),c=c.slice(0,Math.min(c.length,x+1))}let p=!1,m=-1;if(i&&o&&o.v7_partialHydration)for(let x=0;x=0?c=c.slice(0,m+1):c=[c[0]];break}}}return c.reduceRight((x,w,P)=>{let C,A=!1,E=null,j=null;i&&(C=d&&w.route.id?d[w.route.id]:void 0,E=w.route.errorElement||hy,p&&(m<0&&P===0?(xy("route-fallback",!1),A=!0,j=null):m===P&&(A=!0,j=w.route.hydrateFallbackElement||null)));let g=t.concat(c.slice(0,P+1)),_=()=>{let y;return C?y=E:A?y=j:w.route.Component?y=O.createElement(w.route.Component,null):w.route.element?y=w.route.element:y=x,O.createElement(py,{match:w,routeContext:{outlet:x,matches:g,isDataRoute:i!=null},children:y})};return i&&(w.route.ErrorBoundary||w.route.errorElement||P===0)?O.createElement(dy,{location:i.location,revalidation:i.revalidation,component:E,error:C,children:_(),routeContext:{outlet:null,matches:g,isDataRoute:!0}}):_()},null)}var Cp=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(Cp||{}),is=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(is||{});function _y(e){let t=O.useContext(xs);return t||ge(!1),t}function vy(e){let t=O.useContext(kp);return t||ge(!1),t}function gy(e){let t=O.useContext(Un);return t||ge(!1),t}function Ap(e){let t=gy(),i=t.matches[t.matches.length-1];return i.route.id||ge(!1),i.route.id}function yy(){var e;let t=O.useContext(Lp),i=vy(is.UseRouteError),o=Ap(is.UseRouteError);return t!==void 0?t:(e=i.errors)==null?void 0:e[o]}function wy(){let{router:e}=_y(Cp.UseNavigateStable),t=Ap(is.UseNavigateStable),i=O.useRef(!1);return Ep(()=>{i.current=!0}),O.useCallback(function(a,l){l===void 0&&(l={}),i.current&&(typeof a=="number"?e.navigate(a):e.navigate(a,Mr({fromRouteId:t},l)))},[e,t])}const th={};function xy(e,t,i){!t&&!th[e]&&(th[e]=!0)}function Al(e){ge(!1)}function Py(e){let{basename:t="/",children:i=null,location:o,navigationType:a=on.Pop,navigator:l,static:c=!1,future:d}=e;Br()&&ge(!1);let p=t.replace(/^\/*/,"/"),m=O.useMemo(()=>({basename:p,navigator:l,static:c,future:Mr({v7_relativeSplatPath:!1},d)}),[p,d,l,c]);typeof o=="string"&&(o=Ei(o));let{pathname:x="/",search:w="",hash:P="",state:C=null,key:A="default"}=o,E=O.useMemo(()=>{let j=Tr(x,p);return j==null?null:{location:{pathname:j,search:w,hash:P,state:C,key:A},navigationType:a}},[p,x,w,P,C,A,a]);return E==null?null:O.createElement(wn.Provider,{value:m},O.createElement(Ps.Provider,{children:i,value:E}))}function Sy(e){let{children:t,location:i}=e;return uy(Tl(t),i)}new Promise(()=>{});function Tl(e,t){t===void 0&&(t=[]);let i=[];return O.Children.forEach(e,(o,a)=>{if(!O.isValidElement(o))return;let l=[...t,a];if(o.type===O.Fragment){i.push.apply(i,Tl(o.props.children,l));return}o.type!==Al&&ge(!1),!o.props.index||!o.props.children||ge(!1);let c={id:o.props.id||l.join("-"),caseSensitive:o.props.caseSensitive,element:o.props.element,Component:o.props.Component,index:o.props.index,path:o.props.path,loader:o.props.loader,action:o.props.action,errorElement:o.props.errorElement,ErrorBoundary:o.props.ErrorBoundary,hasErrorBoundary:o.props.ErrorBoundary!=null||o.props.errorElement!=null,shouldRevalidate:o.props.shouldRevalidate,handle:o.props.handle,lazy:o.props.lazy};o.props.children&&(c.children=Tl(o.props.children,l)),i.push(c)}),i}/** + * React Router DOM v6.21.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 rs(){return rs=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(i[a]=e[a]);return i}function ky(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Ly(e,t){return e.button===0&&(!t||t==="_self")&&!ky(e)}const Ey=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","unstable_viewTransition"],Cy=["aria-current","caseSensitive","className","end","style","to","unstable_viewTransition","children"],Ay=O.createContext({isTransitioning:!1}),Ty="startTransition",nh=L_[Ty];function My(e){let{basename:t,children:i,future:o,window:a}=e,l=O.useRef();l.current==null&&(l.current=Rg({window:a,v5Compat:!0}));let c=l.current,[d,p]=O.useState({action:c.action,location:c.location}),{v7_startTransition:m}=o||{},x=O.useCallback(w=>{m&&nh?nh(()=>p(w)):p(w)},[p,m]);return O.useLayoutEffect(()=>c.listen(x),[c,x]),O.createElement(Py,{basename:t,children:i,location:d.location,navigationType:d.action,navigator:c,future:o})}const zy=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Ny=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Oy=O.forwardRef(function(t,i){let{onClick:o,relative:a,reloadDocument:l,replace:c,state:d,target:p,to:m,preventScrollReset:x,unstable_viewTransition:w}=t,P=Tp(t,Ey),{basename:C}=O.useContext(wn),A,E=!1;if(typeof m=="string"&&Ny.test(m)&&(A=m,zy))try{let y=new URL(window.location.href),T=m.startsWith("//")?new URL(y.protocol+m):new URL(m),B=Tr(T.pathname,C);T.origin===y.origin&&B!=null?m=B+T.search+T.hash:E=!0}catch{}let j=sy(m,{relative:a}),g=Ry(m,{replace:c,state:d,target:p,preventScrollReset:x,relative:a,unstable_viewTransition:w});function _(y){o&&o(y),y.defaultPrevented||g(y)}return O.createElement("a",rs({},P,{href:A||j,onClick:E||l?o:_,ref:i,target:p}))}),ur=O.forwardRef(function(t,i){let{"aria-current":o="page",caseSensitive:a=!1,className:l="",end:c=!1,style:d,to:p,unstable_viewTransition:m,children:x}=t,w=Tp(t,Cy),P=Ss(p,{relative:w.relative}),C=Ci(),A=O.useContext(kp),{navigator:E}=O.useContext(wn),j=A!=null&&By(P)&&m===!0,g=E.encodeLocation?E.encodeLocation(P).pathname:P.pathname,_=C.pathname,y=A&&A.navigation&&A.navigation.location?A.navigation.location.pathname:null;a||(_=_.toLowerCase(),y=y?y.toLowerCase():null,g=g.toLowerCase());const T=g!=="/"&&g.endsWith("/")?g.length-1:g.length;let B=_===g||!c&&_.startsWith(g)&&_.charAt(T)==="/",F=y!=null&&(y===g||!c&&y.startsWith(g)&&y.charAt(g.length)==="/"),U={isActive:B,isPending:F,isTransitioning:j},W=B?o:void 0,re;typeof l=="function"?re=l(U):re=[l,B?"active":null,F?"pending":null,j?"transitioning":null].filter(Boolean).join(" ");let X=typeof d=="function"?d(U):d;return O.createElement(Oy,rs({},w,{"aria-current":W,className:re,ref:i,style:X,to:p,unstable_viewTransition:m}),typeof x=="function"?x(U):x)});var Ml;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(Ml||(Ml={}));var ih;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(ih||(ih={}));function Iy(e){let t=O.useContext(xs);return t||ge(!1),t}function Ry(e,t){let{target:i,replace:o,state:a,preventScrollReset:l,relative:c,unstable_viewTransition:d}=t===void 0?{}:t,p=ay(),m=Ci(),x=Ss(e,{relative:c});return O.useCallback(w=>{if(Ly(w,i)){w.preventDefault();let P=o!==void 0?o:ns(m)===ns(x);p(e,{replace:P,state:a,preventScrollReset:l,relative:c,unstable_viewTransition:d})}},[m,p,x,o,a,i,e,l,c,d])}function By(e,t){t===void 0&&(t={});let i=O.useContext(Ay);i==null&&ge(!1);let{basename:o}=Iy(Ml.useViewTransitionState),a=Ss(e,{relative:t.relative});if(!i.isTransitioning)return!1;let l=Tr(i.currentLocation.pathname,o)||i.currentLocation.pathname,c=Tr(i.nextLocation.pathname,o)||i.nextLocation.pathname;return Cl(a.pathname,c)!=null||Cl(a.pathname,l)!=null}function Mp(){const[e,t]=O.useState(!0),i=Ci();return console.log(i),O.useEffect(()=>{const o=()=>{window.innerWidth>=760?t(!1):t(!0)};return o(),window.addEventListener("resize",o),()=>{window.removeEventListener("resize",o)}},[]),N.jsxs("div",{className:"header",children:[N.jsx(ur,{to:"/",children:N.jsx("img",{className:"imgHeader",src:"../../img/mariuHeader.png",alt:"Forn Mariu"})}),e?N.jsx("label",{className:"labelMenu",onClick:()=>{t(!1)},children:N.jsx("img",{className:"menuIcon",src:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMwAAADACAMAAAB/Pny7AAAAYFBMVEUAAAD////s7OzV1dV4eHibm5uvr6/6+vrOzs7v7+/g4OD19fUMDAwcHBxtbW2QkJDm5uZ+fn6Hh4ciIiIyMjKpqakXFxdbW1vIyMi5ublBQUFgYGBTU1NnZ2e/v79ISEiN66FaAAAEA0lEQVR4nO2di7KiMAxAixUKLUpBEVAv9///cqksy0PdO3PtTJNMzhfkDNBH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eaEWMujPnRSzDIEft9WTTEugG/jUjjJYO4DWNPYhQ+KvrUIkTsaiP6U9crWDDIGvf6QeZJAtx95zj0QWOgZ/ZKILHYI/OkGgQXuiFETGMseV1mlA1MvlNTktGaT/A3rFgdYAQGpoJjVpklrORAR+DDjyTW0LsCOQAXCcdoOMIvJoavVIaJDYnt3HhAb6e+ccj7vnnIzC+o/DmYM7QDtmNPGf1a7MnGs22BPnZlnSwD2k1WpTbJJoR4Hzvwtb/wApRWjx1w2G7QAAAABJRU5ErkJggg==",alt:"menu"})}):N.jsxs(N.Fragment,{children:[N.jsx("label",{className:"labelMenu",onClick:()=>{t(!0)},children:N.jsx("img",{className:"menuIcon",src:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJwAAACUCAMAAABRNbASAAAAY1BMVEX///8AAADLy8tDQ0Px8fHFxcWxsbFlZWXc3Nz6+vrh4eG/v79qamr19fUsLCysrKw1NTVgYGCgoKDR0dEfHx8aGhqCgoImJiaKiopKSkp4eHg+Pj4JCQkUFBRaWlpQUFCYmJhhngRPAAADfUlEQVR4nO3c63KqMBQF4KC2gHfFa6u27/+UR7A9tZAFSWAle6bZP88cOt+skB3kEqXKyk+JqDrl6qfmoTX1mgu2Pem2oSW62j5sRWiHvooKNw7N0Ne4tM1CK1DN7l0kDY1AleZquguNQLWbyh3VclyFrQ3PdVLn0ARcZ7UPTcC1V5f6P63HgWpdl1xUw1uoQNVcqZq4USjcKOIiLuIiLuIiLuIiLuIC4haHTCwuf0uWU6G4/HA/8r2fjoXLH3f49r10JFyVW1njPjoOLn+6M9pDR8H9z62sHucdA7f4fUfZ/bwj4O495Hc5Zzc8blG3JcnSsRsPjmvkVuncshsap8mtrLVTdkPjiqsWl1xdsht8WNEzDJdZMfyEKI6AZ68jtJLmn3TNjtGEM/Cs4GI7KzS411qtJpZ/U43AbeW1ZXYa3ACVNe4rP+polx0Hp0ZgVhytsiPhVKbH2XVjFk4VS8CzyI6GUwU4797Ns+PhVIayM9YRcTA7447CxKkMzFnTbkzFqQKsFYZXn1ycysAV1NHoeRoZBzvKziQ7Ng6uZEuD7Og43I27s+Pj4JV790rmAefejX3gYL/ryk6Dexm8CvhWWfusMLlMJ1Z7Nw6MS3Zt2YXGJdeW7ILj2rpxeFxLR5GAgx1FAg52FBk40FFk4JJ0IRf3ob/jIQJ3y7U2EbiNdkxl4M6AJgGnnwsycGdwvknApS02TzjwC+zeQ/CY6nGEQlfCm/bDvOBege3WmpsfHMrt1nWgB9wKjWlHbj5wKLeP7kPpOJRbS+/1hoO5tfU3TziYm4mNjEO29t7rB4fGNDU8nolDuXX1Xh84xzXLC65PD2HjevReOg7lNjfqIVwcXOttbCTcILlpcWmtbtZv08AeYmejvB2BxnTefSgdN0APoeE+gc289/JwcC5Y50Z4C2y43AjJ6X9pWfYQFk47rk65UWZrMzvrHsLDNbLbOI0pCVfLzjU31uvfzzr73kvGPencc+N9cvCtc+shZNyXzvR3lmdcpeuVG/UDodeeuXE/rXrpl9vf/e4r4iIu4iIu4iIu4iLuL+Fmi0mQWjS3TGvuaCWnLkrs9nNJslNiN+4rf2mK3n9O6EaWZRVq2thZTUqVXxYduv9bmDoo/Cle8KoeJek/2g5eb9WyMRF51q2/3joVudXm7HvJRc9hAtbq54JgK2yFvTx2E/4HKldDDK/tm38AAAAASUVORK5CYII=",alt:"menu"})}),N.jsxs("ul",{className:"menu",children:[N.jsx("li",{children:N.jsx(ur,{className:i.pathname!=="/marielWebPage.github.io/panes"?"menuNav":"activated",to:"/panes",children:"Carta de panes"})}),N.jsx("li",{children:N.jsx(ur,{className:i.pathname!=="/marielWebPage.github.io"?"menuNav":"activated",to:"/",children:"Menu"})})]})]})]})}function zp(e,t){const i=O.useRef(t);O.useEffect(function(){t!==i.current&&e.attributionControl!=null&&(i.current!=null&&e.attributionControl.removeAttribution(i.current),t!=null&&e.attributionControl.addAttribution(t)),i.current=t},[e,t])}const jy=1;function Zy(e){return Object.freeze({__version:jy,map:e})}function Dy(e,t){return Object.freeze({...e,...t})}const Np=O.createContext(null),Op=Np.Provider;function Ip(){const e=O.useContext(Np);if(e==null)throw new Error("No context provided: useLeafletContext() can only be used in a descendant of ");return e}function Fy(e){function t(i,o){const{instance:a,context:l}=e(i).current;return O.useImperativeHandle(o,()=>a),i.children==null?null:cr.createElement(Op,{value:l},i.children)}return O.forwardRef(t)}function Uy(e){function t(i,o){const[a,l]=O.useState(!1),{instance:c}=e(i,l).current;O.useImperativeHandle(o,()=>c),O.useEffect(function(){a&&c.update()},[c,a,i.children]);const d=c._contentNode;return d?gp.createPortal(i.children,d):null}return O.forwardRef(t)}function Wy(e){function t(i,o){const{instance:a}=e(i).current;return O.useImperativeHandle(o,()=>a),null}return O.forwardRef(t)}function Rp(e,t){const i=O.useRef();O.useEffect(function(){return t!=null&&e.instance.on(t),i.current=t,function(){i.current!=null&&e.instance.off(i.current),i.current=null}},[e,t])}function Au(e,t){const i=e.pane??t.pane;return i?{...e,pane:i}:e}function Hy(e,t){return function(o,a){const l=Ip(),c=e(Au(o,l),l);return zp(l.map,o.attribution),Rp(c.current,o.eventHandlers),t(c.current,l,o,a),c}}var zl={exports:{}};/* @preserve + * Leaflet 1.9.4, a JS library for interactive maps. https://leafletjs.com + * (c) 2010-2023 Vladimir Agafonkin, (c) 2010-2011 CloudMade + */(function(e,t){(function(i,o){o(t)})(l_,function(i){var o="1.9.4";function a(n){var r,s,u,f;for(s=1,u=arguments.length;s"u"||!L||!L.Mixin)){n=y(n)?n:[n];for(var r=0;r0?Math.floor(n):Math.ceil(n)};M.prototype={clone:function(){return new M(this.x,this.y)},add:function(n){return this.clone()._add(R(n))},_add:function(n){return this.x+=n.x,this.y+=n.y,this},subtract:function(n){return this.clone()._subtract(R(n))},_subtract:function(n){return this.x-=n.x,this.y-=n.y,this},divideBy:function(n){return this.clone()._divideBy(n)},_divideBy:function(n){return this.x/=n,this.y/=n,this},multiplyBy:function(n){return this.clone()._multiplyBy(n)},_multiplyBy:function(n){return this.x*=n,this.y*=n,this},scaleBy:function(n){return new M(this.x*n.x,this.y*n.y)},unscaleBy:function(n){return new M(this.x/n.x,this.y/n.y)},round:function(){return this.clone()._round()},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},floor:function(){return this.clone()._floor()},_floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.clone()._ceil()},_ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},trunc:function(){return this.clone()._trunc()},_trunc:function(){return this.x=b(this.x),this.y=b(this.y),this},distanceTo:function(n){n=R(n);var r=n.x-this.x,s=n.y-this.y;return Math.sqrt(r*r+s*s)},equals:function(n){return n=R(n),n.x===this.x&&n.y===this.y},contains:function(n){return n=R(n),Math.abs(n.x)<=Math.abs(this.x)&&Math.abs(n.y)<=Math.abs(this.y)},toString:function(){return"Point("+P(this.x)+", "+P(this.y)+")"}};function R(n,r,s){return n instanceof M?n:y(n)?new M(n[0],n[1]):n==null?n:typeof n=="object"&&"x"in n&&"y"in n?new M(n.x,n.y):new M(n,r,s)}function Q(n,r){if(n)for(var s=r?[n,r]:n,u=0,f=s.length;u=this.min.x&&s.x<=this.max.x&&r.y>=this.min.y&&s.y<=this.max.y},intersects:function(n){n=ee(n);var r=this.min,s=this.max,u=n.min,f=n.max,h=f.x>=r.x&&u.x<=s.x,v=f.y>=r.y&&u.y<=s.y;return h&&v},overlaps:function(n){n=ee(n);var r=this.min,s=this.max,u=n.min,f=n.max,h=f.x>r.x&&u.xr.y&&u.y=r.lat&&f.lat<=s.lat&&u.lng>=r.lng&&f.lng<=s.lng},intersects:function(n){n=se(n);var r=this._southWest,s=this._northEast,u=n.getSouthWest(),f=n.getNorthEast(),h=f.lat>=r.lat&&u.lat<=s.lat,v=f.lng>=r.lng&&u.lng<=s.lng;return h&&v},overlaps:function(n){n=se(n);var r=this._southWest,s=this._northEast,u=n.getSouthWest(),f=n.getNorthEast(),h=f.lat>r.lat&&u.latr.lng&&u.lng1,Yp=function(){var n=!1;try{var r=Object.defineProperty({},"passive",{get:function(){n=!0}});window.addEventListener("testPassiveEventSupport",w,r),window.removeEventListener("testPassiveEventSupport",w,r)}catch{}return n}(),qp=function(){return!!document.createElement("canvas").getContext}(),Os=!!(document.createElementNS&&Nu("svg").createSVGRect),Jp=!!Os&&function(){var n=document.createElement("div");return n.innerHTML="",(n.firstChild&&n.firstChild.namespaceURI)==="http://www.w3.org/2000/svg"}(),$p=!Os&&function(){try{var n=document.createElement("div");n.innerHTML='';var r=n.firstChild;return r.style.behavior="url(#default#VML)",r&&typeof r.adj=="object"}catch{return!1}}(),em=navigator.platform.indexOf("Mac")===0,tm=navigator.platform.indexOf("Linux")===0;function kt(n){return navigator.userAgent.toLowerCase().indexOf(n)>=0}var H={ie:jr,ielt9:Zp,edge:Iu,webkit:Ms,android:Ru,android23:Bu,androidStock:Fp,opera:zs,chrome:ju,gecko:Zu,safari:Up,phantom:Du,opera12:Fu,win:Wp,ie3d:Uu,webkit3d:Ns,gecko3d:Wu,any3d:Hp,mobile:Ti,mobileWebkit:Vp,mobileWebkit3d:Qp,msPointer:Hu,pointer:Vu,touch:bp,touchNative:Qu,mobileOpera:Kp,mobileGecko:Gp,retina:Xp,passiveEvents:Yp,canvas:qp,svg:Os,vml:$p,inlineSvg:Jp,mac:em,linux:tm},bu=H.msPointer?"MSPointerDown":"pointerdown",Ku=H.msPointer?"MSPointerMove":"pointermove",Gu=H.msPointer?"MSPointerUp":"pointerup",Xu=H.msPointer?"MSPointerCancel":"pointercancel",Is={touchstart:bu,touchmove:Ku,touchend:Gu,touchcancel:Xu},Yu={touchstart:am,touchmove:Zr,touchend:Zr,touchcancel:Zr},Wn={},qu=!1;function nm(n,r,s){return r==="touchstart"&&sm(),Yu[r]?(s=Yu[r].bind(this,s),n.addEventListener(Is[r],s,!1),s):(console.warn("wrong event specified:",r),w)}function im(n,r,s){if(!Is[r]){console.warn("wrong event specified:",r);return}n.removeEventListener(Is[r],s,!1)}function rm(n){Wn[n.pointerId]=n}function om(n){Wn[n.pointerId]&&(Wn[n.pointerId]=n)}function Ju(n){delete Wn[n.pointerId]}function sm(){qu||(document.addEventListener(bu,rm,!0),document.addEventListener(Ku,om,!0),document.addEventListener(Gu,Ju,!0),document.addEventListener(Xu,Ju,!0),qu=!0)}function Zr(n,r){if(r.pointerType!==(r.MSPOINTER_TYPE_MOUSE||"mouse")){r.touches=[];for(var s in Wn)r.touches.push(Wn[s]);r.changedTouches=[r],n(r)}}function am(n,r){r.MSPOINTER_TYPE_TOUCH&&r.pointerType===r.MSPOINTER_TYPE_TOUCH&&Ne(r),Zr(n,r)}function lm(n){var r={},s,u;for(u in n)s=n[u],r[u]=s&&s.bind?s.bind(n):s;return n=r,r.type="dblclick",r.detail=2,r.isTrusted=!1,r._simulated=!0,r}var um=200;function cm(n,r){n.addEventListener("dblclick",r);var s=0,u;function f(h){if(h.detail!==1){u=h.detail;return}if(!(h.pointerType==="mouse"||h.sourceCapabilities&&!h.sourceCapabilities.firesTouchEvents)){var v=ic(h);if(!(v.some(function(k){return k instanceof HTMLLabelElement&&k.attributes.for})&&!v.some(function(k){return k instanceof HTMLInputElement||k instanceof HTMLSelectElement}))){var S=Date.now();S-s<=um?(u++,u===2&&r(lm(h))):u=1,s=S}}}return n.addEventListener("click",f),{dblclick:r,simDblclick:f}}function fm(n,r){n.removeEventListener("dblclick",r.dblclick),n.removeEventListener("click",r.simDblclick)}var Rs=Ur(["transform","webkitTransform","OTransform","MozTransform","msTransform"]),Mi=Ur(["webkitTransition","transition","OTransition","MozTransition","msTransition"]),$u=Mi==="webkitTransition"||Mi==="OTransition"?Mi+"End":"transitionend";function ec(n){return typeof n=="string"?document.getElementById(n):n}function zi(n,r){var s=n.style[r]||n.currentStyle&&n.currentStyle[r];if((!s||s==="auto")&&document.defaultView){var u=document.defaultView.getComputedStyle(n,null);s=u?u[r]:null}return s==="auto"?null:s}function ie(n,r,s){var u=document.createElement(n);return u.className=r||"",s&&s.appendChild(u),u}function de(n){var r=n.parentNode;r&&r.removeChild(n)}function Dr(n){for(;n.firstChild;)n.removeChild(n.firstChild)}function Hn(n){var r=n.parentNode;r&&r.lastChild!==n&&r.appendChild(n)}function Vn(n){var r=n.parentNode;r&&r.firstChild!==n&&r.insertBefore(n,r.firstChild)}function Bs(n,r){if(n.classList!==void 0)return n.classList.contains(r);var s=Fr(n);return s.length>0&&new RegExp("(^|\\s)"+r+"(\\s|$)").test(s)}function Y(n,r){if(n.classList!==void 0)for(var s=A(r),u=0,f=s.length;u0?2*window.devicePixelRatio:1;function oc(n){return H.edge?n.wheelDeltaY/2:n.deltaY&&n.deltaMode===0?-n.deltaY/pm:n.deltaY&&n.deltaMode===1?-n.deltaY*20:n.deltaY&&n.deltaMode===2?-n.deltaY*60:n.deltaX||n.deltaZ?0:n.wheelDelta?(n.wheelDeltaY||n.wheelDelta)/2:n.detail&&Math.abs(n.detail)<32765?-n.detail*20:n.detail?n.detail/-32765*60:0}function Gs(n,r){var s=r.relatedTarget;if(!s)return!0;try{for(;s&&s!==n;)s=s.parentNode}catch{return!1}return s!==n}var mm={__proto__:null,on:G,off:le,stopPropagation:kn,disableScrollPropagation:Ks,disableClickPropagation:Ri,preventDefault:Ne,stop:Ln,getPropagationPath:ic,getMousePosition:rc,getWheelDelta:oc,isExternalTarget:Gs,addListener:G,removeListener:le},sc=Ot.extend({run:function(n,r,s,u){this.stop(),this._el=n,this._inProgress=!0,this._duration=s||.25,this._easeOutPower=1/Math.max(u||.5,.2),this._startPos=Sn(n),this._offset=r.subtract(this._startPos),this._startTime=+new Date,this.fire("start"),this._animate()},stop:function(){this._inProgress&&(this._step(!0),this._complete())},_animate:function(){this._animId=ae(this._animate,this),this._step()},_step:function(n){var r=+new Date-this._startTime,s=this._duration*1e3;rthis.options.maxZoom)?this.setZoom(n):this},panInsideBounds:function(n,r){this._enforcingBounds=!0;var s=this.getCenter(),u=this._limitCenter(s,this._zoom,se(n));return s.equals(u)||this.panTo(u,r),this._enforcingBounds=!1,this},panInside:function(n,r){r=r||{};var s=R(r.paddingTopLeft||r.padding||[0,0]),u=R(r.paddingBottomRight||r.padding||[0,0]),f=this.project(this.getCenter()),h=this.project(n),v=this.getPixelBounds(),S=ee([v.min.add(s),v.max.subtract(u)]),k=S.getSize();if(!S.contains(h)){this._enforcingBounds=!0;var z=h.subtract(S.getCenter()),Z=S.extend(h).getSize().subtract(k);f.x+=z.x<0?-Z.x:Z.x,f.y+=z.y<0?-Z.y:Z.y,this.panTo(this.unproject(f),r),this._enforcingBounds=!1}return this},invalidateSize:function(n){if(!this._loaded)return this;n=a({animate:!1,pan:!0},n===!0?{animate:!0}:n);var r=this.getSize();this._sizeChanged=!0,this._lastCenter=null;var s=this.getSize(),u=r.divideBy(2).round(),f=s.divideBy(2).round(),h=u.subtract(f);return!h.x&&!h.y?this:(n.animate&&n.pan?this.panBy(h):(n.pan&&this._rawPanBy(h),this.fire("move"),n.debounceMoveend?(clearTimeout(this._sizeTimer),this._sizeTimer=setTimeout(c(this.fire,this,"moveend"),200)):this.fire("moveend")),this.fire("resize",{oldSize:r,newSize:s}))},stop:function(){return this.setZoom(this._limitZoom(this._zoom)),this.options.zoomSnap||this.fire("viewreset"),this._stop()},locate:function(n){if(n=this._locateOptions=a({timeout:1e4,watch:!1},n),!("geolocation"in navigator))return this._handleGeolocationError({code:0,message:"Geolocation not supported."}),this;var r=c(this._handleGeolocationResponse,this),s=c(this._handleGeolocationError,this);return n.watch?this._locationWatchId=navigator.geolocation.watchPosition(r,s,n):navigator.geolocation.getCurrentPosition(r,s,n),this},stopLocate:function(){return navigator.geolocation&&navigator.geolocation.clearWatch&&navigator.geolocation.clearWatch(this._locationWatchId),this._locateOptions&&(this._locateOptions.setView=!1),this},_handleGeolocationError:function(n){if(this._container._leaflet_id){var r=n.code,s=n.message||(r===1?"permission denied":r===2?"position unavailable":"timeout");this._locateOptions.setView&&!this._loaded&&this.fitWorld(),this.fire("locationerror",{code:r,message:"Geolocation error: "+s+"."})}},_handleGeolocationResponse:function(n){if(this._container._leaflet_id){var r=n.coords.latitude,s=n.coords.longitude,u=new ne(r,s),f=u.toBounds(n.coords.accuracy*2),h=this._locateOptions;if(h.setView){var v=this.getBoundsZoom(f);this.setView(u,h.maxZoom?Math.min(v,h.maxZoom):v)}var S={latlng:u,bounds:f,timestamp:n.timestamp};for(var k in n.coords)typeof n.coords[k]=="number"&&(S[k]=n.coords[k]);this.fire("locationfound",S)}},addHandler:function(n,r){if(!r)return this;var s=this[n]=new r(this);return this._handlers.push(s),this.options[n]&&s.enable(),this},remove:function(){if(this._initEvents(!0),this.options.maxBounds&&this.off("moveend",this._panInsideMaxBounds),this._containerId!==this._container._leaflet_id)throw new Error("Map container is being reused by another instance");try{delete this._container._leaflet_id,delete this._containerId}catch{this._container._leaflet_id=void 0,this._containerId=void 0}this._locationWatchId!==void 0&&this.stopLocate(),this._stop(),de(this._mapPane),this._clearControlPos&&this._clearControlPos(),this._resizeRequest&&(Ce(this._resizeRequest),this._resizeRequest=null),this._clearHandlers(),this._loaded&&this.fire("unload");var n;for(n in this._layers)this._layers[n].remove();for(n in this._panes)de(this._panes[n]);return this._layers=[],this._panes=[],delete this._mapPane,delete this._renderer,this},createPane:function(n,r){var s="leaflet-pane"+(n?" leaflet-"+n.replace("Pane","")+"-pane":""),u=ie("div",s,r||this._mapPane);return n&&(this._panes[n]=u),u},getCenter:function(){return this._checkIfLoaded(),this._lastCenter&&!this._moved()?this._lastCenter.clone():this.layerPointToLatLng(this._getCenterLayerPoint())},getZoom:function(){return this._zoom},getBounds:function(){var n=this.getPixelBounds(),r=this.unproject(n.getBottomLeft()),s=this.unproject(n.getTopRight());return new ke(r,s)},getMinZoom:function(){return this.options.minZoom===void 0?this._layersMinZoom||0:this.options.minZoom},getMaxZoom:function(){return this.options.maxZoom===void 0?this._layersMaxZoom===void 0?1/0:this._layersMaxZoom:this.options.maxZoom},getBoundsZoom:function(n,r,s){n=se(n),s=R(s||[0,0]);var u=this.getZoom()||0,f=this.getMinZoom(),h=this.getMaxZoom(),v=n.getNorthWest(),S=n.getSouthEast(),k=this.getSize().subtract(s),z=ee(this.project(S,u),this.project(v,u)).getSize(),Z=H.any3d?this.options.zoomSnap:1,V=k.x/z.x,q=k.y/z.y,Fe=r?Math.max(V,q):Math.min(V,q);return u=this.getScaleZoom(Fe,u),Z&&(u=Math.round(u/(Z/100))*(Z/100),u=r?Math.ceil(u/Z)*Z:Math.floor(u/Z)*Z),Math.max(f,Math.min(h,u))},getSize:function(){return(!this._size||this._sizeChanged)&&(this._size=new M(this._container.clientWidth||0,this._container.clientHeight||0),this._sizeChanged=!1),this._size.clone()},getPixelBounds:function(n,r){var s=this._getTopLeftPoint(n,r);return new Q(s,s.add(this.getSize()))},getPixelOrigin:function(){return this._checkIfLoaded(),this._pixelOrigin},getPixelWorldBounds:function(n){return this.options.crs.getProjectedBounds(n===void 0?this.getZoom():n)},getPane:function(n){return typeof n=="string"?this._panes[n]:n},getPanes:function(){return this._panes},getContainer:function(){return this._container},getZoomScale:function(n,r){var s=this.options.crs;return r=r===void 0?this._zoom:r,s.scale(n)/s.scale(r)},getScaleZoom:function(n,r){var s=this.options.crs;r=r===void 0?this._zoom:r;var u=s.zoom(n*s.scale(r));return isNaN(u)?1/0:u},project:function(n,r){return r=r===void 0?this._zoom:r,this.options.crs.latLngToPoint(K(n),r)},unproject:function(n,r){return r=r===void 0?this._zoom:r,this.options.crs.pointToLatLng(R(n),r)},layerPointToLatLng:function(n){var r=R(n).add(this.getPixelOrigin());return this.unproject(r)},latLngToLayerPoint:function(n){var r=this.project(K(n))._round();return r._subtract(this.getPixelOrigin())},wrapLatLng:function(n){return this.options.crs.wrapLatLng(K(n))},wrapLatLngBounds:function(n){return this.options.crs.wrapLatLngBounds(se(n))},distance:function(n,r){return this.options.crs.distance(K(n),K(r))},containerPointToLayerPoint:function(n){return R(n).subtract(this._getMapPanePos())},layerPointToContainerPoint:function(n){return R(n).add(this._getMapPanePos())},containerPointToLatLng:function(n){var r=this.containerPointToLayerPoint(R(n));return this.layerPointToLatLng(r)},latLngToContainerPoint:function(n){return this.layerPointToContainerPoint(this.latLngToLayerPoint(K(n)))},mouseEventToContainerPoint:function(n){return rc(n,this._container)},mouseEventToLayerPoint:function(n){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(n))},mouseEventToLatLng:function(n){return this.layerPointToLatLng(this.mouseEventToLayerPoint(n))},_initContainer:function(n){var r=this._container=ec(n);if(r){if(r._leaflet_id)throw new Error("Map container is already initialized.")}else throw new Error("Map container not found.");G(r,"scroll",this._onScroll,this),this._containerId=p(r)},_initLayout:function(){var n=this._container;this._fadeAnimated=this.options.fadeAnimation&&H.any3d,Y(n,"leaflet-container"+(H.touch?" leaflet-touch":"")+(H.retina?" leaflet-retina":"")+(H.ielt9?" leaflet-oldie":"")+(H.safari?" leaflet-safari":"")+(this._fadeAnimated?" leaflet-fade-anim":""));var r=zi(n,"position");r!=="absolute"&&r!=="relative"&&r!=="fixed"&&r!=="sticky"&&(n.style.position="relative"),this._initPanes(),this._initControlPos&&this._initControlPos()},_initPanes:function(){var n=this._panes={};this._paneRenderers={},this._mapPane=this.createPane("mapPane",this._container),xe(this._mapPane,new M(0,0)),this.createPane("tilePane"),this.createPane("overlayPane"),this.createPane("shadowPane"),this.createPane("markerPane"),this.createPane("tooltipPane"),this.createPane("popupPane"),this.options.markerZoomAnimation||(Y(n.markerPane,"leaflet-zoom-hide"),Y(n.shadowPane,"leaflet-zoom-hide"))},_resetView:function(n,r,s){xe(this._mapPane,new M(0,0));var u=!this._loaded;this._loaded=!0,r=this._limitZoom(r),this.fire("viewprereset");var f=this._zoom!==r;this._moveStart(f,s)._move(n,r)._moveEnd(f),this.fire("viewreset"),u&&this.fire("load")},_moveStart:function(n,r){return n&&this.fire("zoomstart"),r||this.fire("movestart"),this},_move:function(n,r,s,u){r===void 0&&(r=this._zoom);var f=this._zoom!==r;return this._zoom=r,this._lastCenter=n,this._pixelOrigin=this._getNewPixelOrigin(n),u?s&&s.pinch&&this.fire("zoom",s):((f||s&&s.pinch)&&this.fire("zoom",s),this.fire("move",s)),this},_moveEnd:function(n){return n&&this.fire("zoomend"),this.fire("moveend")},_stop:function(){return Ce(this._flyToFrame),this._panAnim&&this._panAnim.stop(),this},_rawPanBy:function(n){xe(this._mapPane,this._getMapPanePos().subtract(n))},_getZoomSpan:function(){return this.getMaxZoom()-this.getMinZoom()},_panInsideMaxBounds:function(){this._enforcingBounds||this.panInsideBounds(this.options.maxBounds)},_checkIfLoaded:function(){if(!this._loaded)throw new Error("Set map center and zoom first.")},_initEvents:function(n){this._targets={},this._targets[p(this._container)]=this;var r=n?le:G;r(this._container,"click dblclick mousedown mouseup mouseover mouseout mousemove contextmenu keypress keydown keyup",this._handleDOMEvent,this),this.options.trackResize&&r(window,"resize",this._onResize,this),H.any3d&&this.options.transform3DLimit&&(n?this.off:this.on).call(this,"moveend",this._onMoveEnd)},_onResize:function(){Ce(this._resizeRequest),this._resizeRequest=ae(function(){this.invalidateSize({debounceMoveend:!0})},this)},_onScroll:function(){this._container.scrollTop=0,this._container.scrollLeft=0},_onMoveEnd:function(){var n=this._getMapPanePos();Math.max(Math.abs(n.x),Math.abs(n.y))>=this.options.transform3DLimit&&this._resetView(this.getCenter(),this.getZoom())},_findEventTargets:function(n,r){for(var s=[],u,f=r==="mouseout"||r==="mouseover",h=n.target||n.srcElement,v=!1;h;){if(u=this._targets[p(h)],u&&(r==="click"||r==="preclick")&&this._draggableMoved(u)){v=!0;break}if(u&&u.listens(r,!0)&&(f&&!Gs(h,n)||(s.push(u),f))||h===this._container)break;h=h.parentNode}return!s.length&&!v&&!f&&this.listens(r,!0)&&(s=[this]),s},_isClickDisabled:function(n){for(;n&&n!==this._container;){if(n._leaflet_disable_click)return!0;n=n.parentNode}},_handleDOMEvent:function(n){var r=n.target||n.srcElement;if(!(!this._loaded||r._leaflet_disable_events||n.type==="click"&&this._isClickDisabled(r))){var s=n.type;s==="mousedown"&&Ws(r),this._fireDOMEvent(n,s)}},_mouseEvents:["click","dblclick","mouseover","mouseout","contextmenu"],_fireDOMEvent:function(n,r,s){if(n.type==="click"){var u=a({},n);u.type="preclick",this._fireDOMEvent(u,u.type,s)}var f=this._findEventTargets(n,r);if(s){for(var h=[],v=0;v0?Math.round(n-r)/2:Math.max(0,Math.ceil(n))-Math.max(0,Math.floor(r))},_limitZoom:function(n){var r=this.getMinZoom(),s=this.getMaxZoom(),u=H.any3d?this.options.zoomSnap:1;return u&&(n=Math.round(n/u)*u),Math.max(r,Math.min(s,n))},_onPanTransitionStep:function(){this.fire("move")},_onPanTransitionEnd:function(){ye(this._mapPane,"leaflet-pan-anim"),this.fire("moveend")},_tryAnimatedPan:function(n,r){var s=this._getCenterOffset(n)._trunc();return(r&&r.animate)!==!0&&!this.getSize().contains(s)?!1:(this.panBy(s,r),!0)},_createAnimProxy:function(){var n=this._proxy=ie("div","leaflet-proxy leaflet-zoom-animated");this._panes.mapPane.appendChild(n),this.on("zoomanim",function(r){var s=Rs,u=this._proxy.style[s];Pn(this._proxy,this.project(r.center,r.zoom),this.getZoomScale(r.zoom,1)),u===this._proxy.style[s]&&this._animatingZoom&&this._onZoomTransitionEnd()},this),this.on("load moveend",this._animMoveEnd,this),this._on("unload",this._destroyAnimProxy,this)},_destroyAnimProxy:function(){de(this._proxy),this.off("load moveend",this._animMoveEnd,this),delete this._proxy},_animMoveEnd:function(){var n=this.getCenter(),r=this.getZoom();Pn(this._proxy,this.project(n,r),this.getZoomScale(r,1))},_catchTransitionEnd:function(n){this._animatingZoom&&n.propertyName.indexOf("transform")>=0&&this._onZoomTransitionEnd()},_nothingToAnimate:function(){return!this._container.getElementsByClassName("leaflet-zoom-animated").length},_tryAnimatedZoom:function(n,r,s){if(this._animatingZoom)return!0;if(s=s||{},!this._zoomAnimated||s.animate===!1||this._nothingToAnimate()||Math.abs(r-this._zoom)>this.options.zoomAnimationThreshold)return!1;var u=this.getZoomScale(r),f=this._getCenterOffset(n)._divideBy(1-1/u);return s.animate!==!0&&!this.getSize().contains(f)?!1:(ae(function(){this._moveStart(!0,s.noMoveStart||!1)._animateZoom(n,r,!0)},this),!0)},_animateZoom:function(n,r,s,u){this._mapPane&&(s&&(this._animatingZoom=!0,this._animateToCenter=n,this._animateToZoom=r,Y(this._mapPane,"leaflet-zoom-anim")),this.fire("zoomanim",{center:n,zoom:r,noUpdate:u}),this._tempFireZoomEvent||(this._tempFireZoomEvent=this._zoom!==this._animateToZoom),this._move(this._animateToCenter,this._animateToZoom,void 0,!0),setTimeout(c(this._onZoomTransitionEnd,this),250))},_onZoomTransitionEnd:function(){this._animatingZoom&&(this._mapPane&&ye(this._mapPane,"leaflet-zoom-anim"),this._animatingZoom=!1,this._move(this._animateToCenter,this._animateToZoom,void 0,!0),this._tempFireZoomEvent&&this.fire("zoom"),delete this._tempFireZoomEvent,this.fire("move"),this._moveEnd(!0))}});function _m(n,r){return new $(n,r)}var mt=rt.extend({options:{position:"topright"},initialize:function(n){E(this,n)},getPosition:function(){return this.options.position},setPosition:function(n){var r=this._map;return r&&r.removeControl(this),this.options.position=n,r&&r.addControl(this),this},getContainer:function(){return this._container},addTo:function(n){this.remove(),this._map=n;var r=this._container=this.onAdd(n),s=this.getPosition(),u=n._controlCorners[s];return Y(r,"leaflet-control"),s.indexOf("bottom")!==-1?u.insertBefore(r,u.firstChild):u.appendChild(r),this._map.on("unload",this.remove,this),this},remove:function(){return this._map?(de(this._container),this.onRemove&&this.onRemove(this._map),this._map.off("unload",this.remove,this),this._map=null,this):this},_refocusOnMap:function(n){this._map&&n&&n.screenX>0&&n.screenY>0&&this._map.getContainer().focus()}}),Bi=function(n){return new mt(n)};$.include({addControl:function(n){return n.addTo(this),this},removeControl:function(n){return n.remove(),this},_initControlPos:function(){var n=this._controlCorners={},r="leaflet-",s=this._controlContainer=ie("div",r+"control-container",this._container);function u(f,h){var v=r+f+" "+r+h;n[f+h]=ie("div",v,s)}u("top","left"),u("top","right"),u("bottom","left"),u("bottom","right")},_clearControlPos:function(){for(var n in this._controlCorners)de(this._controlCorners[n]);de(this._controlContainer),delete this._controlCorners,delete this._controlContainer}});var ac=mt.extend({options:{collapsed:!0,position:"topright",autoZIndex:!0,hideSingleBase:!1,sortLayers:!1,sortFunction:function(n,r,s,u){return s1,this._baseLayersList.style.display=n?"":"none"),this._separator.style.display=r&&n?"":"none",this},_onLayerChange:function(n){this._handlingClick||this._update();var r=this._getLayer(p(n.target)),s=r.overlay?n.type==="add"?"overlayadd":"overlayremove":n.type==="add"?"baselayerchange":null;s&&this._map.fire(s,r)},_createRadioElement:function(n,r){var s='",u=document.createElement("div");return u.innerHTML=s,u.firstChild},_addItem:function(n){var r=document.createElement("label"),s=this._map.hasLayer(n.layer),u;n.overlay?(u=document.createElement("input"),u.type="checkbox",u.className="leaflet-control-layers-selector",u.defaultChecked=s):u=this._createRadioElement("leaflet-base-layers_"+p(this),s),this._layerControlInputs.push(u),u.layerId=p(n.layer),G(u,"click",this._onInputClick,this);var f=document.createElement("span");f.innerHTML=" "+n.name;var h=document.createElement("span");r.appendChild(h),h.appendChild(u),h.appendChild(f);var v=n.overlay?this._overlaysList:this._baseLayersList;return v.appendChild(r),this._checkDisabledLayers(),r},_onInputClick:function(){if(!this._preventClick){var n=this._layerControlInputs,r,s,u=[],f=[];this._handlingClick=!0;for(var h=n.length-1;h>=0;h--)r=n[h],s=this._getLayer(r.layerId).layer,r.checked?u.push(s):r.checked||f.push(s);for(h=0;h=0;f--)r=n[f],s=this._getLayer(r.layerId).layer,r.disabled=s.options.minZoom!==void 0&&us.options.maxZoom},_expandIfNotCollapsed:function(){return this._map&&!this.options.collapsed&&this.expand(),this},_expandSafely:function(){var n=this._section;this._preventClick=!0,G(n,"click",Ne),this.expand();var r=this;setTimeout(function(){le(n,"click",Ne),r._preventClick=!1})}}),vm=function(n,r,s){return new ac(n,r,s)},Xs=mt.extend({options:{position:"topleft",zoomInText:'',zoomInTitle:"Zoom in",zoomOutText:'',zoomOutTitle:"Zoom out"},onAdd:function(n){var r="leaflet-control-zoom",s=ie("div",r+" leaflet-bar"),u=this.options;return this._zoomInButton=this._createButton(u.zoomInText,u.zoomInTitle,r+"-in",s,this._zoomIn),this._zoomOutButton=this._createButton(u.zoomOutText,u.zoomOutTitle,r+"-out",s,this._zoomOut),this._updateDisabled(),n.on("zoomend zoomlevelschange",this._updateDisabled,this),s},onRemove:function(n){n.off("zoomend zoomlevelschange",this._updateDisabled,this)},disable:function(){return this._disabled=!0,this._updateDisabled(),this},enable:function(){return this._disabled=!1,this._updateDisabled(),this},_zoomIn:function(n){!this._disabled&&this._map._zoomthis._map.getMinZoom()&&this._map.zoomOut(this._map.options.zoomDelta*(n.shiftKey?3:1))},_createButton:function(n,r,s,u,f){var h=ie("a",s,u);return h.innerHTML=n,h.href="#",h.title=r,h.setAttribute("role","button"),h.setAttribute("aria-label",r),Ri(h),G(h,"click",Ln),G(h,"click",f,this),G(h,"click",this._refocusOnMap,this),h},_updateDisabled:function(){var n=this._map,r="leaflet-disabled";ye(this._zoomInButton,r),ye(this._zoomOutButton,r),this._zoomInButton.setAttribute("aria-disabled","false"),this._zoomOutButton.setAttribute("aria-disabled","false"),(this._disabled||n._zoom===n.getMinZoom())&&(Y(this._zoomOutButton,r),this._zoomOutButton.setAttribute("aria-disabled","true")),(this._disabled||n._zoom===n.getMaxZoom())&&(Y(this._zoomInButton,r),this._zoomInButton.setAttribute("aria-disabled","true"))}});$.mergeOptions({zoomControl:!0}),$.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new Xs,this.addControl(this.zoomControl))});var gm=function(n){return new Xs(n)},lc=mt.extend({options:{position:"bottomleft",maxWidth:100,metric:!0,imperial:!0},onAdd:function(n){var r="leaflet-control-scale",s=ie("div",r),u=this.options;return this._addScales(u,r+"-line",s),n.on(u.updateWhenIdle?"moveend":"move",this._update,this),n.whenReady(this._update,this),s},onRemove:function(n){n.off(this.options.updateWhenIdle?"moveend":"move",this._update,this)},_addScales:function(n,r,s){n.metric&&(this._mScale=ie("div",r,s)),n.imperial&&(this._iScale=ie("div",r,s))},_update:function(){var n=this._map,r=n.getSize().y/2,s=n.distance(n.containerPointToLatLng([0,r]),n.containerPointToLatLng([this.options.maxWidth,r]));this._updateScales(s)},_updateScales:function(n){this.options.metric&&n&&this._updateMetric(n),this.options.imperial&&n&&this._updateImperial(n)},_updateMetric:function(n){var r=this._getRoundNum(n),s=r<1e3?r+" m":r/1e3+" km";this._updateScale(this._mScale,s,r/n)},_updateImperial:function(n){var r=n*3.2808399,s,u,f;r>5280?(s=r/5280,u=this._getRoundNum(s),this._updateScale(this._iScale,u+" mi",u/s)):(f=this._getRoundNum(r),this._updateScale(this._iScale,f+" ft",f/r))},_updateScale:function(n,r,s){n.style.width=Math.round(this.options.maxWidth*s)+"px",n.innerHTML=r},_getRoundNum:function(n){var r=Math.pow(10,(Math.floor(n)+"").length-1),s=n/r;return s=s>=10?10:s>=5?5:s>=3?3:s>=2?2:1,r*s}}),ym=function(n){return new lc(n)},wm='',Ys=mt.extend({options:{position:"bottomright",prefix:''+(H.inlineSvg?wm+" ":"")+"Leaflet"},initialize:function(n){E(this,n),this._attributions={}},onAdd:function(n){n.attributionControl=this,this._container=ie("div","leaflet-control-attribution"),Ri(this._container);for(var r in n._layers)n._layers[r].getAttribution&&this.addAttribution(n._layers[r].getAttribution());return this._update(),n.on("layeradd",this._addAttribution,this),this._container},onRemove:function(n){n.off("layeradd",this._addAttribution,this)},_addAttribution:function(n){n.layer.getAttribution&&(this.addAttribution(n.layer.getAttribution()),n.layer.once("remove",function(){this.removeAttribution(n.layer.getAttribution())},this))},setPrefix:function(n){return this.options.prefix=n,this._update(),this},addAttribution:function(n){return n?(this._attributions[n]||(this._attributions[n]=0),this._attributions[n]++,this._update(),this):this},removeAttribution:function(n){return n?(this._attributions[n]&&(this._attributions[n]--,this._update()),this):this},_update:function(){if(this._map){var n=[];for(var r in this._attributions)this._attributions[r]&&n.push(r);var s=[];this.options.prefix&&s.push(this.options.prefix),n.length&&s.push(n.join(", ")),this._container.innerHTML=s.join(' ')}}});$.mergeOptions({attributionControl:!0}),$.addInitHook(function(){this.options.attributionControl&&new Ys().addTo(this)});var xm=function(n){return new Ys(n)};mt.Layers=ac,mt.Zoom=Xs,mt.Scale=lc,mt.Attribution=Ys,Bi.layers=vm,Bi.zoom=gm,Bi.scale=ym,Bi.attribution=xm;var Et=rt.extend({initialize:function(n){this._map=n},enable:function(){return this._enabled?this:(this._enabled=!0,this.addHooks(),this)},disable:function(){return this._enabled?(this._enabled=!1,this.removeHooks(),this):this},enabled:function(){return!!this._enabled}});Et.addTo=function(n,r){return n.addHandler(r,this),this};var Pm={Events:ze},uc=H.touch?"touchstart mousedown":"mousedown",Xt=Ot.extend({options:{clickTolerance:3},initialize:function(n,r,s,u){E(this,u),this._element=n,this._dragStartTarget=r||n,this._preventOutline=s},enable:function(){this._enabled||(G(this._dragStartTarget,uc,this._onDown,this),this._enabled=!0)},disable:function(){this._enabled&&(Xt._dragging===this&&this.finishDrag(!0),le(this._dragStartTarget,uc,this._onDown,this),this._enabled=!1,this._moved=!1)},_onDown:function(n){if(this._enabled&&(this._moved=!1,!Bs(this._element,"leaflet-zoom-anim"))){if(n.touches&&n.touches.length!==1){Xt._dragging===this&&this.finishDrag();return}if(!(Xt._dragging||n.shiftKey||n.which!==1&&n.button!==1&&!n.touches)&&(Xt._dragging=this,this._preventOutline&&Ws(this._element),Ds(),Ni(),!this._moving)){this.fire("down");var r=n.touches?n.touches[0]:n,s=tc(this._element);this._startPoint=new M(r.clientX,r.clientY),this._startPos=Sn(this._element),this._parentScale=Hs(s);var u=n.type==="mousedown";G(document,u?"mousemove":"touchmove",this._onMove,this),G(document,u?"mouseup":"touchend touchcancel",this._onUp,this)}}},_onMove:function(n){if(this._enabled){if(n.touches&&n.touches.length>1){this._moved=!0;return}var r=n.touches&&n.touches.length===1?n.touches[0]:n,s=new M(r.clientX,r.clientY)._subtract(this._startPoint);!s.x&&!s.y||Math.abs(s.x)+Math.abs(s.y)h&&(v=S,h=k);h>s&&(r[v]=1,Js(n,r,s,u,v),Js(n,r,s,v,f))}function Em(n,r){for(var s=[n[0]],u=1,f=0,h=n.length;ur&&(s.push(n[u]),f=u);return fr.max.x&&(s|=2),n.yr.max.y&&(s|=8),s}function Cm(n,r){var s=r.x-n.x,u=r.y-n.y;return s*s+u*u}function ji(n,r,s,u){var f=r.x,h=r.y,v=s.x-f,S=s.y-h,k=v*v+S*S,z;return k>0&&(z=((n.x-f)*v+(n.y-h)*S)/k,z>1?(f=s.x,h=s.y):z>0&&(f+=v*z,h+=S*z)),v=n.x-f,S=n.y-h,u?v*v+S*S:new M(f,h)}function st(n){return!y(n[0])||typeof n[0][0]!="object"&&typeof n[0][0]<"u"}function _c(n){return console.warn("Deprecated use of _flat, please use L.LineUtil.isFlat instead."),st(n)}function vc(n,r){var s,u,f,h,v,S,k,z;if(!n||n.length===0)throw new Error("latlngs not passed");st(n)||(console.warn("latlngs are not flat! Only the first ring will be used"),n=n[0]);var Z=K([0,0]),V=se(n),q=V.getNorthWest().distanceTo(V.getSouthWest())*V.getNorthEast().distanceTo(V.getNorthWest());q<1700&&(Z=qs(n));var Fe=n.length,Ae=[];for(s=0;su){k=(h-u)/f,z=[S.x-k*(S.x-v.x),S.y-k*(S.y-v.y)];break}var be=r.unproject(R(z));return K([be.lat+Z.lat,be.lng+Z.lng])}var Am={__proto__:null,simplify:hc,pointToSegmentDistance:dc,closestPointOnSegment:km,clipSegment:mc,_getEdgeIntersection:Vr,_getBitCode:En,_sqClosestPointOnSegment:ji,isFlat:st,_flat:_c,polylineCenter:vc},$s={project:function(n){return new M(n.lng,n.lat)},unproject:function(n){return new ne(n.y,n.x)},bounds:new Q([-180,-90],[180,90])},ea={R:6378137,R_MINOR:6356752314245179e-9,bounds:new Q([-2003750834279e-5,-1549657073972e-5],[2003750834279e-5,1876465623138e-5]),project:function(n){var r=Math.PI/180,s=this.R,u=n.lat*r,f=this.R_MINOR/s,h=Math.sqrt(1-f*f),v=h*Math.sin(u),S=Math.tan(Math.PI/4-u/2)/Math.pow((1-v)/(1+v),h/2);return u=-s*Math.log(Math.max(S,1e-10)),new M(n.lng*r*s,u)},unproject:function(n){for(var r=180/Math.PI,s=this.R,u=this.R_MINOR/s,f=Math.sqrt(1-u*u),h=Math.exp(-n.y/s),v=Math.PI/2-2*Math.atan(h),S=0,k=.1,z;S<15&&Math.abs(k)>1e-7;S++)z=f*Math.sin(v),z=Math.pow((1-z)/(1+z),f/2),k=Math.PI/2-2*Math.atan(h*z)-v,v+=k;return new ne(v*r,n.x*r/s)}},Tm={__proto__:null,LonLat:$s,Mercator:ea,SphericalMercator:Es},Mm=a({},Gt,{code:"EPSG:3395",projection:ea,transformation:function(){var n=.5/(Math.PI*ea.R);return Ai(n,.5,-n,.5)}()}),gc=a({},Gt,{code:"EPSG:4326",projection:$s,transformation:Ai(1/180,1,-1/180,.5)}),zm=a({},Qe,{projection:$s,transformation:Ai(1,0,-1,0),scale:function(n){return Math.pow(2,n)},zoom:function(n){return Math.log(n)/Math.LN2},distance:function(n,r){var s=r.lng-n.lng,u=r.lat-n.lat;return Math.sqrt(s*s+u*u)},infinite:!0});Qe.Earth=Gt,Qe.EPSG3395=Mm,Qe.EPSG3857=As,Qe.EPSG900913=jp,Qe.EPSG4326=gc,Qe.Simple=zm;var _t=Ot.extend({options:{pane:"overlayPane",attribution:null,bubblingMouseEvents:!0},addTo:function(n){return n.addLayer(this),this},remove:function(){return this.removeFrom(this._map||this._mapToAdd)},removeFrom:function(n){return n&&n.removeLayer(this),this},getPane:function(n){return this._map.getPane(n?this.options[n]||n:this.options.pane)},addInteractiveTarget:function(n){return this._map._targets[p(n)]=this,this},removeInteractiveTarget:function(n){return delete this._map._targets[p(n)],this},getAttribution:function(){return this.options.attribution},_layerAdd:function(n){var r=n.target;if(r.hasLayer(this)){if(this._map=r,this._zoomAnimated=r._zoomAnimated,this.getEvents){var s=this.getEvents();r.on(s,this),this.once("remove",function(){r.off(s,this)},this)}this.onAdd(r),this.fire("add"),r.fire("layeradd",{layer:this})}}});$.include({addLayer:function(n){if(!n._layerAdd)throw new Error("The provided object is not a Layer.");var r=p(n);return this._layers[r]?this:(this._layers[r]=n,n._mapToAdd=this,n.beforeAdd&&n.beforeAdd(this),this.whenReady(n._layerAdd,n),this)},removeLayer:function(n){var r=p(n);return this._layers[r]?(this._loaded&&n.onRemove(this),delete this._layers[r],this._loaded&&(this.fire("layerremove",{layer:n}),n.fire("remove")),n._map=n._mapToAdd=null,this):this},hasLayer:function(n){return p(n)in this._layers},eachLayer:function(n,r){for(var s in this._layers)n.call(r,this._layers[s]);return this},_addLayers:function(n){n=n?y(n)?n:[n]:[];for(var r=0,s=n.length;rthis._layersMaxZoom&&this.setZoom(this._layersMaxZoom),this.options.minZoom===void 0&&this._layersMinZoom&&this.getZoom()=2&&r[0]instanceof ne&&r[0].equals(r[s-1])&&r.pop(),r},_setLatLngs:function(n){Rt.prototype._setLatLngs.call(this,n),st(this._latlngs)&&(this._latlngs=[this._latlngs])},_defaultShape:function(){return st(this._latlngs[0])?this._latlngs[0]:this._latlngs[0][0]},_clipPoints:function(){var n=this._renderer._bounds,r=this.options.weight,s=new M(r,r);if(n=new Q(n.min.subtract(s),n.max.add(s)),this._parts=[],!(!this._pxBounds||!this._pxBounds.intersects(n))){if(this.options.noClip){this._parts=this._rings;return}for(var u=0,f=this._rings.length,h;un.y!=f.y>n.y&&n.x<(f.x-u.x)*(n.y-u.y)/(f.y-u.y)+u.x&&(r=!r);return r||Rt.prototype._containsPoint.call(this,n,!0)}});function Dm(n,r){return new Kn(n,r)}var Bt=It.extend({initialize:function(n,r){E(this,r),this._layers={},n&&this.addData(n)},addData:function(n){var r=y(n)?n:n.features,s,u,f;if(r){for(s=0,u=r.length;s0&&f.push(f[0].slice()),f}function Gn(n,r){return n.feature?a({},n.feature,{geometry:r}):Yr(r)}function Yr(n){return n.type==="Feature"||n.type==="FeatureCollection"?n:{type:"Feature",properties:{},geometry:n}}var ra={toGeoJSON:function(n){return Gn(this,{type:"Point",coordinates:ia(this.getLatLng(),n)})}};Qr.include(ra),ta.include(ra),br.include(ra),Rt.include({toGeoJSON:function(n){var r=!st(this._latlngs),s=Xr(this._latlngs,r?1:0,!1,n);return Gn(this,{type:(r?"Multi":"")+"LineString",coordinates:s})}}),Kn.include({toGeoJSON:function(n){var r=!st(this._latlngs),s=r&&!st(this._latlngs[0]),u=Xr(this._latlngs,s?2:r?1:0,!0,n);return r||(u=[u]),Gn(this,{type:(s?"Multi":"")+"Polygon",coordinates:u})}}),Qn.include({toMultiPoint:function(n){var r=[];return this.eachLayer(function(s){r.push(s.toGeoJSON(n).geometry.coordinates)}),Gn(this,{type:"MultiPoint",coordinates:r})},toGeoJSON:function(n){var r=this.feature&&this.feature.geometry&&this.feature.geometry.type;if(r==="MultiPoint")return this.toMultiPoint(n);var s=r==="GeometryCollection",u=[];return this.eachLayer(function(f){if(f.toGeoJSON){var h=f.toGeoJSON(n);if(s)u.push(h.geometry);else{var v=Yr(h);v.type==="FeatureCollection"?u.push.apply(u,v.features):u.push(v)}}}),s?Gn(this,{geometries:u,type:"GeometryCollection"}):{type:"FeatureCollection",features:u}}});function xc(n,r){return new Bt(n,r)}var Fm=xc,qr=_t.extend({options:{opacity:1,alt:"",interactive:!1,crossOrigin:!1,errorOverlayUrl:"",zIndex:1,className:""},initialize:function(n,r,s){this._url=n,this._bounds=se(r),E(this,s)},onAdd:function(){this._image||(this._initImage(),this.options.opacity<1&&this._updateOpacity()),this.options.interactive&&(Y(this._image,"leaflet-interactive"),this.addInteractiveTarget(this._image)),this.getPane().appendChild(this._image),this._reset()},onRemove:function(){de(this._image),this.options.interactive&&this.removeInteractiveTarget(this._image)},setOpacity:function(n){return this.options.opacity=n,this._image&&this._updateOpacity(),this},setStyle:function(n){return n.opacity&&this.setOpacity(n.opacity),this},bringToFront:function(){return this._map&&Hn(this._image),this},bringToBack:function(){return this._map&&Vn(this._image),this},setUrl:function(n){return this._url=n,this._image&&(this._image.src=n),this},setBounds:function(n){return this._bounds=se(n),this._map&&this._reset(),this},getEvents:function(){var n={zoom:this._reset,viewreset:this._reset};return this._zoomAnimated&&(n.zoomanim=this._animateZoom),n},setZIndex:function(n){return this.options.zIndex=n,this._updateZIndex(),this},getBounds:function(){return this._bounds},getElement:function(){return this._image},_initImage:function(){var n=this._url.tagName==="IMG",r=this._image=n?this._url:ie("img");if(Y(r,"leaflet-image-layer"),this._zoomAnimated&&Y(r,"leaflet-zoom-animated"),this.options.className&&Y(r,this.options.className),r.onselectstart=w,r.onmousemove=w,r.onload=c(this.fire,this,"load"),r.onerror=c(this._overlayOnError,this,"error"),(this.options.crossOrigin||this.options.crossOrigin==="")&&(r.crossOrigin=this.options.crossOrigin===!0?"":this.options.crossOrigin),this.options.zIndex&&this._updateZIndex(),n){this._url=r.src;return}r.src=this._url,r.alt=this.options.alt},_animateZoom:function(n){var r=this._map.getZoomScale(n.zoom),s=this._map._latLngBoundsToNewLayerBounds(this._bounds,n.zoom,n.center).min;Pn(this._image,s,r)},_reset:function(){var n=this._image,r=new Q(this._map.latLngToLayerPoint(this._bounds.getNorthWest()),this._map.latLngToLayerPoint(this._bounds.getSouthEast())),s=r.getSize();xe(n,r.min),n.style.width=s.x+"px",n.style.height=s.y+"px"},_updateOpacity:function(){ot(this._image,this.options.opacity)},_updateZIndex:function(){this._image&&this.options.zIndex!==void 0&&this.options.zIndex!==null&&(this._image.style.zIndex=this.options.zIndex)},_overlayOnError:function(){this.fire("error");var n=this.options.errorOverlayUrl;n&&this._url!==n&&(this._url=n,this._image.src=n)},getCenter:function(){return this._bounds.getCenter()}}),Um=function(n,r,s){return new qr(n,r,s)},Pc=qr.extend({options:{autoplay:!0,loop:!0,keepAspectRatio:!0,muted:!1,playsInline:!0},_initImage:function(){var n=this._url.tagName==="VIDEO",r=this._image=n?this._url:ie("video");if(Y(r,"leaflet-image-layer"),this._zoomAnimated&&Y(r,"leaflet-zoom-animated"),this.options.className&&Y(r,this.options.className),r.onselectstart=w,r.onmousemove=w,r.onloadeddata=c(this.fire,this,"load"),n){for(var s=r.getElementsByTagName("source"),u=[],f=0;f0?u:[r.src];return}y(this._url)||(this._url=[this._url]),!this.options.keepAspectRatio&&Object.prototype.hasOwnProperty.call(r.style,"objectFit")&&(r.style.objectFit="fill"),r.autoplay=!!this.options.autoplay,r.loop=!!this.options.loop,r.muted=!!this.options.muted,r.playsInline=!!this.options.playsInline;for(var h=0;hf?(r.height=f+"px",Y(n,h)):ye(n,h),this._containerWidth=this._container.offsetWidth},_animateZoom:function(n){var r=this._map._latLngToNewLayerPoint(this._latlng,n.zoom,n.center),s=this._getAnchor();xe(this._container,r.add(s))},_adjustPan:function(){if(this.options.autoPan){if(this._map._panAnim&&this._map._panAnim.stop(),this._autopanning){this._autopanning=!1;return}var n=this._map,r=parseInt(zi(this._container,"marginBottom"),10)||0,s=this._container.offsetHeight+r,u=this._containerWidth,f=new M(this._containerLeft,-s-this._containerBottom);f._add(Sn(this._container));var h=n.layerPointToContainerPoint(f),v=R(this.options.autoPanPadding),S=R(this.options.autoPanPaddingTopLeft||v),k=R(this.options.autoPanPaddingBottomRight||v),z=n.getSize(),Z=0,V=0;h.x+u+k.x>z.x&&(Z=h.x+u-z.x+k.x),h.x-Z-S.x<0&&(Z=h.x-S.x),h.y+s+k.y>z.y&&(V=h.y+s-z.y+k.y),h.y-V-S.y<0&&(V=h.y-S.y),(Z||V)&&(this.options.keepInView&&(this._autopanning=!0),n.fire("autopanstart").panBy([Z,V]))}},_getAnchor:function(){return R(this._source&&this._source._getPopupAnchor?this._source._getPopupAnchor():[0,0])}}),Vm=function(n,r){return new Jr(n,r)};$.mergeOptions({closePopupOnClick:!0}),$.include({openPopup:function(n,r,s){return this._initOverlay(Jr,n,r,s).openOn(this),this},closePopup:function(n){return n=arguments.length?n:this._popup,n&&n.close(),this}}),_t.include({bindPopup:function(n,r){return this._popup=this._initOverlay(Jr,this._popup,n,r),this._popupHandlersAdded||(this.on({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!0),this},unbindPopup:function(){return this._popup&&(this.off({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!1,this._popup=null),this},openPopup:function(n){return this._popup&&(this instanceof It||(this._popup._source=this),this._popup._prepareOpen(n||this._latlng)&&this._popup.openOn(this._map)),this},closePopup:function(){return this._popup&&this._popup.close(),this},togglePopup:function(){return this._popup&&this._popup.toggle(this),this},isPopupOpen:function(){return this._popup?this._popup.isOpen():!1},setPopupContent:function(n){return this._popup&&this._popup.setContent(n),this},getPopup:function(){return this._popup},_openPopup:function(n){if(!(!this._popup||!this._map)){Ln(n);var r=n.layer||n.target;if(this._popup._source===r&&!(r instanceof Yt)){this._map.hasLayer(this._popup)?this.closePopup():this.openPopup(n.latlng);return}this._popup._source=r,this.openPopup(n.latlng)}},_movePopup:function(n){this._popup.setLatLng(n.latlng)},_onKeyPress:function(n){n.originalEvent.keyCode===13&&this._openPopup(n)}});var $r=Ct.extend({options:{pane:"tooltipPane",offset:[0,0],direction:"auto",permanent:!1,sticky:!1,opacity:.9},onAdd:function(n){Ct.prototype.onAdd.call(this,n),this.setOpacity(this.options.opacity),n.fire("tooltipopen",{tooltip:this}),this._source&&(this.addEventParent(this._source),this._source.fire("tooltipopen",{tooltip:this},!0))},onRemove:function(n){Ct.prototype.onRemove.call(this,n),n.fire("tooltipclose",{tooltip:this}),this._source&&(this.removeEventParent(this._source),this._source.fire("tooltipclose",{tooltip:this},!0))},getEvents:function(){var n=Ct.prototype.getEvents.call(this);return this.options.permanent||(n.preclick=this.close),n},_initLayout:function(){var n="leaflet-tooltip",r=n+" "+(this.options.className||"")+" leaflet-zoom-"+(this._zoomAnimated?"animated":"hide");this._contentNode=this._container=ie("div",r),this._container.setAttribute("role","tooltip"),this._container.setAttribute("id","leaflet-tooltip-"+p(this))},_updateLayout:function(){},_adjustPan:function(){},_setPosition:function(n){var r,s,u=this._map,f=this._container,h=u.latLngToContainerPoint(u.getCenter()),v=u.layerPointToContainerPoint(n),S=this.options.direction,k=f.offsetWidth,z=f.offsetHeight,Z=R(this.options.offset),V=this._getAnchor();S==="top"?(r=k/2,s=z):S==="bottom"?(r=k/2,s=0):S==="center"?(r=k/2,s=z/2):S==="right"?(r=0,s=z/2):S==="left"?(r=k,s=z/2):v.xthis.options.maxZoom||su?this._retainParent(f,h,v,u):!1)},_retainChildren:function(n,r,s,u){for(var f=2*n;f<2*n+2;f++)for(var h=2*r;h<2*r+2;h++){var v=new M(f,h);v.z=s+1;var S=this._tileCoordsToKey(v),k=this._tiles[S];if(k&&k.active){k.retain=!0;continue}else k&&k.loaded&&(k.retain=!0);s+1this.options.maxZoom||this.options.minZoom!==void 0&&f1){this._setView(n,s);return}for(var V=f.min.y;V<=f.max.y;V++)for(var q=f.min.x;q<=f.max.x;q++){var Fe=new M(q,V);if(Fe.z=this._tileZoom,!!this._isValidTile(Fe)){var Ae=this._tiles[this._tileCoordsToKey(Fe)];Ae?Ae.current=!0:v.push(Fe)}}if(v.sort(function(be,Yn){return be.distanceTo(h)-Yn.distanceTo(h)}),v.length!==0){this._loading||(this._loading=!0,this.fire("loading"));var at=document.createDocumentFragment();for(q=0;qs.max.x)||!r.wrapLat&&(n.ys.max.y))return!1}if(!this.options.bounds)return!0;var u=this._tileCoordsToBounds(n);return se(this.options.bounds).overlaps(u)},_keyToBounds:function(n){return this._tileCoordsToBounds(this._keyToTileCoords(n))},_tileCoordsToNwSe:function(n){var r=this._map,s=this.getTileSize(),u=n.scaleBy(s),f=u.add(s),h=r.unproject(u,n.z),v=r.unproject(f,n.z);return[h,v]},_tileCoordsToBounds:function(n){var r=this._tileCoordsToNwSe(n),s=new ke(r[0],r[1]);return this.options.noWrap||(s=this._map.wrapLatLngBounds(s)),s},_tileCoordsToKey:function(n){return n.x+":"+n.y+":"+n.z},_keyToTileCoords:function(n){var r=n.split(":"),s=new M(+r[0],+r[1]);return s.z=+r[2],s},_removeTile:function(n){var r=this._tiles[n];r&&(de(r.el),delete this._tiles[n],this.fire("tileunload",{tile:r.el,coords:this._keyToTileCoords(n)}))},_initTile:function(n){Y(n,"leaflet-tile");var r=this.getTileSize();n.style.width=r.x+"px",n.style.height=r.y+"px",n.onselectstart=w,n.onmousemove=w,H.ielt9&&this.options.opacity<1&&ot(n,this.options.opacity)},_addTile:function(n,r){var s=this._getTilePos(n),u=this._tileCoordsToKey(n),f=this.createTile(this._wrapCoords(n),c(this._tileReady,this,n));this._initTile(f),this.createTile.length<2&&ae(c(this._tileReady,this,n,null,f)),xe(f,s),this._tiles[u]={el:f,coords:n,current:!0},r.appendChild(f),this.fire("tileloadstart",{tile:f,coords:n})},_tileReady:function(n,r,s){r&&this.fire("tileerror",{error:r,tile:s,coords:n});var u=this._tileCoordsToKey(n);s=this._tiles[u],s&&(s.loaded=+new Date,this._map._fadeAnimated?(ot(s.el,0),Ce(this._fadeFrame),this._fadeFrame=ae(this._updateOpacity,this)):(s.active=!0,this._pruneTiles()),r||(Y(s.el,"leaflet-tile-loaded"),this.fire("tileload",{tile:s.el,coords:n})),this._noTilesToLoad()&&(this._loading=!1,this.fire("load"),H.ielt9||!this._map._fadeAnimated?ae(this._pruneTiles,this):setTimeout(c(this._pruneTiles,this),250)))},_getTilePos:function(n){return n.scaleBy(this.getTileSize()).subtract(this._level.origin)},_wrapCoords:function(n){var r=new M(this._wrapX?x(n.x,this._wrapX):n.x,this._wrapY?x(n.y,this._wrapY):n.y);return r.z=n.z,r},_pxBoundsToTileRange:function(n){var r=this.getTileSize();return new Q(n.min.unscaleBy(r).floor(),n.max.unscaleBy(r).ceil().subtract([1,1]))},_noTilesToLoad:function(){for(var n in this._tiles)if(!this._tiles[n].loaded)return!1;return!0}});function Km(n){return new Di(n)}var Xn=Di.extend({options:{minZoom:0,maxZoom:18,subdomains:"abc",errorTileUrl:"",zoomOffset:0,tms:!1,zoomReverse:!1,detectRetina:!1,crossOrigin:!1,referrerPolicy:!1},initialize:function(n,r){this._url=n,r=E(this,r),r.detectRetina&&H.retina&&r.maxZoom>0?(r.tileSize=Math.floor(r.tileSize/2),r.zoomReverse?(r.zoomOffset--,r.minZoom=Math.min(r.maxZoom,r.minZoom+1)):(r.zoomOffset++,r.maxZoom=Math.max(r.minZoom,r.maxZoom-1)),r.minZoom=Math.max(0,r.minZoom)):r.zoomReverse?r.minZoom=Math.min(r.maxZoom,r.minZoom):r.maxZoom=Math.max(r.minZoom,r.maxZoom),typeof r.subdomains=="string"&&(r.subdomains=r.subdomains.split("")),this.on("tileunload",this._onTileRemove)},setUrl:function(n,r){return this._url===n&&r===void 0&&(r=!0),this._url=n,r||this.redraw(),this},createTile:function(n,r){var s=document.createElement("img");return G(s,"load",c(this._tileOnLoad,this,r,s)),G(s,"error",c(this._tileOnError,this,r,s)),(this.options.crossOrigin||this.options.crossOrigin==="")&&(s.crossOrigin=this.options.crossOrigin===!0?"":this.options.crossOrigin),typeof this.options.referrerPolicy=="string"&&(s.referrerPolicy=this.options.referrerPolicy),s.alt="",s.src=this.getTileUrl(n),s},getTileUrl:function(n){var r={r:H.retina?"@2x":"",s:this._getSubdomain(n),x:n.x,y:n.y,z:this._getZoomForUrl()};if(this._map&&!this._map.options.crs.infinite){var s=this._globalTileRange.max.y-n.y;this.options.tms&&(r.y=s),r["-y"]=s}return _(this._url,a(r,this.options))},_tileOnLoad:function(n,r){H.ielt9?setTimeout(c(n,this,null,r),0):n(null,r)},_tileOnError:function(n,r,s){var u=this.options.errorTileUrl;u&&r.getAttribute("src")!==u&&(r.src=u),n(s,r)},_onTileRemove:function(n){n.tile.onload=null},_getZoomForUrl:function(){var n=this._tileZoom,r=this.options.maxZoom,s=this.options.zoomReverse,u=this.options.zoomOffset;return s&&(n=r-n),n+u},_getSubdomain:function(n){var r=Math.abs(n.x+n.y)%this.options.subdomains.length;return this.options.subdomains[r]},_abortLoading:function(){var n,r;for(n in this._tiles)if(this._tiles[n].coords.z!==this._tileZoom&&(r=this._tiles[n].el,r.onload=w,r.onerror=w,!r.complete)){r.src=B;var s=this._tiles[n].coords;de(r),delete this._tiles[n],this.fire("tileabort",{tile:r,coords:s})}},_removeTile:function(n){var r=this._tiles[n];if(r)return r.el.setAttribute("src",B),Di.prototype._removeTile.call(this,n)},_tileReady:function(n,r,s){if(!(!this._map||s&&s.getAttribute("src")===B))return Di.prototype._tileReady.call(this,n,r,s)}});function Lc(n,r){return new Xn(n,r)}var Ec=Xn.extend({defaultWmsParams:{service:"WMS",request:"GetMap",layers:"",styles:"",format:"image/jpeg",transparent:!1,version:"1.1.1"},options:{crs:null,uppercase:!1},initialize:function(n,r){this._url=n;var s=a({},this.defaultWmsParams);for(var u in r)u in this.options||(s[u]=r[u]);r=E(this,r);var f=r.detectRetina&&H.retina?2:1,h=this.getTileSize();s.width=h.x*f,s.height=h.y*f,this.wmsParams=s},onAdd:function(n){this._crs=this.options.crs||n.options.crs,this._wmsVersion=parseFloat(this.wmsParams.version);var r=this._wmsVersion>=1.3?"crs":"srs";this.wmsParams[r]=this._crs.code,Xn.prototype.onAdd.call(this,n)},getTileUrl:function(n){var r=this._tileCoordsToNwSe(n),s=this._crs,u=ee(s.project(r[0]),s.project(r[1])),f=u.min,h=u.max,v=(this._wmsVersion>=1.3&&this._crs===gc?[f.y,f.x,h.y,h.x]:[f.x,f.y,h.x,h.y]).join(","),S=Xn.prototype.getTileUrl.call(this,n);return S+j(this.wmsParams,S,this.options.uppercase)+(this.options.uppercase?"&BBOX=":"&bbox=")+v},setParams:function(n,r){return a(this.wmsParams,n),r||this.redraw(),this}});function Gm(n,r){return new Ec(n,r)}Xn.WMS=Ec,Lc.wms=Gm;var jt=_t.extend({options:{padding:.1},initialize:function(n){E(this,n),p(this),this._layers=this._layers||{}},onAdd:function(){this._container||(this._initContainer(),Y(this._container,"leaflet-zoom-animated")),this.getPane().appendChild(this._container),this._update(),this.on("update",this._updatePaths,this)},onRemove:function(){this.off("update",this._updatePaths,this),this._destroyContainer()},getEvents:function(){var n={viewreset:this._reset,zoom:this._onZoom,moveend:this._update,zoomend:this._onZoomEnd};return this._zoomAnimated&&(n.zoomanim=this._onAnimZoom),n},_onAnimZoom:function(n){this._updateTransform(n.center,n.zoom)},_onZoom:function(){this._updateTransform(this._map.getCenter(),this._map.getZoom())},_updateTransform:function(n,r){var s=this._map.getZoomScale(r,this._zoom),u=this._map.getSize().multiplyBy(.5+this.options.padding),f=this._map.project(this._center,r),h=u.multiplyBy(-s).add(f).subtract(this._map._getNewPixelOrigin(n,r));H.any3d?Pn(this._container,h,s):xe(this._container,h)},_reset:function(){this._update(),this._updateTransform(this._center,this._zoom);for(var n in this._layers)this._layers[n]._reset()},_onZoomEnd:function(){for(var n in this._layers)this._layers[n]._project()},_updatePaths:function(){for(var n in this._layers)this._layers[n]._update()},_update:function(){var n=this.options.padding,r=this._map.getSize(),s=this._map.containerPointToLayerPoint(r.multiplyBy(-n)).round();this._bounds=new Q(s,s.add(r.multiplyBy(1+n*2)).round()),this._center=this._map.getCenter(),this._zoom=this._map.getZoom()}}),Cc=jt.extend({options:{tolerance:0},getEvents:function(){var n=jt.prototype.getEvents.call(this);return n.viewprereset=this._onViewPreReset,n},_onViewPreReset:function(){this._postponeUpdatePaths=!0},onAdd:function(){jt.prototype.onAdd.call(this),this._draw()},_initContainer:function(){var n=this._container=document.createElement("canvas");G(n,"mousemove",this._onMouseMove,this),G(n,"click dblclick mousedown mouseup contextmenu",this._onClick,this),G(n,"mouseout",this._handleMouseOut,this),n._leaflet_disable_events=!0,this._ctx=n.getContext("2d")},_destroyContainer:function(){Ce(this._redrawRequest),delete this._ctx,de(this._container),le(this._container),delete this._container},_updatePaths:function(){if(!this._postponeUpdatePaths){var n;this._redrawBounds=null;for(var r in this._layers)n=this._layers[r],n._update();this._redraw()}},_update:function(){if(!(this._map._animatingZoom&&this._bounds)){jt.prototype._update.call(this);var n=this._bounds,r=this._container,s=n.getSize(),u=H.retina?2:1;xe(r,n.min),r.width=u*s.x,r.height=u*s.y,r.style.width=s.x+"px",r.style.height=s.y+"px",H.retina&&this._ctx.scale(2,2),this._ctx.translate(-n.min.x,-n.min.y),this.fire("update")}},_reset:function(){jt.prototype._reset.call(this),this._postponeUpdatePaths&&(this._postponeUpdatePaths=!1,this._updatePaths())},_initPath:function(n){this._updateDashArray(n),this._layers[p(n)]=n;var r=n._order={layer:n,prev:this._drawLast,next:null};this._drawLast&&(this._drawLast.next=r),this._drawLast=r,this._drawFirst=this._drawFirst||this._drawLast},_addPath:function(n){this._requestRedraw(n)},_removePath:function(n){var r=n._order,s=r.next,u=r.prev;s?s.prev=u:this._drawLast=u,u?u.next=s:this._drawFirst=s,delete n._order,delete this._layers[p(n)],this._requestRedraw(n)},_updatePath:function(n){this._extendRedrawBounds(n),n._project(),n._update(),this._requestRedraw(n)},_updateStyle:function(n){this._updateDashArray(n),this._requestRedraw(n)},_updateDashArray:function(n){if(typeof n.options.dashArray=="string"){var r=n.options.dashArray.split(/[, ]+/),s=[],u,f;for(f=0;f')}}catch{}return function(n){return document.createElement("<"+n+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}}(),Xm={_initContainer:function(){this._container=ie("div","leaflet-vml-container")},_update:function(){this._map._animatingZoom||(jt.prototype._update.call(this),this.fire("update"))},_initPath:function(n){var r=n._container=Fi("shape");Y(r,"leaflet-vml-shape "+(this.options.className||"")),r.coordsize="1 1",n._path=Fi("path"),r.appendChild(n._path),this._updateStyle(n),this._layers[p(n)]=n},_addPath:function(n){var r=n._container;this._container.appendChild(r),n.options.interactive&&n.addInteractiveTarget(r)},_removePath:function(n){var r=n._container;de(r),n.removeInteractiveTarget(r),delete this._layers[p(n)]},_updateStyle:function(n){var r=n._stroke,s=n._fill,u=n.options,f=n._container;f.stroked=!!u.stroke,f.filled=!!u.fill,u.stroke?(r||(r=n._stroke=Fi("stroke")),f.appendChild(r),r.weight=u.weight+"px",r.color=u.color,r.opacity=u.opacity,u.dashArray?r.dashStyle=y(u.dashArray)?u.dashArray.join(" "):u.dashArray.replace(/( *, *)/g," "):r.dashStyle="",r.endcap=u.lineCap.replace("butt","flat"),r.joinstyle=u.lineJoin):r&&(f.removeChild(r),n._stroke=null),u.fill?(s||(s=n._fill=Fi("fill")),f.appendChild(s),s.color=u.fillColor||u.color,s.opacity=u.fillOpacity):s&&(f.removeChild(s),n._fill=null)},_updateCircle:function(n){var r=n._point.round(),s=Math.round(n._radius),u=Math.round(n._radiusY||s);this._setPath(n,n._empty()?"M0 0":"AL "+r.x+","+r.y+" "+s+","+u+" 0,"+65535*360)},_setPath:function(n,r){n._path.v=r},_bringToFront:function(n){Hn(n._container)},_bringToBack:function(n){Vn(n._container)}},eo=H.vml?Fi:Nu,Ui=jt.extend({_initContainer:function(){this._container=eo("svg"),this._container.setAttribute("pointer-events","none"),this._rootGroup=eo("g"),this._container.appendChild(this._rootGroup)},_destroyContainer:function(){de(this._container),le(this._container),delete this._container,delete this._rootGroup,delete this._svgSize},_update:function(){if(!(this._map._animatingZoom&&this._bounds)){jt.prototype._update.call(this);var n=this._bounds,r=n.getSize(),s=this._container;(!this._svgSize||!this._svgSize.equals(r))&&(this._svgSize=r,s.setAttribute("width",r.x),s.setAttribute("height",r.y)),xe(s,n.min),s.setAttribute("viewBox",[n.min.x,n.min.y,r.x,r.y].join(" ")),this.fire("update")}},_initPath:function(n){var r=n._path=eo("path");n.options.className&&Y(r,n.options.className),n.options.interactive&&Y(r,"leaflet-interactive"),this._updateStyle(n),this._layers[p(n)]=n},_addPath:function(n){this._rootGroup||this._initContainer(),this._rootGroup.appendChild(n._path),n.addInteractiveTarget(n._path)},_removePath:function(n){de(n._path),n.removeInteractiveTarget(n._path),delete this._layers[p(n)]},_updatePath:function(n){n._project(),n._update()},_updateStyle:function(n){var r=n._path,s=n.options;r&&(s.stroke?(r.setAttribute("stroke",s.color),r.setAttribute("stroke-opacity",s.opacity),r.setAttribute("stroke-width",s.weight),r.setAttribute("stroke-linecap",s.lineCap),r.setAttribute("stroke-linejoin",s.lineJoin),s.dashArray?r.setAttribute("stroke-dasharray",s.dashArray):r.removeAttribute("stroke-dasharray"),s.dashOffset?r.setAttribute("stroke-dashoffset",s.dashOffset):r.removeAttribute("stroke-dashoffset")):r.setAttribute("stroke","none"),s.fill?(r.setAttribute("fill",s.fillColor||s.color),r.setAttribute("fill-opacity",s.fillOpacity),r.setAttribute("fill-rule",s.fillRule||"evenodd")):r.setAttribute("fill","none"))},_updatePoly:function(n,r){this._setPath(n,Ou(n._parts,r))},_updateCircle:function(n){var r=n._point,s=Math.max(Math.round(n._radius),1),u=Math.max(Math.round(n._radiusY),1)||s,f="a"+s+","+u+" 0 1,0 ",h=n._empty()?"M0 0":"M"+(r.x-s)+","+r.y+f+s*2+",0 "+f+-s*2+",0 ";this._setPath(n,h)},_setPath:function(n,r){n._path.setAttribute("d",r)},_bringToFront:function(n){Hn(n._path)},_bringToBack:function(n){Vn(n._path)}});H.vml&&Ui.include(Xm);function Tc(n){return H.svg||H.vml?new Ui(n):null}$.include({getRenderer:function(n){var r=n.options.renderer||this._getPaneRenderer(n.options.pane)||this.options.renderer||this._renderer;return r||(r=this._renderer=this._createRenderer()),this.hasLayer(r)||this.addLayer(r),r},_getPaneRenderer:function(n){if(n==="overlayPane"||n===void 0)return!1;var r=this._paneRenderers[n];return r===void 0&&(r=this._createRenderer({pane:n}),this._paneRenderers[n]=r),r},_createRenderer:function(n){return this.options.preferCanvas&&Ac(n)||Tc(n)}});var Mc=Kn.extend({initialize:function(n,r){Kn.prototype.initialize.call(this,this._boundsToLatLngs(n),r)},setBounds:function(n){return this.setLatLngs(this._boundsToLatLngs(n))},_boundsToLatLngs:function(n){return n=se(n),[n.getSouthWest(),n.getNorthWest(),n.getNorthEast(),n.getSouthEast()]}});function Ym(n,r){return new Mc(n,r)}Ui.create=eo,Ui.pointsToPath=Ou,Bt.geometryToLayer=Kr,Bt.coordsToLatLng=na,Bt.coordsToLatLngs=Gr,Bt.latLngToCoords=ia,Bt.latLngsToCoords=Xr,Bt.getFeature=Gn,Bt.asFeature=Yr,$.mergeOptions({boxZoom:!0});var zc=Et.extend({initialize:function(n){this._map=n,this._container=n._container,this._pane=n._panes.overlayPane,this._resetStateTimeout=0,n.on("unload",this._destroy,this)},addHooks:function(){G(this._container,"mousedown",this._onMouseDown,this)},removeHooks:function(){le(this._container,"mousedown",this._onMouseDown,this)},moved:function(){return this._moved},_destroy:function(){de(this._pane),delete this._pane},_resetState:function(){this._resetStateTimeout=0,this._moved=!1},_clearDeferredResetState:function(){this._resetStateTimeout!==0&&(clearTimeout(this._resetStateTimeout),this._resetStateTimeout=0)},_onMouseDown:function(n){if(!n.shiftKey||n.which!==1&&n.button!==1)return!1;this._clearDeferredResetState(),this._resetState(),Ni(),Ds(),this._startPoint=this._map.mouseEventToContainerPoint(n),G(document,{contextmenu:Ln,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseMove:function(n){this._moved||(this._moved=!0,this._box=ie("div","leaflet-zoom-box",this._container),Y(this._container,"leaflet-crosshair"),this._map.fire("boxzoomstart")),this._point=this._map.mouseEventToContainerPoint(n);var r=new Q(this._point,this._startPoint),s=r.getSize();xe(this._box,r.min),this._box.style.width=s.x+"px",this._box.style.height=s.y+"px"},_finish:function(){this._moved&&(de(this._box),ye(this._container,"leaflet-crosshair")),Oi(),Fs(),le(document,{contextmenu:Ln,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseUp:function(n){if(!(n.which!==1&&n.button!==1)&&(this._finish(),!!this._moved)){this._clearDeferredResetState(),this._resetStateTimeout=setTimeout(c(this._resetState,this),0);var r=new ke(this._map.containerPointToLatLng(this._startPoint),this._map.containerPointToLatLng(this._point));this._map.fitBounds(r).fire("boxzoomend",{boxZoomBounds:r})}},_onKeyDown:function(n){n.keyCode===27&&(this._finish(),this._clearDeferredResetState(),this._resetState())}});$.addInitHook("addHandler","boxZoom",zc),$.mergeOptions({doubleClickZoom:!0});var Nc=Et.extend({addHooks:function(){this._map.on("dblclick",this._onDoubleClick,this)},removeHooks:function(){this._map.off("dblclick",this._onDoubleClick,this)},_onDoubleClick:function(n){var r=this._map,s=r.getZoom(),u=r.options.zoomDelta,f=n.originalEvent.shiftKey?s-u:s+u;r.options.doubleClickZoom==="center"?r.setZoom(f):r.setZoomAround(n.containerPoint,f)}});$.addInitHook("addHandler","doubleClickZoom",Nc),$.mergeOptions({dragging:!0,inertia:!0,inertiaDeceleration:3400,inertiaMaxSpeed:1/0,easeLinearity:.2,worldCopyJump:!1,maxBoundsViscosity:0});var Oc=Et.extend({addHooks:function(){if(!this._draggable){var n=this._map;this._draggable=new Xt(n._mapPane,n._container),this._draggable.on({dragstart:this._onDragStart,drag:this._onDrag,dragend:this._onDragEnd},this),this._draggable.on("predrag",this._onPreDragLimit,this),n.options.worldCopyJump&&(this._draggable.on("predrag",this._onPreDragWrap,this),n.on("zoomend",this._onZoomEnd,this),n.whenReady(this._onZoomEnd,this))}Y(this._map._container,"leaflet-grab leaflet-touch-drag"),this._draggable.enable(),this._positions=[],this._times=[]},removeHooks:function(){ye(this._map._container,"leaflet-grab"),ye(this._map._container,"leaflet-touch-drag"),this._draggable.disable()},moved:function(){return this._draggable&&this._draggable._moved},moving:function(){return this._draggable&&this._draggable._moving},_onDragStart:function(){var n=this._map;if(n._stop(),this._map.options.maxBounds&&this._map.options.maxBoundsViscosity){var r=se(this._map.options.maxBounds);this._offsetLimit=ee(this._map.latLngToContainerPoint(r.getNorthWest()).multiplyBy(-1),this._map.latLngToContainerPoint(r.getSouthEast()).multiplyBy(-1).add(this._map.getSize())),this._viscosity=Math.min(1,Math.max(0,this._map.options.maxBoundsViscosity))}else this._offsetLimit=null;n.fire("movestart").fire("dragstart"),n.options.inertia&&(this._positions=[],this._times=[])},_onDrag:function(n){if(this._map.options.inertia){var r=this._lastTime=+new Date,s=this._lastPos=this._draggable._absPos||this._draggable._newPos;this._positions.push(s),this._times.push(r),this._prunePositions(r)}this._map.fire("move",n).fire("drag",n)},_prunePositions:function(n){for(;this._positions.length>1&&n-this._times[0]>50;)this._positions.shift(),this._times.shift()},_onZoomEnd:function(){var n=this._map.getSize().divideBy(2),r=this._map.latLngToLayerPoint([0,0]);this._initialWorldOffset=r.subtract(n).x,this._worldWidth=this._map.getPixelWorldBounds().getSize().x},_viscousLimit:function(n,r){return n-(n-r)*this._viscosity},_onPreDragLimit:function(){if(!(!this._viscosity||!this._offsetLimit)){var n=this._draggable._newPos.subtract(this._draggable._startPos),r=this._offsetLimit;n.xr.max.x&&(n.x=this._viscousLimit(n.x,r.max.x)),n.y>r.max.y&&(n.y=this._viscousLimit(n.y,r.max.y)),this._draggable._newPos=this._draggable._startPos.add(n)}},_onPreDragWrap:function(){var n=this._worldWidth,r=Math.round(n/2),s=this._initialWorldOffset,u=this._draggable._newPos.x,f=(u-r+s)%n+r-s,h=(u+r+s)%n-r-s,v=Math.abs(f+s)0?h:-h))-r;this._delta=0,this._startTime=null,v&&(n.options.scrollWheelZoom==="center"?n.setZoom(r+v):n.setZoomAround(this._lastMousePos,r+v))}});$.addInitHook("addHandler","scrollWheelZoom",Rc);var qm=600;$.mergeOptions({tapHold:H.touchNative&&H.safari&&H.mobile,tapTolerance:15});var Bc=Et.extend({addHooks:function(){G(this._map._container,"touchstart",this._onDown,this)},removeHooks:function(){le(this._map._container,"touchstart",this._onDown,this)},_onDown:function(n){if(clearTimeout(this._holdTimeout),n.touches.length===1){var r=n.touches[0];this._startPos=this._newPos=new M(r.clientX,r.clientY),this._holdTimeout=setTimeout(c(function(){this._cancel(),this._isTapValid()&&(G(document,"touchend",Ne),G(document,"touchend touchcancel",this._cancelClickPrevent),this._simulateEvent("contextmenu",r))},this),qm),G(document,"touchend touchcancel contextmenu",this._cancel,this),G(document,"touchmove",this._onMove,this)}},_cancelClickPrevent:function n(){le(document,"touchend",Ne),le(document,"touchend touchcancel",n)},_cancel:function(){clearTimeout(this._holdTimeout),le(document,"touchend touchcancel contextmenu",this._cancel,this),le(document,"touchmove",this._onMove,this)},_onMove:function(n){var r=n.touches[0];this._newPos=new M(r.clientX,r.clientY)},_isTapValid:function(){return this._newPos.distanceTo(this._startPos)<=this._map.options.tapTolerance},_simulateEvent:function(n,r){var s=new MouseEvent(n,{bubbles:!0,cancelable:!0,view:window,screenX:r.screenX,screenY:r.screenY,clientX:r.clientX,clientY:r.clientY});s._simulated=!0,r.target.dispatchEvent(s)}});$.addInitHook("addHandler","tapHold",Bc),$.mergeOptions({touchZoom:H.touch,bounceAtZoomLimits:!0});var jc=Et.extend({addHooks:function(){Y(this._map._container,"leaflet-touch-zoom"),G(this._map._container,"touchstart",this._onTouchStart,this)},removeHooks:function(){ye(this._map._container,"leaflet-touch-zoom"),le(this._map._container,"touchstart",this._onTouchStart,this)},_onTouchStart:function(n){var r=this._map;if(!(!n.touches||n.touches.length!==2||r._animatingZoom||this._zooming)){var s=r.mouseEventToContainerPoint(n.touches[0]),u=r.mouseEventToContainerPoint(n.touches[1]);this._centerPoint=r.getSize()._divideBy(2),this._startLatLng=r.containerPointToLatLng(this._centerPoint),r.options.touchZoom!=="center"&&(this._pinchStartLatLng=r.containerPointToLatLng(s.add(u)._divideBy(2))),this._startDist=s.distanceTo(u),this._startZoom=r.getZoom(),this._moved=!1,this._zooming=!0,r._stop(),G(document,"touchmove",this._onTouchMove,this),G(document,"touchend touchcancel",this._onTouchEnd,this),Ne(n)}},_onTouchMove:function(n){if(!(!n.touches||n.touches.length!==2||!this._zooming)){var r=this._map,s=r.mouseEventToContainerPoint(n.touches[0]),u=r.mouseEventToContainerPoint(n.touches[1]),f=s.distanceTo(u)/this._startDist;if(this._zoom=r.getScaleZoom(f,this._startZoom),!r.options.bounceAtZoomLimits&&(this._zoomr.getMaxZoom()&&f>1)&&(this._zoom=r._limitZoom(this._zoom)),r.options.touchZoom==="center"){if(this._center=this._startLatLng,f===1)return}else{var h=s._add(u)._divideBy(2)._subtract(this._centerPoint);if(f===1&&h.x===0&&h.y===0)return;this._center=r.unproject(r.project(this._pinchStartLatLng,this._zoom).subtract(h),this._zoom)}this._moved||(r._moveStart(!0,!1),this._moved=!0),Ce(this._animRequest);var v=c(r._move,r,this._center,this._zoom,{pinch:!0,round:!1},void 0);this._animRequest=ae(v,this,!0),Ne(n)}},_onTouchEnd:function(){if(!this._moved||!this._zooming){this._zooming=!1;return}this._zooming=!1,Ce(this._animRequest),le(document,"touchmove",this._onTouchMove,this),le(document,"touchend touchcancel",this._onTouchEnd,this),this._map.options.zoomAnimation?this._map._animateZoom(this._center,this._map._limitZoom(this._zoom),!0,this._map.options.zoomSnap):this._map._resetView(this._center,this._map._limitZoom(this._zoom))}});$.addInitHook("addHandler","touchZoom",jc),$.BoxZoom=zc,$.DoubleClickZoom=Nc,$.Drag=Oc,$.Keyboard=Ic,$.ScrollWheelZoom=Rc,$.TapHold=Bc,$.TouchZoom=jc,i.Bounds=Q,i.Browser=H,i.CRS=Qe,i.Canvas=Cc,i.Circle=ta,i.CircleMarker=br,i.Class=rt,i.Control=mt,i.DivIcon=kc,i.DivOverlay=Ct,i.DomEvent=mm,i.DomUtil=dm,i.Draggable=Xt,i.Evented=Ot,i.FeatureGroup=It,i.GeoJSON=Bt,i.GridLayer=Di,i.Handler=Et,i.Icon=bn,i.ImageOverlay=qr,i.LatLng=ne,i.LatLngBounds=ke,i.Layer=_t,i.LayerGroup=Qn,i.LineUtil=Am,i.Map=$,i.Marker=Qr,i.Mixin=Pm,i.Path=Yt,i.Point=M,i.PolyUtil=Sm,i.Polygon=Kn,i.Polyline=Rt,i.Popup=Jr,i.PosAnimation=sc,i.Projection=Tm,i.Rectangle=Mc,i.Renderer=jt,i.SVG=Ui,i.SVGOverlay=Sc,i.TileLayer=Xn,i.Tooltip=$r,i.Transformation=Cs,i.Util=xn,i.VideoOverlay=Pc,i.bind=c,i.bounds=ee,i.canvas=Ac,i.circle=jm,i.circleMarker=Bm,i.control=Bi,i.divIcon=bm,i.extend=a,i.featureGroup=Om,i.geoJSON=xc,i.geoJson=Fm,i.gridLayer=Km,i.icon=Im,i.imageOverlay=Um,i.latLng=K,i.latLngBounds=se,i.layerGroup=Nm,i.map=_m,i.marker=Rm,i.point=R,i.polygon=Dm,i.polyline=Zm,i.popup=Vm,i.rectangle=Ym,i.setOptions=E,i.stamp=p,i.svg=Tc,i.svgOverlay=Hm,i.tileLayer=Lc,i.tooltip=Qm,i.transformation=Ai,i.version=o,i.videoOverlay=Wm;var Jm=window.L;i.noConflict=function(){return window.L=Jm,this},window.L=i})})(zl,zl.exports);var ks=zl.exports;function Tu(e,t,i){return Object.freeze({instance:e,context:t,container:i})}function Mu(e,t){return t==null?function(o,a){const l=O.useRef();return l.current||(l.current=e(o,a)),l}:function(o,a){const l=O.useRef();l.current||(l.current=e(o,a));const c=O.useRef(o),{instance:d}=l.current;return O.useEffect(function(){c.current!==o&&(t(d,o,c.current),c.current=o)},[d,o,a]),l}}function Vy(e,t){O.useEffect(function(){return(t.layerContainer??t.map).addLayer(e.instance),function(){var l;(l=t.layerContainer)==null||l.removeLayer(e.instance),t.map.removeLayer(e.instance)}},[t,e])}function Bp(e){return function(i){const o=Ip(),a=e(Au(i,o),o);return zp(o.map,i.attribution),Rp(a.current,i.eventHandlers),Vy(a.current,o),a}}function Qy(e,t){const i=Mu(e,t),o=Bp(i);return Fy(o)}function by(e,t){const i=Mu(e),o=Hy(i,t);return Uy(o)}function Ky(e,t){const i=Mu(e,t),o=Bp(i);return Wy(o)}function Gy(e,t,i){const{opacity:o,zIndex:a}=t;o!=null&&o!==i.opacity&&e.setOpacity(o),a!=null&&a!==i.zIndex&&e.setZIndex(a)}function Nl(){return Nl=Object.assign||function(e){for(var t=1;t(C==null?void 0:C.map)??null,[C]);const E=O.useCallback(g=>{if(g!==null&&C===null){const _=new ks.Map(g,x);i!=null&&m!=null?_.setView(i,m):e!=null&&_.fitBounds(e,t),p!=null&&_.whenReady(p),A(Zy(_))}},[]);O.useEffect(()=>()=>{C==null||C.map.remove()},[C]);const j=C?cr.createElement(Op,{value:C},o):c??null;return cr.createElement("div",Nl({},P,{ref:E}),j)}const Yy=O.forwardRef(Xy),qy=Qy(function({position:t,...i},o){const a=new ks.Marker(t,i);return Tu(a,Dy(o,{overlayContainer:a}))},function(t,i,o){i.position!==o.position&&t.setLatLng(i.position),i.icon!=null&&i.icon!==o.icon&&t.setIcon(i.icon),i.zIndexOffset!=null&&i.zIndexOffset!==o.zIndexOffset&&t.setZIndexOffset(i.zIndexOffset),i.opacity!=null&&i.opacity!==o.opacity&&t.setOpacity(i.opacity),t.dragging!=null&&i.draggable!==o.draggable&&(i.draggable===!0?t.dragging.enable():t.dragging.disable())}),Jy=by(function(t,i){const o=new ks.Popup(t,i.overlayContainer);return Tu(o,i)},function(t,i,{position:o},a){O.useEffect(function(){const{instance:c}=t;function d(m){m.popup===c&&(c.update(),a(!0))}function p(m){m.popup===c&&a(!1)}return i.map.on({popupopen:d,popupclose:p}),i.overlayContainer==null?(o!=null&&c.setLatLng(o),c.openOn(i.map)):i.overlayContainer.bindPopup(c),function(){var x;i.map.off({popupopen:d,popupclose:p}),(x=i.overlayContainer)==null||x.unbindPopup(),i.map.removeLayer(c)}},[t,i,a,o])}),$y=Ky(function({url:t,...i},o){const a=new ks.TileLayer(t,Au(i,o));return Tu(a,o)},function(t,i,o){Gy(t,i,o);const{url:a}=i;a!=null&&a!==o.url&&t.setUrl(a)}),e0=()=>{const e=[38.625951106773876,-.5766300334862065];return N.jsxs(Yy,{center:e,zoom:20,style:{height:"400px",width:"100%"},children:[N.jsx($y,{url:"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",attribution:'© OpenStreetMap contributors'}),N.jsx(qy,{position:e,children:N.jsx(Jy,{children:"Ubicación del marcador."})})]})};function lt(e){return console.log(e.tittle),N.jsxs("div",{className:"modal",children:[N.jsx("img",{className:"imgModal",src:e.img,alt:"modal img"}),N.jsx("h3",{children:e.tittle}),N.jsx("p",{children:e.value})]})}const rh=({phoneNumber:e,message:t})=>{const i=()=>{const o=`https://wa.me/${e}?text=${encodeURIComponent(t)}`;window.open(o,"_blank")};return N.jsxs("button",{className:"btn",onClick:i,children:[" ",N.jsx("img",{className:"whatsapp",src:"../../img/whatsapp.png",alt:"whatsapp"})]})};function t0(){return N.jsxs("main",{children:[N.jsxs("div",{className:"body",children:[N.jsxs("div",{className:"portada",children:[N.jsxs("div",{className:"textOver",children:[N.jsx("h2",{className:"fornMariu",children:"FORN MARIU"}),N.jsx(ur,{to:"/panes",children:N.jsx("button",{className:"btnCart",children:"Ver panes"})})]}),N.jsx("img",{src:"../../img/portada.png",alt:"panetone"})]}),N.jsxs("div",{className:"contact",children:[N.jsx("p",{children:"Ponte en contanto"}),N.jsx(rh,{phoneNumber:"1234567890",message:"Hola, estoy interesado en tu producto."})]}),N.jsxs("div",{className:"location",children:[N.jsx("p",{children:"Donde encontrarnos?"}),N.jsx(e0,{})]}),N.jsxs("div",{className:"text",children:[N.jsx("h1",{children:"Forners desde 1943"}),N.jsx("p",{children:"Forners de 4ª generació. Coneix un nou concepte de panadería. Pa natural sense additius i fermentacions llargues amb masa mare de cultiu. Vine a conèixer-nos a Ibi, Alacant, i gaudeix de pa i dolços tradicionals elaborats artesanalment."}),N.jsx(ur,{to:"/panes",children:N.jsx("button",{className:"btnCart",children:"Ver panes"})})]}),N.jsxs("div",{className:"modals",children:[N.jsx(lt,{tittle:"¿Qué nos diferencia?",value:"Panaderos de 4ª generación. Conoce un nuevo concepto de panadería. Pan natural sin aditivos y fermentaciones largas con masa madre de cultivo.",img:"https://scontent.fvlc6-1.fna.fbcdn.net/v/t39.30808-6/279969722_151101234109555_1728276028996544313_n.jpg?_nc_cat=108&ccb=1-7&_nc_sid=c83dfd&_nc_ohc=AN6qwmWZFjgAX9MDRmJ&_nc_ht=scontent.fvlc6-1.fna&oh=00_AfAkQYQvoOFebl2sjH47EQ_WnQNgB_Zdiyd4wbKogWWOfg&oe=65AA9F2B"}),N.jsx(lt,{tittle:"Conócenos",value:"Conócenos en Ibi, Alicante, y disfruta de pan y dulces tradicionales elaborados artesanalmente.",img:"https://scontent.fvlc6-1.fna.fbcdn.net/v/t39.30808-6/311125434_184850664068222_5591172718944745341_n.jpg?_nc_cat=104&ccb=1-7&_nc_sid=3635dc&_nc_ohc=v8Q7WDvin-gAX-9Kgnt&_nc_ht=scontent.fvlc6-1.fna&oh=00_AfCphsfcZN_kEq-vQkTqUDDsU-P9VNs7PjP0PPG4EsW_Og&oe=65AB11B5"})]}),N.jsxs("div",{className:"dates",children:[N.jsxs("div",{className:" imgContact",children:[N.jsx("h3",{children:"Teléfono"}),N.jsx("h2",{children:"722 848 892"}),N.jsx("a",{href:"https://m.facebook.com/FornMariu/?fref=tag&__nodl&refsrc=deprecated&ref=external%3Awww.google.com&_rdr/%22",children:N.jsx("img",{src:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMwAAADACAMAAAB/Pny7AAAAb1BMVEUYd/L///8AcfIAa/KXtvhdlfQAc/EAb/JMjPPZ5PxxnfVnmfXu8/5/p/b8/f8AbPEAZ/EAZPH1+P/m7v6Wuvvg6/6vyfuNsPchfPS70PxFiPVXkfaFsPrM3/6ivvjK2fvB1fwwg/V1o/eqw/kAXvAhGp/VAAAF2UlEQVR4nO2dW3eiMBRGA0gi95uAipdB+/9/44jWlkJAKTnkpCv7YV5mWbNXSIi5fcQYJAssSpBBrSAbLjEZ+g9/E0Wyi84jijb+RJl0t49lF3uIeL9Lp8g4JWOyyzwMY6Xzvsyuwtda2lCr2r0rsyGIq+UBI5u3ZNKAoa6WB5QF/YbTk8k99NXygHn5K5m8MmWX8l3MqmvTkXHWitRLA1s7YzJOhfJFOURUOcMyuWfJLt80rJ/tpi3jB2jf+kPEgT8gs1LO5Waz4ssUij1jD6yCJ+OYCrwr+1DT4cjsFeqU27B9X+agVKfcJjp0ZY5EyYesgZJjR0adUUwfs/opc5JdoHmc2jKZyhXTVE3WklG8Yp5Vc5fJbaUr5lY1dv4lUyzak1GTMRZFt3+YaVIxX02Lp0zmLvW+pCxOWG27waEsy0Nw8ex1TeIktiI2z4q52afMeZmBDLWSOiiOTp75ftrg+36W5Y5z/HddXfbmR/z7YlDz/JBJyyVe/uxje8r9N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pm+kasHi293+Sb1fGfaZMeF7q3UaZvpB0qbxLX2f5JS1XHfaZUeHbkNtOB/eFg8K7u/yRepUPtMmOw142wgf3hTeBe+wm9Qp7GZLLPWNHzQ84LB6fkdxGWZU+0/f7KrP5X+4L56Ov7jH+XX3j9lVn8oecE9HX9w/l1d4FqrP5Q84J6NyO4fy6u8yKeyyHXUSBo+y3WVs1aU3xsZGzNXVBG4p4IoGBkTQG8669VMKltBGjOcpPdnsqmIQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQBAEAQEICUAQBAEAQH//Z",alt:"instagram"})})]}),N.jsxs("div",{children:[N.jsx("h3",{children:"HORARIO"}),N.jsx("p",{children:"De M a S de 8:00 a 14:30"}),N.jsx("p",{children:"fornmariu@gmail.com"})]}),N.jsxs("div",{children:[N.jsx("h3",{children:"DONDE ESTAMOS"}),N.jsx("p",{children:"Carrer Riu de les Caixes, 61"}),N.jsx("p",{children:"03440 · IBI · Alicante"})]})]})]}),N.jsx("div",{className:"whatsappContainer",children:N.jsx(rh,{})})]})}function n0(){return N.jsx("footer",{children:N.jsx("p",{className:"pFooter",children:"©2024 Mariu. Todos los derechos reservados. Realizado por APM Creative"})})}function i0(){return N.jsxs(N.Fragment,{children:[N.jsx(Mp,{}),N.jsx(t0,{}),N.jsx(n0,{})]})}function r0(){return N.jsxs(N.Fragment,{children:[N.jsx(Mp,{}),N.jsx("h2",{children:"panes 1 "}),N.jsxs("div",{className:"products",children:[N.jsx(lt,{tittle:"¿Qué nos diferencia?",value:"Panaderos de 4ª generación. Conoce un nuevo concepto de panadería. Pan natural sin aditivos y fermentaciones largas con masa madre de cultivo.",img:"https://scontent.fvlc6-1.fna.fbcdn.net/v/t39.30808-6/273677386_126383796581299_8512067019765521045_n.jpg?_nc_cat=105&ccb=1-7&_nc_sid=dd5e9f&_nc_ohc=MvpA4g00D44AX9ZQp6C&_nc_ht=scontent.fvlc6-1.fna&oh=00_AfDBhp8lSbTyJk-neZaxCIv8c1ERNsNFRj6uYK80TEDoLg&oe=65AC08D1"}),N.jsx(lt,{tittle:"¿Qué nos diferencia?",value:"Panaderos de 4ª generación. Conoce un nuevo concepto de panadería. Pan natural sin aditivos y fermentaciones largas con masa madre de cultivo.",img:"https://scontent.fvlc6-1.fna.fbcdn.net/v/t39.30808-6/310330997_184274107459211_2320124158226812286_n.jpg?stp=dst-jpg_p206x206&_nc_cat=101&ccb=1-7&_nc_sid=3d9721&_nc_ohc=szr7GQOY63EAX838cn0&_nc_ht=scontent.fvlc6-1.fna&oh=00_AfD_zkVOSNygGxHatgP8MpjCKjjMysNa56dcx0oRqKFb3A&oe=65A998DF"}),N.jsx(lt,{tittle:"¿Qué nos diferencia?",value:"Panaderos de 4ª generación. Conoce un nuevo concepto de panadería. Pan natural sin aditivos y fermentaciones largas con masa madre de cultivo.",img:"https://scontent.fvlc6-1.fna.fbcdn.net/v/t39.30808-6/279969722_151101234109555_1728276028996544313_n.jpg?_nc_cat=108&ccb=1-7&_nc_sid=c83dfd&_nc_ohc=AN6qwmWZFjgAX9MDRmJ&_nc_ht=scontent.fvlc6-1.fna&oh=00_AfAkQYQvoOFebl2sjH47EQ_WnQNgB_Zdiyd4wbKogWWOfg&oe=65AA9F2B"}),N.jsx(lt,{tittle:"¿Qué nos diferencia?",value:"Panaderos de 4ª generación. Conoce un nuevo concepto de panadería. Pan natural sin aditivos y fermentaciones largas con masa madre de cultivo.",img:"https://scontent.fvlc6-1.fna.fbcdn.net/v/t39.30808-6/279969722_151101234109555_1728276028996544313_n.jpg?_nc_cat=108&ccb=1-7&_nc_sid=c83dfd&_nc_ohc=AN6qwmWZFjgAX9MDRmJ&_nc_ht=scontent.fvlc6-1.fna&oh=00_AfAkQYQvoOFebl2sjH47EQ_WnQNgB_Zdiyd4wbKogWWOfg&oe=65AA9F2B"}),N.jsx(lt,{tittle:"¿Qué nos diferencia?",value:"Panaderos de 4ª generación. Conoce un nuevo concepto de panadería. Pan natural sin aditivos y fermentaciones largas con masa madre de cultivo.",img:"https://scontent.fvlc6-1.fna.fbcdn.net/v/t39.30808-6/279969722_151101234109555_1728276028996544313_n.jpg?_nc_cat=108&ccb=1-7&_nc_sid=c83dfd&_nc_ohc=AN6qwmWZFjgAX9MDRmJ&_nc_ht=scontent.fvlc6-1.fna&oh=00_AfAkQYQvoOFebl2sjH47EQ_WnQNgB_Zdiyd4wbKogWWOfg&oe=65AA9F2B"})]}),N.jsx("h2",{children:"INTEGRALES"}),N.jsxs("div",{className:"products",children:[N.jsx(lt,{tittle:"¿Qué nos diferencia?",value:"Panaderos de 4ª generación. Conoce un nuevo concepto de panadería. Pan natural sin aditivos y fermentaciones largas con masa madre de cultivo.",img:"https://scontent.fvlc6-2.fna.fbcdn.net/v/t39.30808-6/271905491_116415897578089_2773209203287644740_n.jpg?_nc_cat=100&ccb=1-7&_nc_sid=dd5e9f&_nc_ohc=6IMBnqHGhYgAX_gHV8l&_nc_ht=scontent.fvlc6-2.fna&oh=00_AfCe3eB0GEZriv1Mwk8yxW6LYwmvGkh0QdhZWJwFqEfTig&oe=65AA89BA"}),N.jsx(lt,{tittle:"¿Qué nos diferencia?",value:"Panaderos de 4ª generación. Conoce un nuevo concepto de panadería. Pan natural sin aditivos y fermentaciones largas con masa madre de cultivo.",img:"https://scontent.fvlc6-1.fna.fbcdn.net/v/t39.30808-6/282996562_155205863699092_3681715623234006653_n.jpg?_nc_cat=108&ccb=1-7&_nc_sid=c83dfd&_nc_ohc=u6khBqkHEI4AX9sgf3f&_nc_ht=scontent.fvlc6-1.fna&oh=00_AfCtaM_3eEKsH1FD8RcMsAF8H7lxmjAnuSzhNC8QwvDb9Q&oe=65AADB4E"}),N.jsx(lt,{tittle:"¿Qué nos diferencia?",value:"Panaderos de 4ª generación. Conoce un nuevo concepto de panadería. Pan natural sin aditivos y fermentaciones largas con masa madre de cultivo.",img:"https://scontent.fvlc6-2.fna.fbcdn.net/v/t39.30808-6/283154191_155205867032425_3018415170667786642_n.jpg?stp=c0.17.206.206a_dst-jpg_p206x206&_nc_cat=107&ccb=1-7&_nc_sid=3d9721&_nc_ohc=qaLNp4RSN_0AX8edEKb&_nc_ht=scontent.fvlc6-2.fna&oh=00_AfDmcLbanWRk33NYWerI9letT2Y3uD5vnrMB0IxxKLAioQ&oe=65AB0305"}),N.jsx(lt,{tittle:"¿Qué nos diferencia?",value:"Panaderos de 4ª generación. Conoce un nuevo concepto de panadería. Pan natural sin aditivos y fermentaciones largas con masa madre de cultivo.",img:"https://scontent.fvlc6-1.fna.fbcdn.net/v/t39.30808-6/279969722_151101234109555_1728276028996544313_n.jpg?_nc_cat=108&ccb=1-7&_nc_sid=c83dfd&_nc_ohc=AN6qwmWZFjgAX9MDRmJ&_nc_ht=scontent.fvlc6-1.fna&oh=00_AfAkQYQvoOFebl2sjH47EQ_WnQNgB_Zdiyd4wbKogWWOfg&oe=65AA9F2B"}),N.jsx(lt,{tittle:"¿Qué nos diferencia?",value:"Panaderos de 4ª generación. Conoce un nuevo concepto de panadería. Pan natural sin aditivos y fermentaciones largas con masa madre de cultivo.",img:"https://scontent.fvlc6-1.fna.fbcdn.net/v/t39.30808-6/279969722_151101234109555_1728276028996544313_n.jpg?_nc_cat=108&ccb=1-7&_nc_sid=c83dfd&_nc_ohc=AN6qwmWZFjgAX9MDRmJ&_nc_ht=scontent.fvlc6-1.fna&oh=00_AfAkQYQvoOFebl2sjH47EQ_WnQNgB_Zdiyd4wbKogWWOfg&oe=65AA9F2B"})]})]})}function o0(){return N.jsx(N.Fragment,{children:N.jsx(My,{children:N.jsxs(Sy,{children:[N.jsx(Al,{path:"/marielWebPage.github.io",element:N.jsx(i0,{})}),N.jsx(Al,{path:"/marielWebPage.github.io/panes",element:N.jsx(r0,{})})]})})})}Oa.createRoot(document.getElementById("root")).render(N.jsx(cr.StrictMode,{children:N.jsx(o0,{})})); diff --git a/dist/index.html b/dist/index.html new file mode 100644 index 0000000..972c8ce --- /dev/null +++ b/dist/index.html @@ -0,0 +1,18 @@ + + + + + + + Forn Mariu + + + + +
+ + diff --git a/dist/vite.svg b/dist/vite.svg new file mode 100644 index 0000000..e7b8dfb --- /dev/null +++ b/dist/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/node_modules/.cache/gh-pages/git@github.com!bobgus39!marielWebPage.github.io.git b/node_modules/.cache/gh-pages/git@github.com!bobgus39!marielWebPage.github.io.git index 8cf4a07..9b1915c 160000 --- a/node_modules/.cache/gh-pages/git@github.com!bobgus39!marielWebPage.github.io.git +++ b/node_modules/.cache/gh-pages/git@github.com!bobgus39!marielWebPage.github.io.git @@ -1 +1 @@ -Subproject commit 8cf4a07f1628ca925b60e2def82abf657d5b9322 +Subproject commit 9b1915c91518227b8b24bdcc8e8cf4d9641499dc diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs b/node_modules/@ampproject/remapping/dist/remapping.mjs new file mode 100644 index 0000000..b5edded --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs @@ -0,0 +1,191 @@ +import { decodedMappings, traceSegment, TraceMap } from '@jridgewell/trace-mapping'; +import { GenMapping, maybeAddSegment, setSourceContent, toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping'; + +const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null); +const EMPTY_SOURCES = []; +function SegmentObject(source, line, column, name, content) { + return { source, line, column, name, content }; +} +function Source(map, sources, source, content) { + return { + map, + sources, + source, + content, + }; +} +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +function MapSource(map, sources) { + return Source(map, sources, '', null); +} +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +function OriginalSource(source, content) { + return Source(null, EMPTY_SOURCES, source, content); +} +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +function traceMappings(tree) { + // TODO: Eventually support sourceRoot, which has to be removed because the sources are already + // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. + const gen = new GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + const { column, line, name, content, source } = traced; + maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) + setSourceContent(gen, source, content); + } + } + return gen; +} +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content); + } + const segment = traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); +} + +function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; +} +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; +} +function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + return OriginalSource(source, sourceContent); + }); + return MapSource(map, children); +} + +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } +} + +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); +} + +export { remapping as default }; +//# sourceMappingURL=remapping.mjs.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs.map b/node_modules/@ampproject/remapping/dist/remapping.mjs.map new file mode 100644 index 0000000..078a2b7 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.mjs","sources":["../src/source-map-tree.ts","../src/build-source-map-tree.ts","../src/source-map.ts","../src/remapping.ts"],"sourcesContent":["import { GenMapping, maybeAddSegment, setSourceContent } from '@jridgewell/gen-mapping';\nimport { traceSegment, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport type { TraceMap } from '@jridgewell/trace-mapping';\n\nexport type SourceMapSegmentObject = {\n column: number;\n line: number;\n name: string;\n source: string;\n content: string | null;\n};\n\nexport type OriginalSource = {\n map: null;\n sources: Sources[];\n source: string;\n content: string | null;\n};\n\nexport type MapSource = {\n map: TraceMap;\n sources: Sources[];\n source: string;\n content: null;\n};\n\nexport type Sources = OriginalSource | MapSource;\n\nconst SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null);\nconst EMPTY_SOURCES: Sources[] = [];\n\nfunction SegmentObject(\n source: string,\n line: number,\n column: number,\n name: string,\n content: string | null\n): SourceMapSegmentObject {\n return { source, line, column, name, content };\n}\n\nfunction Source(map: TraceMap, sources: Sources[], source: '', content: null): MapSource;\nfunction Source(\n map: null,\n sources: Sources[],\n source: string,\n content: string | null\n): OriginalSource;\nfunction Source(\n map: TraceMap | null,\n sources: Sources[],\n source: string | '',\n content: string | null\n): Sources {\n return {\n map,\n sources,\n source,\n content,\n } as any;\n}\n\n/**\n * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes\n * (which may themselves be SourceMapTrees).\n */\nexport function MapSource(map: TraceMap, sources: Sources[]): MapSource {\n return Source(map, sources, '', null);\n}\n\n/**\n * A \"leaf\" node in the sourcemap tree, representing an original, unmodified source file. Recursive\n * segment tracing ends at the `OriginalSource`.\n */\nexport function OriginalSource(source: string, content: string | null): OriginalSource {\n return Source(null, EMPTY_SOURCES, source, content);\n}\n\n/**\n * traceMappings is only called on the root level SourceMapTree, and begins the process of\n * resolving each mapping in terms of the original source files.\n */\nexport function traceMappings(tree: MapSource): GenMapping {\n // TODO: Eventually support sourceRoot, which has to be removed because the sources are already\n // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.\n const gen = new GenMapping({ file: tree.map.file });\n const { sources: rootSources, map } = tree;\n const rootNames = map.names;\n const rootMappings = decodedMappings(map);\n\n for (let i = 0; i < rootMappings.length; i++) {\n const segments = rootMappings[i];\n\n for (let j = 0; j < segments.length; j++) {\n const segment = segments[j];\n const genCol = segment[0];\n let traced: SourceMapSegmentObject | null = SOURCELESS_MAPPING;\n\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length !== 1) {\n const source = rootSources[segment[1]];\n traced = originalPositionFor(\n source,\n segment[2],\n segment[3],\n segment.length === 5 ? rootNames[segment[4]] : ''\n );\n\n // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a\n // respective segment into an original source.\n if (traced == null) continue;\n }\n\n const { column, line, name, content, source } = traced;\n\n maybeAddSegment(gen, i, genCol, source, line, column, name);\n if (source && content != null) setSourceContent(gen, source, content);\n }\n }\n\n return gen;\n}\n\n/**\n * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own\n * child SourceMapTrees, until we find the original source map.\n */\nexport function originalPositionFor(\n source: Sources,\n line: number,\n column: number,\n name: string\n): SourceMapSegmentObject | null {\n if (!source.map) {\n return SegmentObject(source.source, line, column, name, source.content);\n }\n\n const segment = traceSegment(source.map, line, column);\n\n // If we couldn't find a segment, then this doesn't exist in the sourcemap.\n if (segment == null) return null;\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length === 1) return SOURCELESS_MAPPING;\n\n return originalPositionFor(\n source.sources[segment[1]],\n segment[2],\n segment[3],\n segment.length === 5 ? source.map.names[segment[4]] : name\n );\n}\n","import { TraceMap } from '@jridgewell/trace-mapping';\n\nimport { OriginalSource, MapSource } from './source-map-tree';\n\nimport type { Sources, MapSource as MapSourceType } from './source-map-tree';\nimport type { SourceMapInput, SourceMapLoader, LoaderContext } from './types';\n\nfunction asArray(value: T | T[]): T[] {\n if (Array.isArray(value)) return value;\n return [value];\n}\n\n/**\n * Recursively builds a tree structure out of sourcemap files, with each node\n * being either an `OriginalSource` \"leaf\" or a `SourceMapTree` composed of\n * `OriginalSource`s and `SourceMapTree`s.\n *\n * Every sourcemap is composed of a collection of source files and mappings\n * into locations of those source files. When we generate a `SourceMapTree` for\n * the sourcemap, we attempt to load each source file's own sourcemap. If it\n * does not have an associated sourcemap, it is considered an original,\n * unmodified source file.\n */\nexport default function buildSourceMapTree(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader\n): MapSourceType {\n const maps = asArray(input).map((m) => new TraceMap(m, ''));\n const map = maps.pop()!;\n\n for (let i = 0; i < maps.length; i++) {\n if (maps[i].sources.length > 1) {\n throw new Error(\n `Transformation map ${i} must have exactly one source file.\\n` +\n 'Did you specify these with the most recent transformation maps first?'\n );\n }\n }\n\n let tree = build(map, loader, '', 0);\n for (let i = maps.length - 1; i >= 0; i--) {\n tree = MapSource(maps[i], [tree]);\n }\n return tree;\n}\n\nfunction build(\n map: TraceMap,\n loader: SourceMapLoader,\n importer: string,\n importerDepth: number\n): MapSourceType {\n const { resolvedSources, sourcesContent } = map;\n\n const depth = importerDepth + 1;\n const children = resolvedSources.map((sourceFile: string | null, i: number): Sources => {\n // The loading context gives the loader more information about why this file is being loaded\n // (eg, from which importer). It also allows the loader to override the location of the loaded\n // sourcemap/original source, or to override the content in the sourcesContent field if it's\n // an unmodified source file.\n const ctx: LoaderContext = {\n importer,\n depth,\n source: sourceFile || '',\n content: undefined,\n };\n\n // Use the provided loader callback to retrieve the file's sourcemap.\n // TODO: We should eventually support async loading of sourcemap files.\n const sourceMap = loader(ctx.source, ctx);\n\n const { source, content } = ctx;\n\n // If there is a sourcemap, then we need to recurse into it to load its source files.\n if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);\n\n // Else, it's an an unmodified source file.\n // The contents of this unmodified source file can be overridden via the loader context,\n // allowing it to be explicitly null or a string. If it remains undefined, we fall back to\n // the importing sourcemap's `sourcesContent` field.\n const sourceContent =\n content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;\n return OriginalSource(source, sourceContent);\n });\n\n return MapSource(map, children);\n}\n","import { toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping';\n\nimport type { GenMapping } from '@jridgewell/gen-mapping';\nimport type { DecodedSourceMap, EncodedSourceMap, Options } from './types';\n\n/**\n * A SourceMap v3 compatible sourcemap, which only includes fields that were\n * provided to it.\n */\nexport default class SourceMap {\n declare file?: string | null;\n declare mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings'];\n declare sourceRoot?: string;\n declare names: string[];\n declare sources: (string | null)[];\n declare sourcesContent?: (string | null)[];\n declare version: 3;\n\n constructor(map: GenMapping, options: Options) {\n const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);\n this.version = out.version; // SourceMap spec says this should be first.\n this.file = out.file;\n this.mappings = out.mappings as SourceMap['mappings'];\n this.names = out.names as SourceMap['names'];\n\n this.sourceRoot = out.sourceRoot;\n\n this.sources = out.sources as SourceMap['sources'];\n if (!options.excludeContent) {\n this.sourcesContent = out.sourcesContent as SourceMap['sourcesContent'];\n }\n }\n\n toString(): string {\n return JSON.stringify(this);\n }\n}\n","import buildSourceMapTree from './build-source-map-tree';\nimport { traceMappings } from './source-map-tree';\nimport SourceMap from './source-map';\n\nimport type { SourceMapInput, SourceMapLoader, Options } from './types';\nexport type {\n SourceMapSegment,\n EncodedSourceMap,\n EncodedSourceMap as RawSourceMap,\n DecodedSourceMap,\n SourceMapInput,\n SourceMapLoader,\n LoaderContext,\n Options,\n} from './types';\n\n/**\n * Traces through all the mappings in the root sourcemap, through the sources\n * (and their sourcemaps), all the way back to the original source location.\n *\n * `loader` will be called every time we encounter a source file. If it returns\n * a sourcemap, we will recurse into that sourcemap to continue the trace. If\n * it returns a falsey value, that source file is treated as an original,\n * unmodified source file.\n *\n * Pass `excludeContent` to exclude any self-containing source file content\n * from the output sourcemap.\n *\n * Pass `decodedMappings` to receive a SourceMap with decoded (instead of\n * VLQ encoded) mappings.\n */\nexport default function remapping(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader,\n options?: boolean | Options\n): SourceMap {\n const opts =\n typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };\n const tree = buildSourceMapTree(input, loader);\n return new SourceMap(traceMappings(tree), opts);\n}\n"],"names":[],"mappings":";;;AA6BA,MAAM,kBAAkB,mBAAmB,aAAa,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;AAC/E,MAAM,aAAa,GAAc,EAAE,CAAC;AAEpC,SAAS,aAAa,CACpB,MAAc,EACd,IAAY,EACZ,MAAc,EACd,IAAY,EACZ,OAAsB,EAAA;IAEtB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;AACjD,CAAC;AASD,SAAS,MAAM,CACb,GAAoB,EACpB,OAAkB,EAClB,MAAmB,EACnB,OAAsB,EAAA;IAEtB,OAAO;QACL,GAAG;QACH,OAAO;QACP,MAAM;QACN,OAAO;KACD,CAAC;AACX,CAAC;AAED;;;AAGG;AACa,SAAA,S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AAG,YAAY,CAAC,GAAG,CAAC,CAAC;QAC5E,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC;AAC3B,QAAA,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;AACrB,QAAA,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAiC,CAAC;AACtD,QAAA,IAAI,CAAC,KAAK,GAAG,GAAG,CAAC,KAA2B,CAAC;AAE7C,QAAA,IAAI,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;AAEjC,QAAA,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAA+B,CAAC;AACnD,QAAA,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE;AAC3B,YAAA,IAAI,CAAC,cAAc,GAAG,GAAG,CAAC,cAA6C,CAAC;AACzE,SAAA;KACF;IAED,QAAQ,GAAA;AACN,QAAA,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;KAC7B;AACF;;ACpBD;;;;;;;;;;;;;;AAcG;AACqB,SAAA,SAAS,CAC/B,KAAwC,EACxC,MAAuB,EACvB,OAA2B,EAAA;IAE3B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC;IAChG,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;AAClD;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js b/node_modules/@ampproject/remapping/dist/remapping.umd.js new file mode 100644 index 0000000..e292d4c --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js @@ -0,0 +1,196 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@jridgewell/trace-mapping'), require('@jridgewell/gen-mapping')) : + typeof define === 'function' && define.amd ? define(['@jridgewell/trace-mapping', '@jridgewell/gen-mapping'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.remapping = factory(global.traceMapping, global.genMapping)); +})(this, (function (traceMapping, genMapping) { 'use strict'; + + const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null); + const EMPTY_SOURCES = []; + function SegmentObject(source, line, column, name, content) { + return { source, line, column, name, content }; + } + function Source(map, sources, source, content) { + return { + map, + sources, + source, + content, + }; + } + /** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ + function MapSource(map, sources) { + return Source(map, sources, '', null); + } + /** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ + function OriginalSource(source, content) { + return Source(null, EMPTY_SOURCES, source, content); + } + /** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ + function traceMappings(tree) { + // TODO: Eventually support sourceRoot, which has to be removed because the sources are already + // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. + const gen = new genMapping.GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = traceMapping.decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + const { column, line, name, content, source } = traced; + genMapping.maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) + genMapping.setSourceContent(gen, source, content); + } + } + return gen; + } + /** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ + function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content); + } + const segment = traceMapping.traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); + } + + function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; + } + /** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ + function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new traceMapping.TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; + } + function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new traceMapping.TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + return OriginalSource(source, sourceContent); + }); + return MapSource(map, children); + } + + /** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ + class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? genMapping.toDecodedMap(map) : genMapping.toEncodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } + } + + /** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ + function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); + } + + return remapping; + +})); +//# sourceMappingURL=remapping.umd.js.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js.map b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map new file mode 100644 index 0000000..9c89888 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.umd.js","sources":["../src/source-map-tree.ts","../src/build-source-map-tree.ts","../src/source-map.ts","../src/remapping.ts"],"sourcesContent":["import { GenMapping, maybeAddSegment, setSourceContent } from '@jridgewell/gen-mapping';\nimport { traceSegment, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport type { TraceMap } from '@jridgewell/trace-mapping';\n\nexport type SourceMapSegmentObject = {\n column: number;\n line: number;\n name: string;\n source: string;\n content: string | null;\n};\n\nexport type OriginalSource = {\n map: null;\n sources: Sources[];\n source: string;\n content: string | null;\n};\n\nexport type MapSource = {\n map: TraceMap;\n sources: Sources[];\n source: string;\n content: null;\n};\n\nexport type Sources = OriginalSource | MapSource;\n\nconst SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null);\nconst EMPTY_SOURCES: Sources[] = [];\n\nfunction SegmentObject(\n source: string,\n line: number,\n column: number,\n name: string,\n content: string | null\n): SourceMapSegmentObject {\n return { source, line, column, name, content };\n}\n\nfunction Source(map: TraceMap, sources: Sources[], source: '', content: null): MapSource;\nfunction Source(\n map: null,\n sources: Sources[],\n source: string,\n content: string | null\n): OriginalSource;\nfunction Source(\n map: TraceMap | null,\n sources: Sources[],\n source: string | '',\n content: string | null\n): Sources {\n return {\n map,\n sources,\n source,\n content,\n } as any;\n}\n\n/**\n * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes\n * (which may themselves be SourceMapTrees).\n */\nexport function MapSource(map: TraceMap, sources: Sources[]): MapSource {\n return Source(map, sources, '', null);\n}\n\n/**\n * A \"leaf\" node in the sourcemap tree, representing an original, unmodified source file. Recursive\n * segment tracing ends at the `OriginalSource`.\n */\nexport function OriginalSource(source: string, content: string | null): OriginalSource {\n return Source(null, EMPTY_SOURCES, source, content);\n}\n\n/**\n * traceMappings is only called on the root level SourceMapTree, and begins the process of\n * resolving each mapping in terms of the original source files.\n */\nexport function traceMappings(tree: MapSource): GenMapping {\n // TODO: Eventually support sourceRoot, which has to be removed because the sources are already\n // fully resolved. We'll need to make sources relative to the sourceRoot before adding them.\n const gen = new GenMapping({ file: tree.map.file });\n const { sources: rootSources, map } = tree;\n const rootNames = map.names;\n const rootMappings = decodedMappings(map);\n\n for (let i = 0; i < rootMappings.length; i++) {\n const segments = rootMappings[i];\n\n for (let j = 0; j < segments.length; j++) {\n const segment = segments[j];\n const genCol = segment[0];\n let traced: SourceMapSegmentObject | null = SOURCELESS_MAPPING;\n\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length !== 1) {\n const source = rootSources[segment[1]];\n traced = originalPositionFor(\n source,\n segment[2],\n segment[3],\n segment.length === 5 ? rootNames[segment[4]] : ''\n );\n\n // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a\n // respective segment into an original source.\n if (traced == null) continue;\n }\n\n const { column, line, name, content, source } = traced;\n\n maybeAddSegment(gen, i, genCol, source, line, column, name);\n if (source && content != null) setSourceContent(gen, source, content);\n }\n }\n\n return gen;\n}\n\n/**\n * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own\n * child SourceMapTrees, until we find the original source map.\n */\nexport function originalPositionFor(\n source: Sources,\n line: number,\n column: number,\n name: string\n): SourceMapSegmentObject | null {\n if (!source.map) {\n return SegmentObject(source.source, line, column, name, source.content);\n }\n\n const segment = traceSegment(source.map, line, column);\n\n // If we couldn't find a segment, then this doesn't exist in the sourcemap.\n if (segment == null) return null;\n // 1-length segments only move the current generated column, there's no source information\n // to gather from it.\n if (segment.length === 1) return SOURCELESS_MAPPING;\n\n return originalPositionFor(\n source.sources[segment[1]],\n segment[2],\n segment[3],\n segment.length === 5 ? source.map.names[segment[4]] : name\n );\n}\n","import { TraceMap } from '@jridgewell/trace-mapping';\n\nimport { OriginalSource, MapSource } from './source-map-tree';\n\nimport type { Sources, MapSource as MapSourceType } from './source-map-tree';\nimport type { SourceMapInput, SourceMapLoader, LoaderContext } from './types';\n\nfunction asArray(value: T | T[]): T[] {\n if (Array.isArray(value)) return value;\n return [value];\n}\n\n/**\n * Recursively builds a tree structure out of sourcemap files, with each node\n * being either an `OriginalSource` \"leaf\" or a `SourceMapTree` composed of\n * `OriginalSource`s and `SourceMapTree`s.\n *\n * Every sourcemap is composed of a collection of source files and mappings\n * into locations of those source files. When we generate a `SourceMapTree` for\n * the sourcemap, we attempt to load each source file's own sourcemap. If it\n * does not have an associated sourcemap, it is considered an original,\n * unmodified source file.\n */\nexport default function buildSourceMapTree(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader\n): MapSourceType {\n const maps = asArray(input).map((m) => new TraceMap(m, ''));\n const map = maps.pop()!;\n\n for (let i = 0; i < maps.length; i++) {\n if (maps[i].sources.length > 1) {\n throw new Error(\n `Transformation map ${i} must have exactly one source file.\\n` +\n 'Did you specify these with the most recent transformation maps first?'\n );\n }\n }\n\n let tree = build(map, loader, '', 0);\n for (let i = maps.length - 1; i >= 0; i--) {\n tree = MapSource(maps[i], [tree]);\n }\n return tree;\n}\n\nfunction build(\n map: TraceMap,\n loader: SourceMapLoader,\n importer: string,\n importerDepth: number\n): MapSourceType {\n const { resolvedSources, sourcesContent } = map;\n\n const depth = importerDepth + 1;\n const children = resolvedSources.map((sourceFile: string | null, i: number): Sources => {\n // The loading context gives the loader more information about why this file is being loaded\n // (eg, from which importer). It also allows the loader to override the location of the loaded\n // sourcemap/original source, or to override the content in the sourcesContent field if it's\n // an unmodified source file.\n const ctx: LoaderContext = {\n importer,\n depth,\n source: sourceFile || '',\n content: undefined,\n };\n\n // Use the provided loader callback to retrieve the file's sourcemap.\n // TODO: We should eventually support async loading of sourcemap files.\n const sourceMap = loader(ctx.source, ctx);\n\n const { source, content } = ctx;\n\n // If there is a sourcemap, then we need to recurse into it to load its source files.\n if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth);\n\n // Else, it's an an unmodified source file.\n // The contents of this unmodified source file can be overridden via the loader context,\n // allowing it to be explicitly null or a string. If it remains undefined, we fall back to\n // the importing sourcemap's `sourcesContent` field.\n const sourceContent =\n content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;\n return OriginalSource(source, sourceContent);\n });\n\n return MapSource(map, children);\n}\n","import { toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping';\n\nimport type { GenMapping } from '@jridgewell/gen-mapping';\nimport type { DecodedSourceMap, EncodedSourceMap, Options } from './types';\n\n/**\n * A SourceMap v3 compatible sourcemap, which only includes fields that were\n * provided to it.\n */\nexport default class SourceMap {\n declare file?: string | null;\n declare mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings'];\n declare sourceRoot?: string;\n declare names: string[];\n declare sources: (string | null)[];\n declare sourcesContent?: (string | null)[];\n declare version: 3;\n\n constructor(map: GenMapping, options: Options) {\n const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);\n this.version = out.version; // SourceMap spec says this should be first.\n this.file = out.file;\n this.mappings = out.mappings as SourceMap['mappings'];\n this.names = out.names as SourceMap['names'];\n\n this.sourceRoot = out.sourceRoot;\n\n this.sources = out.sources as SourceMap['sources'];\n if (!options.excludeContent) {\n this.sourcesContent = out.sourcesContent as SourceMap['sourcesContent'];\n }\n }\n\n toString(): string {\n return JSON.stringify(this);\n }\n}\n","import buildSourceMapTree from './build-source-map-tree';\nimport { traceMappings } from './source-map-tree';\nimport SourceMap from './source-map';\n\nimport type { SourceMapInput, SourceMapLoader, Options } from './types';\nexport type {\n SourceMapSegment,\n EncodedSourceMap,\n EncodedSourceMap as RawSourceMap,\n DecodedSourceMap,\n SourceMapInput,\n SourceMapLoader,\n LoaderContext,\n Options,\n} from './types';\n\n/**\n * Traces through all the mappings in the root sourcemap, through the sources\n * (and their sourcemaps), all the way back to the original source location.\n *\n * `loader` will be called every time we encounter a source file. If it returns\n * a sourcemap, we will recurse into that sourcemap to continue the trace. If\n * it returns a falsey value, that source file is treated as an original,\n * unmodified source file.\n *\n * Pass `excludeContent` to exclude any self-containing source file content\n * from the output sourcemap.\n *\n * Pass `decodedMappings` to receive a SourceMap with decoded (instead of\n * VLQ encoded) mappings.\n */\nexport default function remapping(\n input: SourceMapInput | SourceMapInput[],\n loader: SourceMapLoader,\n options?: boolean | Options\n): SourceMap {\n const opts =\n typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };\n const tree = buildSourceMapTree(input, loader);\n return new SourceMap(traceMappings(tree), opts);\n}\n"],"names":["GenMapping","decodedMappings","maybeAddSegment","setSourceContent","traceSegment","TraceMap","toDecodedMap","toEncodedMap"],"mappings":";;;;;;IA6BA,MAAM,kBAAkB,mBAAmB,aAAa,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;IAC/E,MAAM,aAAa,GAAc,EAAE,CAAC;IAEpC,SAAS,aAAa,CACpB,MAAc,EACd,IAAY,EACZ,MAAc,EACd,IAAY,EACZ,OAAsB,EAAA;QAEtB,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IACjD,CAAC;IASD,SAAS,MAAM,CACb,GAAoB,EACpB,OAAkB,EAClB,MAAmB,EACnB,OAAsB,EAAA;QAEtB,OAAO;YACL,GAAG;YACH,OAAO;YACP,MAAM;YACN,OAAO;SACD,CAAC;IACX,CAAC;IAED;;;IAGG;IACa,SAAA,SAAS,CAAC,GAAa,EAAE,OAAkB,EAAA;QACzD,OAAO,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;IACxC,CAAC;IAED;;;IAGG;IACa,SAAA,cAAc,CAAC,MAAc,EAAE,OAAsB,EAAA;QACnE,OAAO,MAAM,CAAC,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;IACtD,CAAC;IAED;;;IAGG;IACG,SAAU,aAAa,CAAC,IAAe,EAAA;;;IAG3C,IAAA,MAAM,GAAG,GAAG,IAAIA,qBAAU,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;QACpD,MAAM,EAAE,OAAO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AE;IAC3B,YAAA,IAAI,CAAC,cAAc,GAAG,GAAG,CAAC,cAA6C,CAAC;IACzE,SAAA;SACF;QAED,QAAQ,GAAA;IACN,QAAA,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;SAC7B;IACF;;ICpBD;;;;;;;;;;;;;;IAcG;IACqB,SAAA,SAAS,CAC/B,KAAwC,EACxC,MAAuB,EACvB,OAA2B,EAAA;QAE3B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC;QAChG,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;IAClD;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts new file mode 100644 index 0000000..f87fcea --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts @@ -0,0 +1,14 @@ +import type { MapSource as MapSourceType } from './source-map-tree'; +import type { SourceMapInput, SourceMapLoader } from './types'; +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +export default function buildSourceMapTree(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader): MapSourceType; diff --git a/node_modules/@ampproject/remapping/dist/types/remapping.d.ts b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts new file mode 100644 index 0000000..0b58ea9 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts @@ -0,0 +1,19 @@ +import SourceMap from './source-map'; +import type { SourceMapInput, SourceMapLoader, Options } from './types'; +export type { SourceMapSegment, EncodedSourceMap, EncodedSourceMap as RawSourceMap, DecodedSourceMap, SourceMapInput, SourceMapLoader, LoaderContext, Options, } from './types'; +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +export default function remapping(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader, options?: boolean | Options): SourceMap; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts new file mode 100644 index 0000000..3a9f7af --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts @@ -0,0 +1,42 @@ +import { GenMapping } from '@jridgewell/gen-mapping'; +import type { TraceMap } from '@jridgewell/trace-mapping'; +export declare type SourceMapSegmentObject = { + column: number; + line: number; + name: string; + source: string; + content: string | null; +}; +export declare type OriginalSource = { + map: null; + sources: Sources[]; + source: string; + content: string | null; +}; +export declare type MapSource = { + map: TraceMap; + sources: Sources[]; + source: string; + content: null; +}; +export declare type Sources = OriginalSource | MapSource; +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +export declare function MapSource(map: TraceMap, sources: Sources[]): MapSource; +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +export declare function OriginalSource(source: string, content: string | null): OriginalSource; +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +export declare function traceMappings(tree: MapSource): GenMapping; +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +export declare function originalPositionFor(source: Sources, line: number, column: number, name: string): SourceMapSegmentObject | null; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts new file mode 100644 index 0000000..ef999b7 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts @@ -0,0 +1,17 @@ +import type { GenMapping } from '@jridgewell/gen-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Options } from './types'; +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +export default class SourceMap { + file?: string | null; + mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings']; + sourceRoot?: string; + names: string[]; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + constructor(map: GenMapping, options: Options); + toString(): string; +} diff --git a/node_modules/@ampproject/remapping/dist/types/types.d.ts b/node_modules/@ampproject/remapping/dist/types/types.d.ts new file mode 100644 index 0000000..730a963 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/types.d.ts @@ -0,0 +1,14 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +export type { SourceMapSegment, DecodedSourceMap, EncodedSourceMap, } from '@jridgewell/trace-mapping'; +export type { SourceMapInput }; +export declare type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; +}; +export declare type SourceMapLoader = (file: string, ctx: LoaderContext) => SourceMapInput | null | undefined | void; +export declare type Options = { + excludeContent?: boolean; + decodedMappings?: boolean; +}; diff --git a/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs b/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs new file mode 100644 index 0000000..64e6666 --- /dev/null +++ b/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs @@ -0,0 +1,1104 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var util = require('util'); +var path = require('path'); +var Ajv = require('ajv'); +var globals = require('globals'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var util__default = /*#__PURE__*/_interopDefaultLegacy(util); +var path__default = /*#__PURE__*/_interopDefaultLegacy(path); +var Ajv__default = /*#__PURE__*/_interopDefaultLegacy(Ajv); +var globals__default = /*#__PURE__*/_interopDefaultLegacy(globals); + +/** + * @fileoverview Config file operations. This file must be usable in the browser, + * so no Node-specific code can be here. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +const RULE_SEVERITY_STRINGS = ["off", "warn", "error"], + RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => { + map[value] = index; + return map; + }, {}), + VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"]; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Normalizes the severity value of a rule's configuration to a number + * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally + * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0), + * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array + * whose first element is one of the above values. Strings are matched case-insensitively. + * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0. + */ +function getRuleSeverity(ruleConfig) { + const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; + + if (severityValue === 0 || severityValue === 1 || severityValue === 2) { + return severityValue; + } + + if (typeof severityValue === "string") { + return RULE_SEVERITY[severityValue.toLowerCase()] || 0; + } + + return 0; +} + +/** + * Converts old-style severity settings (0, 1, 2) into new-style + * severity settings (off, warn, error) for all rules. Assumption is that severity + * values have already been validated as correct. + * @param {Object} config The config object to normalize. + * @returns {void} + */ +function normalizeToStrings(config) { + + if (config.rules) { + Object.keys(config.rules).forEach(ruleId => { + const ruleConfig = config.rules[ruleId]; + + if (typeof ruleConfig === "number") { + config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0]; + } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") { + ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0]; + } + }); + } +} + +/** + * Determines if the severity for the given rule configuration represents an error. + * @param {int|string|Array} ruleConfig The configuration for an individual rule. + * @returns {boolean} True if the rule represents an error, false if not. + */ +function isErrorSeverity(ruleConfig) { + return getRuleSeverity(ruleConfig) === 2; +} + +/** + * Checks whether a given config has valid severity or not. + * @param {number|string|Array} ruleConfig The configuration for an individual rule. + * @returns {boolean} `true` if the configuration has valid severity. + */ +function isValidSeverity(ruleConfig) { + let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; + + if (typeof severity === "string") { + severity = severity.toLowerCase(); + } + return VALID_SEVERITIES.indexOf(severity) !== -1; +} + +/** + * Checks whether every rule of a given config has valid severity or not. + * @param {Object} config The configuration for rules. + * @returns {boolean} `true` if the configuration has valid severity. + */ +function isEverySeverityValid(config) { + return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId])); +} + +/** + * Normalizes a value for a global in a config + * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in + * a global directive comment + * @returns {("readable"|"writeable"|"off")} The value normalized as a string + * @throws Error if global value is invalid + */ +function normalizeConfigGlobal(configuredValue) { + switch (configuredValue) { + case "off": + return "off"; + + case true: + case "true": + case "writeable": + case "writable": + return "writable"; + + case null: + case false: + case "false": + case "readable": + case "readonly": + return "readonly"; + + default: + throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`); + } +} + +var ConfigOps = { + __proto__: null, + getRuleSeverity: getRuleSeverity, + normalizeToStrings: normalizeToStrings, + isErrorSeverity: isErrorSeverity, + isValidSeverity: isValidSeverity, + isEverySeverityValid: isEverySeverityValid, + normalizeConfigGlobal: normalizeConfigGlobal +}; + +/** + * @fileoverview Provide the function that emits deprecation warnings. + * @author Toru Nagashima + */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +// Defitions for deprecation warnings. +const deprecationWarningMessages = { + ESLINT_LEGACY_ECMAFEATURES: + "The 'ecmaFeatures' config file property is deprecated and has no effect.", + ESLINT_PERSONAL_CONFIG_LOAD: + "'~/.eslintrc.*' config files have been deprecated. " + + "Please use a config file per project or the '--config' option.", + ESLINT_PERSONAL_CONFIG_SUPPRESS: + "'~/.eslintrc.*' config files have been deprecated. " + + "Please remove it or add 'root:true' to the config files in your " + + "projects in order to avoid loading '~/.eslintrc.*' accidentally." +}; + +const sourceFileErrorCache = new Set(); + +/** + * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted + * for each unique file path, but repeated invocations with the same file path have no effect. + * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active. + * @param {string} source The name of the configuration source to report the warning for. + * @param {string} errorCode The warning message to show. + * @returns {void} + */ +function emitDeprecationWarning(source, errorCode) { + const cacheKey = JSON.stringify({ source, errorCode }); + + if (sourceFileErrorCache.has(cacheKey)) { + return; + } + sourceFileErrorCache.add(cacheKey); + + const rel = path__default["default"].relative(process.cwd(), source); + const message = deprecationWarningMessages[errorCode]; + + process.emitWarning( + `${message} (found in "${rel}")`, + "DeprecationWarning", + errorCode + ); +} + +/** + * @fileoverview The instance of Ajv validator. + * @author Evgeny Poberezkin + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/* + * Copied from ajv/lib/refs/json-schema-draft-04.json + * The MIT License (MIT) + * Copyright (c) 2015-2017 Evgeny Poberezkin + */ +const metaSchema = { + id: "http://json-schema.org/draft-04/schema#", + $schema: "http://json-schema.org/draft-04/schema#", + description: "Core schema meta-schema", + definitions: { + schemaArray: { + type: "array", + minItems: 1, + items: { $ref: "#" } + }, + positiveInteger: { + type: "integer", + minimum: 0 + }, + positiveIntegerDefault0: { + allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }] + }, + simpleTypes: { + enum: ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + stringArray: { + type: "array", + items: { type: "string" }, + minItems: 1, + uniqueItems: true + } + }, + type: "object", + properties: { + id: { + type: "string" + }, + $schema: { + type: "string" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + default: { }, + multipleOf: { + type: "number", + minimum: 0, + exclusiveMinimum: true + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "boolean", + default: false + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "boolean", + default: false + }, + maxLength: { $ref: "#/definitions/positiveInteger" }, + minLength: { $ref: "#/definitions/positiveIntegerDefault0" }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { + anyOf: [ + { type: "boolean" }, + { $ref: "#" } + ], + default: { } + }, + items: { + anyOf: [ + { $ref: "#" }, + { $ref: "#/definitions/schemaArray" } + ], + default: { } + }, + maxItems: { $ref: "#/definitions/positiveInteger" }, + minItems: { $ref: "#/definitions/positiveIntegerDefault0" }, + uniqueItems: { + type: "boolean", + default: false + }, + maxProperties: { $ref: "#/definitions/positiveInteger" }, + minProperties: { $ref: "#/definitions/positiveIntegerDefault0" }, + required: { $ref: "#/definitions/stringArray" }, + additionalProperties: { + anyOf: [ + { type: "boolean" }, + { $ref: "#" } + ], + default: { } + }, + definitions: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + properties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + patternProperties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [ + { $ref: "#" }, + { $ref: "#/definitions/stringArray" } + ] + } + }, + enum: { + type: "array", + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { $ref: "#/definitions/simpleTypes" }, + { + type: "array", + items: { $ref: "#/definitions/simpleTypes" }, + minItems: 1, + uniqueItems: true + } + ] + }, + format: { type: "string" }, + allOf: { $ref: "#/definitions/schemaArray" }, + anyOf: { $ref: "#/definitions/schemaArray" }, + oneOf: { $ref: "#/definitions/schemaArray" }, + not: { $ref: "#" } + }, + dependencies: { + exclusiveMaximum: ["maximum"], + exclusiveMinimum: ["minimum"] + }, + default: { } +}; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +var ajvOrig = (additionalOptions = {}) => { + const ajv = new Ajv__default["default"]({ + meta: false, + useDefaults: true, + validateSchema: false, + missingRefs: "ignore", + verbose: true, + schemaId: "auto", + ...additionalOptions + }); + + ajv.addMetaSchema(metaSchema); + // eslint-disable-next-line no-underscore-dangle + ajv._opts.defaultMeta = metaSchema.id; + + return ajv; +}; + +/** + * @fileoverview Defines a schema for configs. + * @author Sylvan Mably + */ + +const baseConfigProperties = { + $schema: { type: "string" }, + env: { type: "object" }, + extends: { $ref: "#/definitions/stringOrStrings" }, + globals: { type: "object" }, + overrides: { + type: "array", + items: { $ref: "#/definitions/overrideConfig" }, + additionalItems: false + }, + parser: { type: ["string", "null"] }, + parserOptions: { type: "object" }, + plugins: { type: "array" }, + processor: { type: "string" }, + rules: { type: "object" }, + settings: { type: "object" }, + noInlineConfig: { type: "boolean" }, + reportUnusedDisableDirectives: { type: "boolean" }, + + ecmaFeatures: { type: "object" } // deprecated; logs a warning when used +}; + +const configSchema = { + definitions: { + stringOrStrings: { + oneOf: [ + { type: "string" }, + { + type: "array", + items: { type: "string" }, + additionalItems: false + } + ] + }, + stringOrStringsRequired: { + oneOf: [ + { type: "string" }, + { + type: "array", + items: { type: "string" }, + additionalItems: false, + minItems: 1 + } + ] + }, + + // Config at top-level. + objectConfig: { + type: "object", + properties: { + root: { type: "boolean" }, + ignorePatterns: { $ref: "#/definitions/stringOrStrings" }, + ...baseConfigProperties + }, + additionalProperties: false + }, + + // Config in `overrides`. + overrideConfig: { + type: "object", + properties: { + excludedFiles: { $ref: "#/definitions/stringOrStrings" }, + files: { $ref: "#/definitions/stringOrStringsRequired" }, + ...baseConfigProperties + }, + required: ["files"], + additionalProperties: false + } + }, + + $ref: "#/definitions/objectConfig" +}; + +/** + * @fileoverview Defines environment settings and globals. + * @author Elan Shanker + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Get the object that has difference. + * @param {Record} current The newer object. + * @param {Record} prev The older object. + * @returns {Record} The difference object. + */ +function getDiff(current, prev) { + const retv = {}; + + for (const [key, value] of Object.entries(current)) { + if (!Object.hasOwnProperty.call(prev, key)) { + retv[key] = value; + } + } + + return retv; +} + +const newGlobals2015 = getDiff(globals__default["default"].es2015, globals__default["default"].es5); // 19 variables such as Promise, Map, ... +const newGlobals2017 = { + Atomics: false, + SharedArrayBuffer: false +}; +const newGlobals2020 = { + BigInt: false, + BigInt64Array: false, + BigUint64Array: false, + globalThis: false +}; + +const newGlobals2021 = { + AggregateError: false, + FinalizationRegistry: false, + WeakRef: false +}; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** @type {Map} */ +var environments = new Map(Object.entries({ + + // Language + builtin: { + globals: globals__default["default"].es5 + }, + es6: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 6 + } + }, + es2015: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 6 + } + }, + es2016: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 7 + } + }, + es2017: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 8 + } + }, + es2018: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 9 + } + }, + es2019: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 10 + } + }, + es2020: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 }, + parserOptions: { + ecmaVersion: 11 + } + }, + es2021: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 12 + } + }, + es2022: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 13 + } + }, + es2023: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 14 + } + }, + es2024: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 15 + } + }, + + // Platforms + browser: { + globals: globals__default["default"].browser + }, + node: { + globals: globals__default["default"].node, + parserOptions: { + ecmaFeatures: { + globalReturn: true + } + } + }, + "shared-node-browser": { + globals: globals__default["default"]["shared-node-browser"] + }, + worker: { + globals: globals__default["default"].worker + }, + serviceworker: { + globals: globals__default["default"].serviceworker + }, + + // Frameworks + commonjs: { + globals: globals__default["default"].commonjs, + parserOptions: { + ecmaFeatures: { + globalReturn: true + } + } + }, + amd: { + globals: globals__default["default"].amd + }, + mocha: { + globals: globals__default["default"].mocha + }, + jasmine: { + globals: globals__default["default"].jasmine + }, + jest: { + globals: globals__default["default"].jest + }, + phantomjs: { + globals: globals__default["default"].phantomjs + }, + jquery: { + globals: globals__default["default"].jquery + }, + qunit: { + globals: globals__default["default"].qunit + }, + prototypejs: { + globals: globals__default["default"].prototypejs + }, + shelljs: { + globals: globals__default["default"].shelljs + }, + meteor: { + globals: globals__default["default"].meteor + }, + mongo: { + globals: globals__default["default"].mongo + }, + protractor: { + globals: globals__default["default"].protractor + }, + applescript: { + globals: globals__default["default"].applescript + }, + nashorn: { + globals: globals__default["default"].nashorn + }, + atomtest: { + globals: globals__default["default"].atomtest + }, + embertest: { + globals: globals__default["default"].embertest + }, + webextensions: { + globals: globals__default["default"].webextensions + }, + greasemonkey: { + globals: globals__default["default"].greasemonkey + } +})); + +/** + * @fileoverview Validates configs. + * @author Brandon Mills + */ + +const ajv = ajvOrig(); + +const ruleValidators = new WeakMap(); +const noop = Function.prototype; + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ +let validateSchema; +const severityMap = { + error: 2, + warn: 1, + off: 0 +}; + +const validated = new WeakSet(); + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +class ConfigValidator { + constructor({ builtInRules = new Map() } = {}) { + this.builtInRules = builtInRules; + } + + /** + * Gets a complete options schema for a rule. + * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object + * @returns {Object} JSON Schema for the rule's options. + */ + getRuleOptionsSchema(rule) { + if (!rule) { + return null; + } + + const schema = rule.schema || rule.meta && rule.meta.schema; + + // Given a tuple of schemas, insert warning level at the beginning + if (Array.isArray(schema)) { + if (schema.length) { + return { + type: "array", + items: schema, + minItems: 0, + maxItems: schema.length + }; + } + return { + type: "array", + minItems: 0, + maxItems: 0 + }; + + } + + // Given a full schema, leave it alone + return schema || null; + } + + /** + * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid. + * @param {options} options The given options for the rule. + * @returns {number|string} The rule's severity value + */ + validateRuleSeverity(options) { + const severity = Array.isArray(options) ? options[0] : options; + const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity; + + if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) { + return normSeverity; + } + + throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util__default["default"].inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`); + + } + + /** + * Validates the non-severity options passed to a rule, based on its schema. + * @param {{create: Function}} rule The rule to validate + * @param {Array} localOptions The options for the rule, excluding severity + * @returns {void} + */ + validateRuleSchema(rule, localOptions) { + if (!ruleValidators.has(rule)) { + const schema = this.getRuleOptionsSchema(rule); + + if (schema) { + ruleValidators.set(rule, ajv.compile(schema)); + } + } + + const validateRule = ruleValidators.get(rule); + + if (validateRule) { + validateRule(localOptions); + if (validateRule.errors) { + throw new Error(validateRule.errors.map( + error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n` + ).join("")); + } + } + } + + /** + * Validates a rule's options against its schema. + * @param {{create: Function}|null} rule The rule that the config is being validated for + * @param {string} ruleId The rule's unique name. + * @param {Array|number} options The given options for the rule. + * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined, + * no source is prepended to the message. + * @returns {void} + */ + validateRuleOptions(rule, ruleId, options, source = null) { + try { + const severity = this.validateRuleSeverity(options); + + if (severity !== 0) { + this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []); + } + } catch (err) { + const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`; + + if (typeof source === "string") { + throw new Error(`${source}:\n\t${enhancedMessage}`); + } else { + throw new Error(enhancedMessage); + } + } + } + + /** + * Validates an environment object + * @param {Object} environment The environment config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments. + * @returns {void} + */ + validateEnvironment( + environment, + source, + getAdditionalEnv = noop + ) { + + // not having an environment is ok + if (!environment) { + return; + } + + Object.keys(environment).forEach(id => { + const env = getAdditionalEnv(id) || environments.get(id) || null; + + if (!env) { + const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`; + + throw new Error(message); + } + }); + } + + /** + * Validates a rules config object + * @param {Object} rulesConfig The rules config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules + * @returns {void} + */ + validateRules( + rulesConfig, + source, + getAdditionalRule = noop + ) { + if (!rulesConfig) { + return; + } + + Object.keys(rulesConfig).forEach(id => { + const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null; + + this.validateRuleOptions(rule, id, rulesConfig[id], source); + }); + } + + /** + * Validates a `globals` section of a config file + * @param {Object} globalsConfig The `globals` section + * @param {string|null} source The name of the configuration source to report in the event of an error. + * @returns {void} + */ + validateGlobals(globalsConfig, source = null) { + if (!globalsConfig) { + return; + } + + Object.entries(globalsConfig) + .forEach(([configuredGlobal, configuredValue]) => { + try { + normalizeConfigGlobal(configuredValue); + } catch (err) { + throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`); + } + }); + } + + /** + * Validate `processor` configuration. + * @param {string|undefined} processorName The processor name. + * @param {string} source The name of config file. + * @param {function(id:string): Processor} getProcessor The getter of defined processors. + * @returns {void} + */ + validateProcessor(processorName, source, getProcessor) { + if (processorName && !getProcessor(processorName)) { + throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`); + } + } + + /** + * Formats an array of schema validation errors. + * @param {Array} errors An array of error messages to format. + * @returns {string} Formatted error message + */ + formatErrors(errors) { + return errors.map(error => { + if (error.keyword === "additionalProperties") { + const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty; + + return `Unexpected top-level property "${formattedPropertyPath}"`; + } + if (error.keyword === "type") { + const formattedField = error.dataPath.slice(1); + const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema; + const formattedValue = JSON.stringify(error.data); + + return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`; + } + + const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath; + + return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`; + }).map(message => `\t- ${message}.\n`).join(""); + } + + /** + * Validates the top level properties of the config object. + * @param {Object} config The config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @returns {void} + */ + validateConfigSchema(config, source = null) { + validateSchema = validateSchema || ajv.compile(configSchema); + + if (!validateSchema(config)) { + throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`); + } + + if (Object.hasOwnProperty.call(config, "ecmaFeatures")) { + emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES"); + } + } + + /** + * Validates an entire config object. + * @param {Object} config The config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules. + * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs. + * @returns {void} + */ + validate(config, source, getAdditionalRule, getAdditionalEnv) { + this.validateConfigSchema(config, source); + this.validateRules(config.rules, source, getAdditionalRule); + this.validateEnvironment(config.env, source, getAdditionalEnv); + this.validateGlobals(config.globals, source); + + for (const override of config.overrides || []) { + this.validateRules(override.rules, source, getAdditionalRule); + this.validateEnvironment(override.env, source, getAdditionalEnv); + this.validateGlobals(config.globals, source); + } + } + + /** + * Validate config array object. + * @param {ConfigArray} configArray The config array to validate. + * @returns {void} + */ + validateConfigArray(configArray) { + const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments); + const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors); + const getPluginRule = Map.prototype.get.bind(configArray.pluginRules); + + // Validate. + for (const element of configArray) { + if (validated.has(element)) { + continue; + } + validated.add(element); + + this.validateEnvironment(element.env, element.name, getPluginEnv); + this.validateGlobals(element.globals, element.name); + this.validateProcessor(element.processor, element.name, getPluginProcessor); + this.validateRules(element.rules, element.name, getPluginRule); + } + } + +} + +/** + * @fileoverview Common helpers for naming of plugins, formatters and configs + */ + +const NAMESPACE_REGEX = /^@.*\//iu; + +/** + * Brings package name to correct format based on prefix + * @param {string} name The name of the package. + * @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter" + * @returns {string} Normalized name of the package + * @private + */ +function normalizePackageName(name, prefix) { + let normalizedName = name; + + /** + * On Windows, name can come in with Windows slashes instead of Unix slashes. + * Normalize to Unix first to avoid errors later on. + * https://github.com/eslint/eslint/issues/5644 + */ + if (normalizedName.includes("\\")) { + normalizedName = normalizedName.replace(/\\/gu, "/"); + } + + if (normalizedName.charAt(0) === "@") { + + /** + * it's a scoped package + * package name is the prefix, or just a username + */ + const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"), + scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u"); + + if (scopedPackageShortcutRegex.test(normalizedName)) { + normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`); + } else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) { + + /** + * for scoped packages, insert the prefix after the first / unless + * the path is already @scope/eslint or @scope/eslint-xxx-yyy + */ + normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`); + } + } else if (!normalizedName.startsWith(`${prefix}-`)) { + normalizedName = `${prefix}-${normalizedName}`; + } + + return normalizedName; +} + +/** + * Removes the prefix from a fullname. + * @param {string} fullname The term which may have the prefix. + * @param {string} prefix The prefix to remove. + * @returns {string} The term without prefix. + */ +function getShorthandName(fullname, prefix) { + if (fullname[0] === "@") { + let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname); + + if (matchResult) { + return matchResult[1]; + } + + matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname); + if (matchResult) { + return `${matchResult[1]}/${matchResult[2]}`; + } + } else if (fullname.startsWith(`${prefix}-`)) { + return fullname.slice(prefix.length + 1); + } + + return fullname; +} + +/** + * Gets the scope (namespace) of a term. + * @param {string} term The term which may have the namespace. + * @returns {string} The namespace of the term if it has one. + */ +function getNamespaceFromTerm(term) { + const match = term.match(NAMESPACE_REGEX); + + return match ? match[0] : ""; +} + +var naming = { + __proto__: null, + normalizePackageName: normalizePackageName, + getShorthandName: getShorthandName, + getNamespaceFromTerm: getNamespaceFromTerm +}; + +/** + * @fileoverview Package exports for @eslint/eslintrc + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +const Legacy = { + environments, + + // shared + ConfigOps, + ConfigValidator, + naming +}; + +exports.Legacy = Legacy; +//# sourceMappingURL=eslintrc-universal.cjs.map diff --git a/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs.map b/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs.map new file mode 100644 index 0000000..12895a6 --- /dev/null +++ b/node_modules/@eslint/eslintrc/dist/eslintrc-universal.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"eslintrc-universal.cjs","sources":["../lib/shared/config-ops.js","../lib/shared/deprecation-warnings.js","../lib/shared/ajv.js","../conf/config-schema.js","../conf/environments.js","../lib/shared/config-validator.js","../lib/shared/naming.js","../lib/index-universal.js"],"sourcesContent":["/**\n * @fileoverview Config file operations. This file must be usable in the browser,\n * so no Node-specific code can be here.\n * @author Nicholas C. Zakas\n */\n\n//------------------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------------------\n\nconst RULE_SEVERITY_STRINGS = [\"off\", \"warn\", \"error\"],\n RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {\n map[value] = index;\n return map;\n }, {}),\n VALID_SEVERITIES = [0, 1, 2, \"off\", \"warn\", \"error\"];\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/**\n * Normalizes the severity value of a rule's configuration to a number\n * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally\n * received from the user. A valid config value is either 0, 1, 2, the string \"off\" (treated the same as 0),\n * the string \"warn\" (treated the same as 1), the string \"error\" (treated the same as 2), or an array\n * whose first element is one of the above values. Strings are matched case-insensitively.\n * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.\n */\nfunction getRuleSeverity(ruleConfig) {\n const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;\n\n if (severityValue === 0 || severityValue === 1 || severityValue === 2) {\n return severityValue;\n }\n\n if (typeof severityValue === \"string\") {\n return RULE_SEVERITY[severityValue.toLowerCase()] || 0;\n }\n\n return 0;\n}\n\n/**\n * Converts old-style severity settings (0, 1, 2) into new-style\n * severity settings (off, warn, error) for all rules. Assumption is that severity\n * values have already been validated as correct.\n * @param {Object} config The config object to normalize.\n * @returns {void}\n */\nfunction normalizeToStrings(config) {\n\n if (config.rules) {\n Object.keys(config.rules).forEach(ruleId => {\n const ruleConfig = config.rules[ruleId];\n\n if (typeof ruleConfig === \"number\") {\n config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];\n } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === \"number\") {\n ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];\n }\n });\n }\n}\n\n/**\n * Determines if the severity for the given rule configuration represents an error.\n * @param {int|string|Array} ruleConfig The configuration for an individual rule.\n * @returns {boolean} True if the rule represents an error, false if not.\n */\nfunction isErrorSeverity(ruleConfig) {\n return getRuleSeverity(ruleConfig) === 2;\n}\n\n/**\n * Checks whether a given config has valid severity or not.\n * @param {number|string|Array} ruleConfig The configuration for an individual rule.\n * @returns {boolean} `true` if the configuration has valid severity.\n */\nfunction isValidSeverity(ruleConfig) {\n let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;\n\n if (typeof severity === \"string\") {\n severity = severity.toLowerCase();\n }\n return VALID_SEVERITIES.indexOf(severity) !== -1;\n}\n\n/**\n * Checks whether every rule of a given config has valid severity or not.\n * @param {Object} config The configuration for rules.\n * @returns {boolean} `true` if the configuration has valid severity.\n */\nfunction isEverySeverityValid(config) {\n return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));\n}\n\n/**\n * Normalizes a value for a global in a config\n * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in\n * a global directive comment\n * @returns {(\"readable\"|\"writeable\"|\"off\")} The value normalized as a string\n * @throws Error if global value is invalid\n */\nfunction normalizeConfigGlobal(configuredValue) {\n switch (configuredValue) {\n case \"off\":\n return \"off\";\n\n case true:\n case \"true\":\n case \"writeable\":\n case \"writable\":\n return \"writable\";\n\n case null:\n case false:\n case \"false\":\n case \"readable\":\n case \"readonly\":\n return \"readonly\";\n\n default:\n throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);\n }\n}\n\nexport {\n getRuleSeverity,\n normalizeToStrings,\n isErrorSeverity,\n isValidSeverity,\n isEverySeverityValid,\n normalizeConfigGlobal\n};\n","/**\n * @fileoverview Provide the function that emits deprecation warnings.\n * @author Toru Nagashima \n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport path from \"path\";\n\n//------------------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------------------\n\n// Defitions for deprecation warnings.\nconst deprecationWarningMessages = {\n ESLINT_LEGACY_ECMAFEATURES:\n \"The 'ecmaFeatures' config file property is deprecated and has no effect.\",\n ESLINT_PERSONAL_CONFIG_LOAD:\n \"'~/.eslintrc.*' config files have been deprecated. \" +\n \"Please use a config file per project or the '--config' option.\",\n ESLINT_PERSONAL_CONFIG_SUPPRESS:\n \"'~/.eslintrc.*' config files have been deprecated. \" +\n \"Please remove it or add 'root:true' to the config files in your \" +\n \"projects in order to avoid loading '~/.eslintrc.*' accidentally.\"\n};\n\nconst sourceFileErrorCache = new Set();\n\n/**\n * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted\n * for each unique file path, but repeated invocations with the same file path have no effect.\n * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.\n * @param {string} source The name of the configuration source to report the warning for.\n * @param {string} errorCode The warning message to show.\n * @returns {void}\n */\nfunction emitDeprecationWarning(source, errorCode) {\n const cacheKey = JSON.stringify({ source, errorCode });\n\n if (sourceFileErrorCache.has(cacheKey)) {\n return;\n }\n sourceFileErrorCache.add(cacheKey);\n\n const rel = path.relative(process.cwd(), source);\n const message = deprecationWarningMessages[errorCode];\n\n process.emitWarning(\n `${message} (found in \"${rel}\")`,\n \"DeprecationWarning\",\n errorCode\n );\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport {\n emitDeprecationWarning\n};\n","/**\n * @fileoverview The instance of Ajv validator.\n * @author Evgeny Poberezkin\n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport Ajv from \"ajv\";\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/*\n * Copied from ajv/lib/refs/json-schema-draft-04.json\n * The MIT License (MIT)\n * Copyright (c) 2015-2017 Evgeny Poberezkin\n */\nconst metaSchema = {\n id: \"http://json-schema.org/draft-04/schema#\",\n $schema: \"http://json-schema.org/draft-04/schema#\",\n description: \"Core schema meta-schema\",\n definitions: {\n schemaArray: {\n type: \"array\",\n minItems: 1,\n items: { $ref: \"#\" }\n },\n positiveInteger: {\n type: \"integer\",\n minimum: 0\n },\n positiveIntegerDefault0: {\n allOf: [{ $ref: \"#/definitions/positiveInteger\" }, { default: 0 }]\n },\n simpleTypes: {\n enum: [\"array\", \"boolean\", \"integer\", \"null\", \"number\", \"object\", \"string\"]\n },\n stringArray: {\n type: \"array\",\n items: { type: \"string\" },\n minItems: 1,\n uniqueItems: true\n }\n },\n type: \"object\",\n properties: {\n id: {\n type: \"string\"\n },\n $schema: {\n type: \"string\"\n },\n title: {\n type: \"string\"\n },\n description: {\n type: \"string\"\n },\n default: { },\n multipleOf: {\n type: \"number\",\n minimum: 0,\n exclusiveMinimum: true\n },\n maximum: {\n type: \"number\"\n },\n exclusiveMaximum: {\n type: \"boolean\",\n default: false\n },\n minimum: {\n type: \"number\"\n },\n exclusiveMinimum: {\n type: \"boolean\",\n default: false\n },\n maxLength: { $ref: \"#/definitions/positiveInteger\" },\n minLength: { $ref: \"#/definitions/positiveIntegerDefault0\" },\n pattern: {\n type: \"string\",\n format: \"regex\"\n },\n additionalItems: {\n anyOf: [\n { type: \"boolean\" },\n { $ref: \"#\" }\n ],\n default: { }\n },\n items: {\n anyOf: [\n { $ref: \"#\" },\n { $ref: \"#/definitions/schemaArray\" }\n ],\n default: { }\n },\n maxItems: { $ref: \"#/definitions/positiveInteger\" },\n minItems: { $ref: \"#/definitions/positiveIntegerDefault0\" },\n uniqueItems: {\n type: \"boolean\",\n default: false\n },\n maxProperties: { $ref: \"#/definitions/positiveInteger\" },\n minProperties: { $ref: \"#/definitions/positiveIntegerDefault0\" },\n required: { $ref: \"#/definitions/stringArray\" },\n additionalProperties: {\n anyOf: [\n { type: \"boolean\" },\n { $ref: \"#\" }\n ],\n default: { }\n },\n definitions: {\n type: \"object\",\n additionalProperties: { $ref: \"#\" },\n default: { }\n },\n properties: {\n type: \"object\",\n additionalProperties: { $ref: \"#\" },\n default: { }\n },\n patternProperties: {\n type: \"object\",\n additionalProperties: { $ref: \"#\" },\n default: { }\n },\n dependencies: {\n type: \"object\",\n additionalProperties: {\n anyOf: [\n { $ref: \"#\" },\n { $ref: \"#/definitions/stringArray\" }\n ]\n }\n },\n enum: {\n type: \"array\",\n minItems: 1,\n uniqueItems: true\n },\n type: {\n anyOf: [\n { $ref: \"#/definitions/simpleTypes\" },\n {\n type: \"array\",\n items: { $ref: \"#/definitions/simpleTypes\" },\n minItems: 1,\n uniqueItems: true\n }\n ]\n },\n format: { type: \"string\" },\n allOf: { $ref: \"#/definitions/schemaArray\" },\n anyOf: { $ref: \"#/definitions/schemaArray\" },\n oneOf: { $ref: \"#/definitions/schemaArray\" },\n not: { $ref: \"#\" }\n },\n dependencies: {\n exclusiveMaximum: [\"maximum\"],\n exclusiveMinimum: [\"minimum\"]\n },\n default: { }\n};\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport default (additionalOptions = {}) => {\n const ajv = new Ajv({\n meta: false,\n useDefaults: true,\n validateSchema: false,\n missingRefs: \"ignore\",\n verbose: true,\n schemaId: \"auto\",\n ...additionalOptions\n });\n\n ajv.addMetaSchema(metaSchema);\n // eslint-disable-next-line no-underscore-dangle\n ajv._opts.defaultMeta = metaSchema.id;\n\n return ajv;\n};\n","/**\n * @fileoverview Defines a schema for configs.\n * @author Sylvan Mably\n */\n\nconst baseConfigProperties = {\n $schema: { type: \"string\" },\n env: { type: \"object\" },\n extends: { $ref: \"#/definitions/stringOrStrings\" },\n globals: { type: \"object\" },\n overrides: {\n type: \"array\",\n items: { $ref: \"#/definitions/overrideConfig\" },\n additionalItems: false\n },\n parser: { type: [\"string\", \"null\"] },\n parserOptions: { type: \"object\" },\n plugins: { type: \"array\" },\n processor: { type: \"string\" },\n rules: { type: \"object\" },\n settings: { type: \"object\" },\n noInlineConfig: { type: \"boolean\" },\n reportUnusedDisableDirectives: { type: \"boolean\" },\n\n ecmaFeatures: { type: \"object\" } // deprecated; logs a warning when used\n};\n\nconst configSchema = {\n definitions: {\n stringOrStrings: {\n oneOf: [\n { type: \"string\" },\n {\n type: \"array\",\n items: { type: \"string\" },\n additionalItems: false\n }\n ]\n },\n stringOrStringsRequired: {\n oneOf: [\n { type: \"string\" },\n {\n type: \"array\",\n items: { type: \"string\" },\n additionalItems: false,\n minItems: 1\n }\n ]\n },\n\n // Config at top-level.\n objectConfig: {\n type: \"object\",\n properties: {\n root: { type: \"boolean\" },\n ignorePatterns: { $ref: \"#/definitions/stringOrStrings\" },\n ...baseConfigProperties\n },\n additionalProperties: false\n },\n\n // Config in `overrides`.\n overrideConfig: {\n type: \"object\",\n properties: {\n excludedFiles: { $ref: \"#/definitions/stringOrStrings\" },\n files: { $ref: \"#/definitions/stringOrStringsRequired\" },\n ...baseConfigProperties\n },\n required: [\"files\"],\n additionalProperties: false\n }\n },\n\n $ref: \"#/definitions/objectConfig\"\n};\n\nexport default configSchema;\n","/**\n * @fileoverview Defines environment settings and globals.\n * @author Elan Shanker\n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport globals from \"globals\";\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\n/**\n * Get the object that has difference.\n * @param {Record} current The newer object.\n * @param {Record} prev The older object.\n * @returns {Record} The difference object.\n */\nfunction getDiff(current, prev) {\n const retv = {};\n\n for (const [key, value] of Object.entries(current)) {\n if (!Object.hasOwnProperty.call(prev, key)) {\n retv[key] = value;\n }\n }\n\n return retv;\n}\n\nconst newGlobals2015 = getDiff(globals.es2015, globals.es5); // 19 variables such as Promise, Map, ...\nconst newGlobals2017 = {\n Atomics: false,\n SharedArrayBuffer: false\n};\nconst newGlobals2020 = {\n BigInt: false,\n BigInt64Array: false,\n BigUint64Array: false,\n globalThis: false\n};\n\nconst newGlobals2021 = {\n AggregateError: false,\n FinalizationRegistry: false,\n WeakRef: false\n};\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/** @type {Map} */\nexport default new Map(Object.entries({\n\n // Language\n builtin: {\n globals: globals.es5\n },\n es6: {\n globals: newGlobals2015,\n parserOptions: {\n ecmaVersion: 6\n }\n },\n es2015: {\n globals: newGlobals2015,\n parserOptions: {\n ecmaVersion: 6\n }\n },\n es2016: {\n globals: newGlobals2015,\n parserOptions: {\n ecmaVersion: 7\n }\n },\n es2017: {\n globals: { ...newGlobals2015, ...newGlobals2017 },\n parserOptions: {\n ecmaVersion: 8\n }\n },\n es2018: {\n globals: { ...newGlobals2015, ...newGlobals2017 },\n parserOptions: {\n ecmaVersion: 9\n }\n },\n es2019: {\n globals: { ...newGlobals2015, ...newGlobals2017 },\n parserOptions: {\n ecmaVersion: 10\n }\n },\n es2020: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },\n parserOptions: {\n ecmaVersion: 11\n }\n },\n es2021: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 12\n }\n },\n es2022: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 13\n }\n },\n es2023: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 14\n }\n },\n es2024: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 15\n }\n },\n\n // Platforms\n browser: {\n globals: globals.browser\n },\n node: {\n globals: globals.node,\n parserOptions: {\n ecmaFeatures: {\n globalReturn: true\n }\n }\n },\n \"shared-node-browser\": {\n globals: globals[\"shared-node-browser\"]\n },\n worker: {\n globals: globals.worker\n },\n serviceworker: {\n globals: globals.serviceworker\n },\n\n // Frameworks\n commonjs: {\n globals: globals.commonjs,\n parserOptions: {\n ecmaFeatures: {\n globalReturn: true\n }\n }\n },\n amd: {\n globals: globals.amd\n },\n mocha: {\n globals: globals.mocha\n },\n jasmine: {\n globals: globals.jasmine\n },\n jest: {\n globals: globals.jest\n },\n phantomjs: {\n globals: globals.phantomjs\n },\n jquery: {\n globals: globals.jquery\n },\n qunit: {\n globals: globals.qunit\n },\n prototypejs: {\n globals: globals.prototypejs\n },\n shelljs: {\n globals: globals.shelljs\n },\n meteor: {\n globals: globals.meteor\n },\n mongo: {\n globals: globals.mongo\n },\n protractor: {\n globals: globals.protractor\n },\n applescript: {\n globals: globals.applescript\n },\n nashorn: {\n globals: globals.nashorn\n },\n atomtest: {\n globals: globals.atomtest\n },\n embertest: {\n globals: globals.embertest\n },\n webextensions: {\n globals: globals.webextensions\n },\n greasemonkey: {\n globals: globals.greasemonkey\n }\n}));\n","/**\n * @fileoverview Validates configs.\n * @author Brandon Mills\n */\n\n/* eslint class-methods-use-this: \"off\" */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport util from \"util\";\nimport * as ConfigOps from \"./config-ops.js\";\nimport { emitDeprecationWarning } from \"./deprecation-warnings.js\";\nimport ajvOrig from \"./ajv.js\";\nimport configSchema from \"../../conf/config-schema.js\";\nimport BuiltInEnvironments from \"../../conf/environments.js\";\n\nconst ajv = ajvOrig();\n\nconst ruleValidators = new WeakMap();\nconst noop = Function.prototype;\n\n//------------------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------------------\nlet validateSchema;\nconst severityMap = {\n error: 2,\n warn: 1,\n off: 0\n};\n\nconst validated = new WeakSet();\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\nexport default class ConfigValidator {\n constructor({ builtInRules = new Map() } = {}) {\n this.builtInRules = builtInRules;\n }\n\n /**\n * Gets a complete options schema for a rule.\n * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object\n * @returns {Object} JSON Schema for the rule's options.\n */\n getRuleOptionsSchema(rule) {\n if (!rule) {\n return null;\n }\n\n const schema = rule.schema || rule.meta && rule.meta.schema;\n\n // Given a tuple of schemas, insert warning level at the beginning\n if (Array.isArray(schema)) {\n if (schema.length) {\n return {\n type: \"array\",\n items: schema,\n minItems: 0,\n maxItems: schema.length\n };\n }\n return {\n type: \"array\",\n minItems: 0,\n maxItems: 0\n };\n\n }\n\n // Given a full schema, leave it alone\n return schema || null;\n }\n\n /**\n * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.\n * @param {options} options The given options for the rule.\n * @returns {number|string} The rule's severity value\n */\n validateRuleSeverity(options) {\n const severity = Array.isArray(options) ? options[0] : options;\n const normSeverity = typeof severity === \"string\" ? severityMap[severity.toLowerCase()] : severity;\n\n if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {\n return normSeverity;\n }\n\n throw new Error(`\\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, \"\\\"\").replace(/\\n/gu, \"\")}').\\n`);\n\n }\n\n /**\n * Validates the non-severity options passed to a rule, based on its schema.\n * @param {{create: Function}} rule The rule to validate\n * @param {Array} localOptions The options for the rule, excluding severity\n * @returns {void}\n */\n validateRuleSchema(rule, localOptions) {\n if (!ruleValidators.has(rule)) {\n const schema = this.getRuleOptionsSchema(rule);\n\n if (schema) {\n ruleValidators.set(rule, ajv.compile(schema));\n }\n }\n\n const validateRule = ruleValidators.get(rule);\n\n if (validateRule) {\n validateRule(localOptions);\n if (validateRule.errors) {\n throw new Error(validateRule.errors.map(\n error => `\\tValue ${JSON.stringify(error.data)} ${error.message}.\\n`\n ).join(\"\"));\n }\n }\n }\n\n /**\n * Validates a rule's options against its schema.\n * @param {{create: Function}|null} rule The rule that the config is being validated for\n * @param {string} ruleId The rule's unique name.\n * @param {Array|number} options The given options for the rule.\n * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,\n * no source is prepended to the message.\n * @returns {void}\n */\n validateRuleOptions(rule, ruleId, options, source = null) {\n try {\n const severity = this.validateRuleSeverity(options);\n\n if (severity !== 0) {\n this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);\n }\n } catch (err) {\n const enhancedMessage = `Configuration for rule \"${ruleId}\" is invalid:\\n${err.message}`;\n\n if (typeof source === \"string\") {\n throw new Error(`${source}:\\n\\t${enhancedMessage}`);\n } else {\n throw new Error(enhancedMessage);\n }\n }\n }\n\n /**\n * Validates an environment object\n * @param {Object} environment The environment config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.\n * @returns {void}\n */\n validateEnvironment(\n environment,\n source,\n getAdditionalEnv = noop\n ) {\n\n // not having an environment is ok\n if (!environment) {\n return;\n }\n\n Object.keys(environment).forEach(id => {\n const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null;\n\n if (!env) {\n const message = `${source}:\\n\\tEnvironment key \"${id}\" is unknown\\n`;\n\n throw new Error(message);\n }\n });\n }\n\n /**\n * Validates a rules config object\n * @param {Object} rulesConfig The rules config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules\n * @returns {void}\n */\n validateRules(\n rulesConfig,\n source,\n getAdditionalRule = noop\n ) {\n if (!rulesConfig) {\n return;\n }\n\n Object.keys(rulesConfig).forEach(id => {\n const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;\n\n this.validateRuleOptions(rule, id, rulesConfig[id], source);\n });\n }\n\n /**\n * Validates a `globals` section of a config file\n * @param {Object} globalsConfig The `globals` section\n * @param {string|null} source The name of the configuration source to report in the event of an error.\n * @returns {void}\n */\n validateGlobals(globalsConfig, source = null) {\n if (!globalsConfig) {\n return;\n }\n\n Object.entries(globalsConfig)\n .forEach(([configuredGlobal, configuredValue]) => {\n try {\n ConfigOps.normalizeConfigGlobal(configuredValue);\n } catch (err) {\n throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\\n${err.message}`);\n }\n });\n }\n\n /**\n * Validate `processor` configuration.\n * @param {string|undefined} processorName The processor name.\n * @param {string} source The name of config file.\n * @param {function(id:string): Processor} getProcessor The getter of defined processors.\n * @returns {void}\n */\n validateProcessor(processorName, source, getProcessor) {\n if (processorName && !getProcessor(processorName)) {\n throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);\n }\n }\n\n /**\n * Formats an array of schema validation errors.\n * @param {Array} errors An array of error messages to format.\n * @returns {string} Formatted error message\n */\n formatErrors(errors) {\n return errors.map(error => {\n if (error.keyword === \"additionalProperties\") {\n const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;\n\n return `Unexpected top-level property \"${formattedPropertyPath}\"`;\n }\n if (error.keyword === \"type\") {\n const formattedField = error.dataPath.slice(1);\n const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join(\"/\") : error.schema;\n const formattedValue = JSON.stringify(error.data);\n\n return `Property \"${formattedField}\" is the wrong type (expected ${formattedExpectedType} but got \\`${formattedValue}\\`)`;\n }\n\n const field = error.dataPath[0] === \".\" ? error.dataPath.slice(1) : error.dataPath;\n\n return `\"${field}\" ${error.message}. Value: ${JSON.stringify(error.data)}`;\n }).map(message => `\\t- ${message}.\\n`).join(\"\");\n }\n\n /**\n * Validates the top level properties of the config object.\n * @param {Object} config The config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @returns {void}\n */\n validateConfigSchema(config, source = null) {\n validateSchema = validateSchema || ajv.compile(configSchema);\n\n if (!validateSchema(config)) {\n throw new Error(`ESLint configuration in ${source} is invalid:\\n${this.formatErrors(validateSchema.errors)}`);\n }\n\n if (Object.hasOwnProperty.call(config, \"ecmaFeatures\")) {\n emitDeprecationWarning(source, \"ESLINT_LEGACY_ECMAFEATURES\");\n }\n }\n\n /**\n * Validates an entire config object.\n * @param {Object} config The config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.\n * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.\n * @returns {void}\n */\n validate(config, source, getAdditionalRule, getAdditionalEnv) {\n this.validateConfigSchema(config, source);\n this.validateRules(config.rules, source, getAdditionalRule);\n this.validateEnvironment(config.env, source, getAdditionalEnv);\n this.validateGlobals(config.globals, source);\n\n for (const override of config.overrides || []) {\n this.validateRules(override.rules, source, getAdditionalRule);\n this.validateEnvironment(override.env, source, getAdditionalEnv);\n this.validateGlobals(config.globals, source);\n }\n }\n\n /**\n * Validate config array object.\n * @param {ConfigArray} configArray The config array to validate.\n * @returns {void}\n */\n validateConfigArray(configArray) {\n const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);\n const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);\n const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);\n\n // Validate.\n for (const element of configArray) {\n if (validated.has(element)) {\n continue;\n }\n validated.add(element);\n\n this.validateEnvironment(element.env, element.name, getPluginEnv);\n this.validateGlobals(element.globals, element.name);\n this.validateProcessor(element.processor, element.name, getPluginProcessor);\n this.validateRules(element.rules, element.name, getPluginRule);\n }\n }\n\n}\n","/**\n * @fileoverview Common helpers for naming of plugins, formatters and configs\n */\n\nconst NAMESPACE_REGEX = /^@.*\\//iu;\n\n/**\n * Brings package name to correct format based on prefix\n * @param {string} name The name of the package.\n * @param {string} prefix Can be either \"eslint-plugin\", \"eslint-config\" or \"eslint-formatter\"\n * @returns {string} Normalized name of the package\n * @private\n */\nfunction normalizePackageName(name, prefix) {\n let normalizedName = name;\n\n /**\n * On Windows, name can come in with Windows slashes instead of Unix slashes.\n * Normalize to Unix first to avoid errors later on.\n * https://github.com/eslint/eslint/issues/5644\n */\n if (normalizedName.includes(\"\\\\\")) {\n normalizedName = normalizedName.replace(/\\\\/gu, \"/\");\n }\n\n if (normalizedName.charAt(0) === \"@\") {\n\n /**\n * it's a scoped package\n * package name is the prefix, or just a username\n */\n const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, \"u\"),\n scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, \"u\");\n\n if (scopedPackageShortcutRegex.test(normalizedName)) {\n normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);\n } else if (!scopedPackageNameRegex.test(normalizedName.split(\"/\")[1])) {\n\n /**\n * for scoped packages, insert the prefix after the first / unless\n * the path is already @scope/eslint or @scope/eslint-xxx-yyy\n */\n normalizedName = normalizedName.replace(/^@([^/]+)\\/(.*)$/u, `@$1/${prefix}-$2`);\n }\n } else if (!normalizedName.startsWith(`${prefix}-`)) {\n normalizedName = `${prefix}-${normalizedName}`;\n }\n\n return normalizedName;\n}\n\n/**\n * Removes the prefix from a fullname.\n * @param {string} fullname The term which may have the prefix.\n * @param {string} prefix The prefix to remove.\n * @returns {string} The term without prefix.\n */\nfunction getShorthandName(fullname, prefix) {\n if (fullname[0] === \"@\") {\n let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, \"u\").exec(fullname);\n\n if (matchResult) {\n return matchResult[1];\n }\n\n matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, \"u\").exec(fullname);\n if (matchResult) {\n return `${matchResult[1]}/${matchResult[2]}`;\n }\n } else if (fullname.startsWith(`${prefix}-`)) {\n return fullname.slice(prefix.length + 1);\n }\n\n return fullname;\n}\n\n/**\n * Gets the scope (namespace) of a term.\n * @param {string} term The term which may have the namespace.\n * @returns {string} The namespace of the term if it has one.\n */\nfunction getNamespaceFromTerm(term) {\n const match = term.match(NAMESPACE_REGEX);\n\n return match ? match[0] : \"\";\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport {\n normalizePackageName,\n getShorthandName,\n getNamespaceFromTerm\n};\n","/**\n * @fileoverview Package exports for @eslint/eslintrc\n * @author Nicholas C. Zakas\n */\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport * as ConfigOps from \"./shared/config-ops.js\";\nimport ConfigValidator from \"./shared/config-validator.js\";\nimport * as naming from \"./shared/naming.js\";\nimport environments from \"../conf/environments.js\";\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\nconst Legacy = {\n environments,\n\n // shared\n ConfigOps,\n ConfigValidator,\n naming\n};\n\nexport {\n Legacy\n};\n"],"names":["path","Ajv","globals","util","BuiltInEnvironments","ConfigOps.normalizeConfigGlobal"],"mappings":";;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,qBAAqB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC;AACtD,IAAI,aAAa,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,KAAK;AACxE,QAAQ,GAAG,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;AAC3B,QAAQ,OAAO,GAAG,CAAC;AACnB,KAAK,EAAE,EAAE,CAAC;AACV,IAAI,gBAAgB,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACzD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,eAAe,CAAC,UAAU,EAAE;AACrC,IAAI,MAAM,aAAa,GAAG,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,GAAG,UAAU,CAAC;AACjF;AACA,IAAI,IAAI,aAAa,KAAK,CAAC,I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MAAM,CAAC,CAAC,CAAC,CAAC,EAAE;AAClD,QAAQ,OAAO,QAAQ,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACjD,KAAK;AACL;AACA,IAAI,OAAO,QAAQ,CAAC;AACpB,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,oBAAoB,CAAC,IAAI,EAAE;AACpC,IAAI,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;AAC9C;AACA,IAAI,OAAO,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;AACjC;;;;;;;;;ACrFA;AACA;AACA;AACA;AASA;AACA;AACA;AACA;AACA;AACK,MAAC,MAAM,GAAG;AACf,IAAI,YAAY;AAChB;AACA;AACA,IAAI,SAAS;AACb,IAAI,eAAe;AACnB,IAAI,MAAM;AACV;;;;"} \ No newline at end of file diff --git a/node_modules/@eslint/eslintrc/dist/eslintrc.cjs b/node_modules/@eslint/eslintrc/dist/eslintrc.cjs new file mode 100644 index 0000000..eb2ed8d --- /dev/null +++ b/node_modules/@eslint/eslintrc/dist/eslintrc.cjs @@ -0,0 +1,4344 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var debugOrig = require('debug'); +var fs = require('fs'); +var importFresh = require('import-fresh'); +var Module = require('module'); +var path = require('path'); +var stripComments = require('strip-json-comments'); +var assert = require('assert'); +var ignore = require('ignore'); +var util = require('util'); +var minimatch = require('minimatch'); +var Ajv = require('ajv'); +var globals = require('globals'); +var os = require('os'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var debugOrig__default = /*#__PURE__*/_interopDefaultLegacy(debugOrig); +var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs); +var importFresh__default = /*#__PURE__*/_interopDefaultLegacy(importFresh); +var Module__default = /*#__PURE__*/_interopDefaultLegacy(Module); +var path__default = /*#__PURE__*/_interopDefaultLegacy(path); +var stripComments__default = /*#__PURE__*/_interopDefaultLegacy(stripComments); +var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert); +var ignore__default = /*#__PURE__*/_interopDefaultLegacy(ignore); +var util__default = /*#__PURE__*/_interopDefaultLegacy(util); +var minimatch__default = /*#__PURE__*/_interopDefaultLegacy(minimatch); +var Ajv__default = /*#__PURE__*/_interopDefaultLegacy(Ajv); +var globals__default = /*#__PURE__*/_interopDefaultLegacy(globals); +var os__default = /*#__PURE__*/_interopDefaultLegacy(os); + +/** + * @fileoverview `IgnorePattern` class. + * + * `IgnorePattern` class has the set of glob patterns and the base path. + * + * It provides two static methods. + * + * - `IgnorePattern.createDefaultIgnore(cwd)` + * Create the default predicate function. + * - `IgnorePattern.createIgnore(ignorePatterns)` + * Create the predicate function from multiple `IgnorePattern` objects. + * + * It provides two properties and a method. + * + * - `patterns` + * The glob patterns that ignore to lint. + * - `basePath` + * The base path of the glob patterns. If absolute paths existed in the + * glob patterns, those are handled as relative paths to the base path. + * - `getPatternsRelativeTo(basePath)` + * Get `patterns` as modified for a given base path. It modifies the + * absolute paths in the patterns as prepending the difference of two base + * paths. + * + * `ConfigArrayFactory` creates `IgnorePattern` objects when it processes + * `ignorePatterns` properties. + * + * @author Toru Nagashima + */ + +const debug$3 = debugOrig__default["default"]("eslintrc:ignore-pattern"); + +/** @typedef {ReturnType} Ignore */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Get the path to the common ancestor directory of given paths. + * @param {string[]} sourcePaths The paths to calculate the common ancestor. + * @returns {string} The path to the common ancestor directory. + */ +function getCommonAncestorPath(sourcePaths) { + let result = sourcePaths[0]; + + for (let i = 1; i < sourcePaths.length; ++i) { + const a = result; + const b = sourcePaths[i]; + + // Set the shorter one (it's the common ancestor if one includes the other). + result = a.length < b.length ? a : b; + + // Set the common ancestor. + for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) { + if (a[j] !== b[j]) { + result = a.slice(0, lastSepPos); + break; + } + if (a[j] === path__default["default"].sep) { + lastSepPos = j; + } + } + } + + let resolvedResult = result || path__default["default"].sep; + + // if Windows common ancestor is root of drive must have trailing slash to be absolute. + if (resolvedResult && resolvedResult.endsWith(":") && process.platform === "win32") { + resolvedResult += path__default["default"].sep; + } + return resolvedResult; +} + +/** + * Make relative path. + * @param {string} from The source path to get relative path. + * @param {string} to The destination path to get relative path. + * @returns {string} The relative path. + */ +function relative(from, to) { + const relPath = path__default["default"].relative(from, to); + + if (path__default["default"].sep === "/") { + return relPath; + } + return relPath.split(path__default["default"].sep).join("/"); +} + +/** + * Get the trailing slash if existed. + * @param {string} filePath The path to check. + * @returns {string} The trailing slash if existed. + */ +function dirSuffix(filePath) { + const isDir = ( + filePath.endsWith(path__default["default"].sep) || + (process.platform === "win32" && filePath.endsWith("/")) + ); + + return isDir ? "/" : ""; +} + +const DefaultPatterns = Object.freeze(["/**/node_modules/*"]); +const DotPatterns = Object.freeze([".*", "!.eslintrc.*", "!../"]); + +//------------------------------------------------------------------------------ +// Public +//------------------------------------------------------------------------------ + +class IgnorePattern { + + /** + * The default patterns. + * @type {string[]} + */ + static get DefaultPatterns() { + return DefaultPatterns; + } + + /** + * Create the default predicate function. + * @param {string} cwd The current working directory. + * @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}} + * The preficate function. + * The first argument is an absolute path that is checked. + * The second argument is the flag to not ignore dotfiles. + * If the predicate function returned `true`, it means the path should be ignored. + */ + static createDefaultIgnore(cwd) { + return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]); + } + + /** + * Create the predicate function from multiple `IgnorePattern` objects. + * @param {IgnorePattern[]} ignorePatterns The list of ignore patterns. + * @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}} + * The preficate function. + * The first argument is an absolute path that is checked. + * The second argument is the flag to not ignore dotfiles. + * If the predicate function returned `true`, it means the path should be ignored. + */ + static createIgnore(ignorePatterns) { + debug$3("Create with: %o", ignorePatterns); + + const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath)); + const patterns = [].concat( + ...ignorePatterns.map(p => p.getPatternsRelativeTo(basePath)) + ); + const ig = ignore__default["default"]({ allowRelativePaths: true }).add([...DotPatterns, ...patterns]); + const dotIg = ignore__default["default"]({ allowRelativePaths: true }).add(patterns); + + debug$3(" processed: %o", { basePath, patterns }); + + return Object.assign( + (filePath, dot = false) => { + assert__default["default"](path__default["default"].isAbsolute(filePath), "'filePath' should be an absolute path."); + const relPathRaw = relative(basePath, filePath); + const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath)); + const adoptedIg = dot ? dotIg : ig; + const result = relPath !== "" && adoptedIg.ignores(relPath); + + debug$3("Check", { filePath, dot, relativePath: relPath, result }); + return result; + }, + { basePath, patterns } + ); + } + + /** + * Initialize a new `IgnorePattern` instance. + * @param {string[]} patterns The glob patterns that ignore to lint. + * @param {string} basePath The base path of `patterns`. + */ + constructor(patterns, basePath) { + assert__default["default"](path__default["default"].isAbsolute(basePath), "'basePath' should be an absolute path."); + + /** + * The glob patterns that ignore to lint. + * @type {string[]} + */ + this.patterns = patterns; + + /** + * The base path of `patterns`. + * @type {string} + */ + this.basePath = basePath; + + /** + * If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`. + * + * It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility. + * It's `false` as-is for `ignorePatterns` property in config files. + * @type {boolean} + */ + this.loose = false; + } + + /** + * Get `patterns` as modified for a given base path. It modifies the + * absolute paths in the patterns as prepending the difference of two base + * paths. + * @param {string} newBasePath The base path. + * @returns {string[]} Modifired patterns. + */ + getPatternsRelativeTo(newBasePath) { + assert__default["default"](path__default["default"].isAbsolute(newBasePath), "'newBasePath' should be an absolute path."); + const { basePath, loose, patterns } = this; + + if (newBasePath === basePath) { + return patterns; + } + const prefix = `/${relative(newBasePath, basePath)}`; + + return patterns.map(pattern => { + const negative = pattern.startsWith("!"); + const head = negative ? "!" : ""; + const body = negative ? pattern.slice(1) : pattern; + + if (body.startsWith("/") || body.startsWith("../")) { + return `${head}${prefix}${body}`; + } + return loose ? pattern : `${head}${prefix}/**/${body}`; + }); + } +} + +/** + * @fileoverview `ExtractedConfig` class. + * + * `ExtractedConfig` class expresses a final configuration for a specific file. + * + * It provides one method. + * + * - `toCompatibleObjectAsConfigFileContent()` + * Convert this configuration to the compatible object as the content of + * config files. It converts the loaded parser and plugins to strings. + * `CLIEngine#getConfigForFile(filePath)` method uses this method. + * + * `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance. + * + * @author Toru Nagashima + */ + +// For VSCode intellisense +/** @typedef {import("../../shared/types").ConfigData} ConfigData */ +/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */ +/** @typedef {import("../../shared/types").SeverityConf} SeverityConf */ +/** @typedef {import("./config-dependency").DependentParser} DependentParser */ +/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */ + +/** + * Check if `xs` starts with `ys`. + * @template T + * @param {T[]} xs The array to check. + * @param {T[]} ys The array that may be the first part of `xs`. + * @returns {boolean} `true` if `xs` starts with `ys`. + */ +function startsWith(xs, ys) { + return xs.length >= ys.length && ys.every((y, i) => y === xs[i]); +} + +/** + * The class for extracted config data. + */ +class ExtractedConfig { + constructor() { + + /** + * The config name what `noInlineConfig` setting came from. + * @type {string} + */ + this.configNameOfNoInlineConfig = ""; + + /** + * Environments. + * @type {Record} + */ + this.env = {}; + + /** + * Global variables. + * @type {Record} + */ + this.globals = {}; + + /** + * The glob patterns that ignore to lint. + * @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined} + */ + this.ignores = void 0; + + /** + * The flag that disables directive comments. + * @type {boolean|undefined} + */ + this.noInlineConfig = void 0; + + /** + * Parser definition. + * @type {DependentParser|null} + */ + this.parser = null; + + /** + * Options for the parser. + * @type {Object} + */ + this.parserOptions = {}; + + /** + * Plugin definitions. + * @type {Record} + */ + this.plugins = {}; + + /** + * Processor ID. + * @type {string|null} + */ + this.processor = null; + + /** + * The flag that reports unused `eslint-disable` directive comments. + * @type {boolean|undefined} + */ + this.reportUnusedDisableDirectives = void 0; + + /** + * Rule settings. + * @type {Record} + */ + this.rules = {}; + + /** + * Shared settings. + * @type {Object} + */ + this.settings = {}; + } + + /** + * Convert this config to the compatible object as a config file content. + * @returns {ConfigData} The converted object. + */ + toCompatibleObjectAsConfigFileContent() { + const { + /* eslint-disable no-unused-vars */ + configNameOfNoInlineConfig: _ignore1, + processor: _ignore2, + /* eslint-enable no-unused-vars */ + ignores, + ...config + } = this; + + config.parser = config.parser && config.parser.filePath; + config.plugins = Object.keys(config.plugins).filter(Boolean).reverse(); + config.ignorePatterns = ignores ? ignores.patterns : []; + + // Strip the default patterns from `ignorePatterns`. + if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) { + config.ignorePatterns = + config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length); + } + + return config; + } +} + +/** + * @fileoverview `ConfigArray` class. + * + * `ConfigArray` class expresses the full of a configuration. It has the entry + * config file, base config files that were extended, loaded parsers, and loaded + * plugins. + * + * `ConfigArray` class provides three properties and two methods. + * + * - `pluginEnvironments` + * - `pluginProcessors` + * - `pluginRules` + * The `Map` objects that contain the members of all plugins that this + * config array contains. Those map objects don't have mutation methods. + * Those keys are the member ID such as `pluginId/memberName`. + * - `isRoot()` + * If `true` then this configuration has `root:true` property. + * - `extractConfig(filePath)` + * Extract the final configuration for a given file. This means merging + * every config array element which that `criteria` property matched. The + * `filePath` argument must be an absolute path. + * + * `ConfigArrayFactory` provides the loading logic of config files. + * + * @author Toru Nagashima + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// Define types for VSCode IntelliSense. +/** @typedef {import("../../shared/types").Environment} Environment */ +/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */ +/** @typedef {import("../../shared/types").RuleConf} RuleConf */ +/** @typedef {import("../../shared/types").Rule} Rule */ +/** @typedef {import("../../shared/types").Plugin} Plugin */ +/** @typedef {import("../../shared/types").Processor} Processor */ +/** @typedef {import("./config-dependency").DependentParser} DependentParser */ +/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */ +/** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */ + +/** + * @typedef {Object} ConfigArrayElement + * @property {string} name The name of this config element. + * @property {string} filePath The path to the source file of this config element. + * @property {InstanceType|null} criteria The tester for the `files` and `excludedFiles` of this config element. + * @property {Record|undefined} env The environment settings. + * @property {Record|undefined} globals The global variable settings. + * @property {IgnorePattern|undefined} ignorePattern The ignore patterns. + * @property {boolean|undefined} noInlineConfig The flag that disables directive comments. + * @property {DependentParser|undefined} parser The parser loader. + * @property {Object|undefined} parserOptions The parser options. + * @property {Record|undefined} plugins The plugin loaders. + * @property {string|undefined} processor The processor name to refer plugin's processor. + * @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments. + * @property {boolean|undefined} root The flag to express root. + * @property {Record|undefined} rules The rule settings + * @property {Object|undefined} settings The shared settings. + * @property {"config" | "ignore" | "implicit-processor"} type The element type. + */ + +/** + * @typedef {Object} ConfigArrayInternalSlots + * @property {Map} cache The cache to extract configs. + * @property {ReadonlyMap|null} envMap The map from environment ID to environment definition. + * @property {ReadonlyMap|null} processorMap The map from processor ID to environment definition. + * @property {ReadonlyMap|null} ruleMap The map from rule ID to rule definition. + */ + +/** @type {WeakMap} */ +const internalSlotsMap$2 = new class extends WeakMap { + get(key) { + let value = super.get(key); + + if (!value) { + value = { + cache: new Map(), + envMap: null, + processorMap: null, + ruleMap: null + }; + super.set(key, value); + } + + return value; + } +}(); + +/** + * Get the indices which are matched to a given file. + * @param {ConfigArrayElement[]} elements The elements. + * @param {string} filePath The path to a target file. + * @returns {number[]} The indices. + */ +function getMatchedIndices(elements, filePath) { + const indices = []; + + for (let i = elements.length - 1; i >= 0; --i) { + const element = elements[i]; + + if (!element.criteria || (filePath && element.criteria.test(filePath))) { + indices.push(i); + } + } + + return indices; +} + +/** + * Check if a value is a non-null object. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is a non-null object. + */ +function isNonNullObject(x) { + return typeof x === "object" && x !== null; +} + +/** + * Merge two objects. + * + * Assign every property values of `y` to `x` if `x` doesn't have the property. + * If `x`'s property value is an object, it does recursive. + * @param {Object} target The destination to merge + * @param {Object|undefined} source The source to merge. + * @returns {void} + */ +function mergeWithoutOverwrite(target, source) { + if (!isNonNullObject(source)) { + return; + } + + for (const key of Object.keys(source)) { + if (key === "__proto__") { + continue; + } + + if (isNonNullObject(target[key])) { + mergeWithoutOverwrite(target[key], source[key]); + } else if (target[key] === void 0) { + if (isNonNullObject(source[key])) { + target[key] = Array.isArray(source[key]) ? [] : {}; + mergeWithoutOverwrite(target[key], source[key]); + } else if (source[key] !== void 0) { + target[key] = source[key]; + } + } + } +} + +/** + * The error for plugin conflicts. + */ +class PluginConflictError extends Error { + + /** + * Initialize this error object. + * @param {string} pluginId The plugin ID. + * @param {{filePath:string, importerName:string}[]} plugins The resolved plugins. + */ + constructor(pluginId, plugins) { + super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`); + this.messageTemplate = "plugin-conflict"; + this.messageData = { pluginId, plugins }; + } +} + +/** + * Merge plugins. + * `target`'s definition is prior to `source`'s. + * @param {Record} target The destination to merge + * @param {Record|undefined} source The source to merge. + * @returns {void} + */ +function mergePlugins(target, source) { + if (!isNonNullObject(source)) { + return; + } + + for (const key of Object.keys(source)) { + if (key === "__proto__") { + continue; + } + const targetValue = target[key]; + const sourceValue = source[key]; + + // Adopt the plugin which was found at first. + if (targetValue === void 0) { + if (sourceValue.error) { + throw sourceValue.error; + } + target[key] = sourceValue; + } else if (sourceValue.filePath !== targetValue.filePath) { + throw new PluginConflictError(key, [ + { + filePath: targetValue.filePath, + importerName: targetValue.importerName + }, + { + filePath: sourceValue.filePath, + importerName: sourceValue.importerName + } + ]); + } + } +} + +/** + * Merge rule configs. + * `target`'s definition is prior to `source`'s. + * @param {Record} target The destination to merge + * @param {Record|undefined} source The source to merge. + * @returns {void} + */ +function mergeRuleConfigs(target, source) { + if (!isNonNullObject(source)) { + return; + } + + for (const key of Object.keys(source)) { + if (key === "__proto__") { + continue; + } + const targetDef = target[key]; + const sourceDef = source[key]; + + // Adopt the rule config which was found at first. + if (targetDef === void 0) { + if (Array.isArray(sourceDef)) { + target[key] = [...sourceDef]; + } else { + target[key] = [sourceDef]; + } + + /* + * If the first found rule config is severity only and the current rule + * config has options, merge the severity and the options. + */ + } else if ( + targetDef.length === 1 && + Array.isArray(sourceDef) && + sourceDef.length >= 2 + ) { + targetDef.push(...sourceDef.slice(1)); + } + } +} + +/** + * Create the extracted config. + * @param {ConfigArray} instance The config elements. + * @param {number[]} indices The indices to use. + * @returns {ExtractedConfig} The extracted config. + */ +function createConfig(instance, indices) { + const config = new ExtractedConfig(); + const ignorePatterns = []; + + // Merge elements. + for (const index of indices) { + const element = instance[index]; + + // Adopt the parser which was found at first. + if (!config.parser && element.parser) { + if (element.parser.error) { + throw element.parser.error; + } + config.parser = element.parser; + } + + // Adopt the processor which was found at first. + if (!config.processor && element.processor) { + config.processor = element.processor; + } + + // Adopt the noInlineConfig which was found at first. + if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) { + config.noInlineConfig = element.noInlineConfig; + config.configNameOfNoInlineConfig = element.name; + } + + // Adopt the reportUnusedDisableDirectives which was found at first. + if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) { + config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives; + } + + // Collect ignorePatterns + if (element.ignorePattern) { + ignorePatterns.push(element.ignorePattern); + } + + // Merge others. + mergeWithoutOverwrite(config.env, element.env); + mergeWithoutOverwrite(config.globals, element.globals); + mergeWithoutOverwrite(config.parserOptions, element.parserOptions); + mergeWithoutOverwrite(config.settings, element.settings); + mergePlugins(config.plugins, element.plugins); + mergeRuleConfigs(config.rules, element.rules); + } + + // Create the predicate function for ignore patterns. + if (ignorePatterns.length > 0) { + config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse()); + } + + return config; +} + +/** + * Collect definitions. + * @template T, U + * @param {string} pluginId The plugin ID for prefix. + * @param {Record} defs The definitions to collect. + * @param {Map} map The map to output. + * @param {function(T): U} [normalize] The normalize function for each value. + * @returns {void} + */ +function collect(pluginId, defs, map, normalize) { + if (defs) { + const prefix = pluginId && `${pluginId}/`; + + for (const [key, value] of Object.entries(defs)) { + map.set( + `${prefix}${key}`, + normalize ? normalize(value) : value + ); + } + } +} + +/** + * Normalize a rule definition. + * @param {Function|Rule} rule The rule definition to normalize. + * @returns {Rule} The normalized rule definition. + */ +function normalizePluginRule(rule) { + return typeof rule === "function" ? { create: rule } : rule; +} + +/** + * Delete the mutation methods from a given map. + * @param {Map} map The map object to delete. + * @returns {void} + */ +function deleteMutationMethods(map) { + Object.defineProperties(map, { + clear: { configurable: true, value: void 0 }, + delete: { configurable: true, value: void 0 }, + set: { configurable: true, value: void 0 } + }); +} + +/** + * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array. + * @param {ConfigArrayElement[]} elements The config elements. + * @param {ConfigArrayInternalSlots} slots The internal slots. + * @returns {void} + */ +function initPluginMemberMaps(elements, slots) { + const processed = new Set(); + + slots.envMap = new Map(); + slots.processorMap = new Map(); + slots.ruleMap = new Map(); + + for (const element of elements) { + if (!element.plugins) { + continue; + } + + for (const [pluginId, value] of Object.entries(element.plugins)) { + const plugin = value.definition; + + if (!plugin || processed.has(pluginId)) { + continue; + } + processed.add(pluginId); + + collect(pluginId, plugin.environments, slots.envMap); + collect(pluginId, plugin.processors, slots.processorMap); + collect(pluginId, plugin.rules, slots.ruleMap, normalizePluginRule); + } + } + + deleteMutationMethods(slots.envMap); + deleteMutationMethods(slots.processorMap); + deleteMutationMethods(slots.ruleMap); +} + +/** + * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array. + * @param {ConfigArray} instance The config elements. + * @returns {ConfigArrayInternalSlots} The extracted config. + */ +function ensurePluginMemberMaps(instance) { + const slots = internalSlotsMap$2.get(instance); + + if (!slots.ruleMap) { + initPluginMemberMaps(instance, slots); + } + + return slots; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * The Config Array. + * + * `ConfigArray` instance contains all settings, parsers, and plugins. + * You need to call `ConfigArray#extractConfig(filePath)` method in order to + * extract, merge and get only the config data which is related to an arbitrary + * file. + * @extends {Array} + */ +class ConfigArray extends Array { + + /** + * Get the plugin environments. + * The returned map cannot be mutated. + * @type {ReadonlyMap} The plugin environments. + */ + get pluginEnvironments() { + return ensurePluginMemberMaps(this).envMap; + } + + /** + * Get the plugin processors. + * The returned map cannot be mutated. + * @type {ReadonlyMap} The plugin processors. + */ + get pluginProcessors() { + return ensurePluginMemberMaps(this).processorMap; + } + + /** + * Get the plugin rules. + * The returned map cannot be mutated. + * @returns {ReadonlyMap} The plugin rules. + */ + get pluginRules() { + return ensurePluginMemberMaps(this).ruleMap; + } + + /** + * Check if this config has `root` flag. + * @returns {boolean} `true` if this config array is root. + */ + isRoot() { + for (let i = this.length - 1; i >= 0; --i) { + const root = this[i].root; + + if (typeof root === "boolean") { + return root; + } + } + return false; + } + + /** + * Extract the config data which is related to a given file. + * @param {string} filePath The absolute path to the target file. + * @returns {ExtractedConfig} The extracted config data. + */ + extractConfig(filePath) { + const { cache } = internalSlotsMap$2.get(this); + const indices = getMatchedIndices(this, filePath); + const cacheKey = indices.join(","); + + if (!cache.has(cacheKey)) { + cache.set(cacheKey, createConfig(this, indices)); + } + + return cache.get(cacheKey); + } + + /** + * Check if a given path is an additional lint target. + * @param {string} filePath The absolute path to the target file. + * @returns {boolean} `true` if the file is an additional lint target. + */ + isAdditionalTargetPath(filePath) { + for (const { criteria, type } of this) { + if ( + type === "config" && + criteria && + !criteria.endsWithWildcard && + criteria.test(filePath) + ) { + return true; + } + } + return false; + } +} + +/** + * Get the used extracted configs. + * CLIEngine will use this method to collect used deprecated rules. + * @param {ConfigArray} instance The config array object to get. + * @returns {ExtractedConfig[]} The used extracted configs. + * @private + */ +function getUsedExtractedConfigs(instance) { + const { cache } = internalSlotsMap$2.get(instance); + + return Array.from(cache.values()); +} + +/** + * @fileoverview `ConfigDependency` class. + * + * `ConfigDependency` class expresses a loaded parser or plugin. + * + * If the parser or plugin was loaded successfully, it has `definition` property + * and `filePath` property. Otherwise, it has `error` property. + * + * When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it + * omits `definition` property. + * + * `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers + * or plugins. + * + * @author Toru Nagashima + */ + +/** + * The class is to store parsers or plugins. + * This class hides the loaded object from `JSON.stringify()` and `console.log`. + * @template T + */ +class ConfigDependency { + + /** + * Initialize this instance. + * @param {Object} data The dependency data. + * @param {T} [data.definition] The dependency if the loading succeeded. + * @param {T} [data.original] The original, non-normalized dependency if the loading succeeded. + * @param {Error} [data.error] The error object if the loading failed. + * @param {string} [data.filePath] The actual path to the dependency if the loading succeeded. + * @param {string} data.id The ID of this dependency. + * @param {string} data.importerName The name of the config file which loads this dependency. + * @param {string} data.importerPath The path to the config file which loads this dependency. + */ + constructor({ + definition = null, + original = null, + error = null, + filePath = null, + id, + importerName, + importerPath + }) { + + /** + * The loaded dependency if the loading succeeded. + * @type {T|null} + */ + this.definition = definition; + + /** + * The original dependency as loaded directly from disk if the loading succeeded. + * @type {T|null} + */ + this.original = original; + + /** + * The error object if the loading failed. + * @type {Error|null} + */ + this.error = error; + + /** + * The loaded dependency if the loading succeeded. + * @type {string|null} + */ + this.filePath = filePath; + + /** + * The ID of this dependency. + * @type {string} + */ + this.id = id; + + /** + * The name of the config file which loads this dependency. + * @type {string} + */ + this.importerName = importerName; + + /** + * The path to the config file which loads this dependency. + * @type {string} + */ + this.importerPath = importerPath; + } + + // eslint-disable-next-line jsdoc/require-description + /** + * @returns {Object} a JSON compatible object. + */ + toJSON() { + const obj = this[util__default["default"].inspect.custom](); + + // Display `error.message` (`Error#message` is unenumerable). + if (obj.error instanceof Error) { + obj.error = { ...obj.error, message: obj.error.message }; + } + + return obj; + } + + // eslint-disable-next-line jsdoc/require-description + /** + * @returns {Object} an object to display by `console.log()`. + */ + [util__default["default"].inspect.custom]() { + const { + definition: _ignore1, // eslint-disable-line no-unused-vars + original: _ignore2, // eslint-disable-line no-unused-vars + ...obj + } = this; + + return obj; + } +} + +/** + * @fileoverview `OverrideTester` class. + * + * `OverrideTester` class handles `files` property and `excludedFiles` property + * of `overrides` config. + * + * It provides one method. + * + * - `test(filePath)` + * Test if a file path matches the pair of `files` property and + * `excludedFiles` property. The `filePath` argument must be an absolute + * path. + * + * `ConfigArrayFactory` creates `OverrideTester` objects when it processes + * `overrides` properties. + * + * @author Toru Nagashima + */ + +const { Minimatch } = minimatch__default["default"]; + +const minimatchOpts = { dot: true, matchBase: true }; + +/** + * @typedef {Object} Pattern + * @property {InstanceType[] | null} includes The positive matchers. + * @property {InstanceType[] | null} excludes The negative matchers. + */ + +/** + * Normalize a given pattern to an array. + * @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns. + * @returns {string[]|null} Normalized patterns. + * @private + */ +function normalizePatterns(patterns) { + if (Array.isArray(patterns)) { + return patterns.filter(Boolean); + } + if (typeof patterns === "string" && patterns) { + return [patterns]; + } + return []; +} + +/** + * Create the matchers of given patterns. + * @param {string[]} patterns The patterns. + * @returns {InstanceType[] | null} The matchers. + */ +function toMatcher(patterns) { + if (patterns.length === 0) { + return null; + } + return patterns.map(pattern => { + if (/^\.[/\\]/u.test(pattern)) { + return new Minimatch( + pattern.slice(2), + + // `./*.js` should not match with `subdir/foo.js` + { ...minimatchOpts, matchBase: false } + ); + } + return new Minimatch(pattern, minimatchOpts); + }); +} + +/** + * Convert a given matcher to string. + * @param {Pattern} matchers The matchers. + * @returns {string} The string expression of the matcher. + */ +function patternToJson({ includes, excludes }) { + return { + includes: includes && includes.map(m => m.pattern), + excludes: excludes && excludes.map(m => m.pattern) + }; +} + +/** + * The class to test given paths are matched by the patterns. + */ +class OverrideTester { + + /** + * Create a tester with given criteria. + * If there are no criteria, returns `null`. + * @param {string|string[]} files The glob patterns for included files. + * @param {string|string[]} excludedFiles The glob patterns for excluded files. + * @param {string} basePath The path to the base directory to test paths. + * @returns {OverrideTester|null} The created instance or `null`. + */ + static create(files, excludedFiles, basePath) { + const includePatterns = normalizePatterns(files); + const excludePatterns = normalizePatterns(excludedFiles); + let endsWithWildcard = false; + + if (includePatterns.length === 0) { + return null; + } + + // Rejects absolute paths or relative paths to parents. + for (const pattern of includePatterns) { + if (path__default["default"].isAbsolute(pattern) || pattern.includes("..")) { + throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`); + } + if (pattern.endsWith("*")) { + endsWithWildcard = true; + } + } + for (const pattern of excludePatterns) { + if (path__default["default"].isAbsolute(pattern) || pattern.includes("..")) { + throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`); + } + } + + const includes = toMatcher(includePatterns); + const excludes = toMatcher(excludePatterns); + + return new OverrideTester( + [{ includes, excludes }], + basePath, + endsWithWildcard + ); + } + + /** + * Combine two testers by logical and. + * If either of the testers was `null`, returns the other tester. + * The `basePath` property of the two must be the same value. + * @param {OverrideTester|null} a A tester. + * @param {OverrideTester|null} b Another tester. + * @returns {OverrideTester|null} Combined tester. + */ + static and(a, b) { + if (!b) { + return a && new OverrideTester( + a.patterns, + a.basePath, + a.endsWithWildcard + ); + } + if (!a) { + return new OverrideTester( + b.patterns, + b.basePath, + b.endsWithWildcard + ); + } + + assert__default["default"].strictEqual(a.basePath, b.basePath); + return new OverrideTester( + a.patterns.concat(b.patterns), + a.basePath, + a.endsWithWildcard || b.endsWithWildcard + ); + } + + /** + * Initialize this instance. + * @param {Pattern[]} patterns The matchers. + * @param {string} basePath The base path. + * @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`. + */ + constructor(patterns, basePath, endsWithWildcard = false) { + + /** @type {Pattern[]} */ + this.patterns = patterns; + + /** @type {string} */ + this.basePath = basePath; + + /** @type {boolean} */ + this.endsWithWildcard = endsWithWildcard; + } + + /** + * Test if a given path is matched or not. + * @param {string} filePath The absolute path to the target file. + * @returns {boolean} `true` if the path was matched. + */ + test(filePath) { + if (typeof filePath !== "string" || !path__default["default"].isAbsolute(filePath)) { + throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`); + } + const relativePath = path__default["default"].relative(this.basePath, filePath); + + return this.patterns.every(({ includes, excludes }) => ( + (!includes || includes.some(m => m.match(relativePath))) && + (!excludes || !excludes.some(m => m.match(relativePath))) + )); + } + + // eslint-disable-next-line jsdoc/require-description + /** + * @returns {Object} a JSON compatible object. + */ + toJSON() { + if (this.patterns.length === 1) { + return { + ...patternToJson(this.patterns[0]), + basePath: this.basePath + }; + } + return { + AND: this.patterns.map(patternToJson), + basePath: this.basePath + }; + } + + // eslint-disable-next-line jsdoc/require-description + /** + * @returns {Object} an object to display by `console.log()`. + */ + [util__default["default"].inspect.custom]() { + return this.toJSON(); + } +} + +/** + * @fileoverview `ConfigArray` class. + * @author Toru Nagashima + */ + +/** + * @fileoverview Config file operations. This file must be usable in the browser, + * so no Node-specific code can be here. + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +const RULE_SEVERITY_STRINGS = ["off", "warn", "error"], + RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => { + map[value] = index; + return map; + }, {}), + VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"]; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * Normalizes the severity value of a rule's configuration to a number + * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally + * received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0), + * the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array + * whose first element is one of the above values. Strings are matched case-insensitively. + * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0. + */ +function getRuleSeverity(ruleConfig) { + const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; + + if (severityValue === 0 || severityValue === 1 || severityValue === 2) { + return severityValue; + } + + if (typeof severityValue === "string") { + return RULE_SEVERITY[severityValue.toLowerCase()] || 0; + } + + return 0; +} + +/** + * Converts old-style severity settings (0, 1, 2) into new-style + * severity settings (off, warn, error) for all rules. Assumption is that severity + * values have already been validated as correct. + * @param {Object} config The config object to normalize. + * @returns {void} + */ +function normalizeToStrings(config) { + + if (config.rules) { + Object.keys(config.rules).forEach(ruleId => { + const ruleConfig = config.rules[ruleId]; + + if (typeof ruleConfig === "number") { + config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0]; + } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") { + ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0]; + } + }); + } +} + +/** + * Determines if the severity for the given rule configuration represents an error. + * @param {int|string|Array} ruleConfig The configuration for an individual rule. + * @returns {boolean} True if the rule represents an error, false if not. + */ +function isErrorSeverity(ruleConfig) { + return getRuleSeverity(ruleConfig) === 2; +} + +/** + * Checks whether a given config has valid severity or not. + * @param {number|string|Array} ruleConfig The configuration for an individual rule. + * @returns {boolean} `true` if the configuration has valid severity. + */ +function isValidSeverity(ruleConfig) { + let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig; + + if (typeof severity === "string") { + severity = severity.toLowerCase(); + } + return VALID_SEVERITIES.indexOf(severity) !== -1; +} + +/** + * Checks whether every rule of a given config has valid severity or not. + * @param {Object} config The configuration for rules. + * @returns {boolean} `true` if the configuration has valid severity. + */ +function isEverySeverityValid(config) { + return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId])); +} + +/** + * Normalizes a value for a global in a config + * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in + * a global directive comment + * @returns {("readable"|"writeable"|"off")} The value normalized as a string + * @throws Error if global value is invalid + */ +function normalizeConfigGlobal(configuredValue) { + switch (configuredValue) { + case "off": + return "off"; + + case true: + case "true": + case "writeable": + case "writable": + return "writable"; + + case null: + case false: + case "false": + case "readable": + case "readonly": + return "readonly"; + + default: + throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`); + } +} + +var ConfigOps = { + __proto__: null, + getRuleSeverity: getRuleSeverity, + normalizeToStrings: normalizeToStrings, + isErrorSeverity: isErrorSeverity, + isValidSeverity: isValidSeverity, + isEverySeverityValid: isEverySeverityValid, + normalizeConfigGlobal: normalizeConfigGlobal +}; + +/** + * @fileoverview Provide the function that emits deprecation warnings. + * @author Toru Nagashima + */ + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ + +// Defitions for deprecation warnings. +const deprecationWarningMessages = { + ESLINT_LEGACY_ECMAFEATURES: + "The 'ecmaFeatures' config file property is deprecated and has no effect.", + ESLINT_PERSONAL_CONFIG_LOAD: + "'~/.eslintrc.*' config files have been deprecated. " + + "Please use a config file per project or the '--config' option.", + ESLINT_PERSONAL_CONFIG_SUPPRESS: + "'~/.eslintrc.*' config files have been deprecated. " + + "Please remove it or add 'root:true' to the config files in your " + + "projects in order to avoid loading '~/.eslintrc.*' accidentally." +}; + +const sourceFileErrorCache = new Set(); + +/** + * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted + * for each unique file path, but repeated invocations with the same file path have no effect. + * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active. + * @param {string} source The name of the configuration source to report the warning for. + * @param {string} errorCode The warning message to show. + * @returns {void} + */ +function emitDeprecationWarning(source, errorCode) { + const cacheKey = JSON.stringify({ source, errorCode }); + + if (sourceFileErrorCache.has(cacheKey)) { + return; + } + sourceFileErrorCache.add(cacheKey); + + const rel = path__default["default"].relative(process.cwd(), source); + const message = deprecationWarningMessages[errorCode]; + + process.emitWarning( + `${message} (found in "${rel}")`, + "DeprecationWarning", + errorCode + ); +} + +/** + * @fileoverview The instance of Ajv validator. + * @author Evgeny Poberezkin + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/* + * Copied from ajv/lib/refs/json-schema-draft-04.json + * The MIT License (MIT) + * Copyright (c) 2015-2017 Evgeny Poberezkin + */ +const metaSchema = { + id: "http://json-schema.org/draft-04/schema#", + $schema: "http://json-schema.org/draft-04/schema#", + description: "Core schema meta-schema", + definitions: { + schemaArray: { + type: "array", + minItems: 1, + items: { $ref: "#" } + }, + positiveInteger: { + type: "integer", + minimum: 0 + }, + positiveIntegerDefault0: { + allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }] + }, + simpleTypes: { + enum: ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + stringArray: { + type: "array", + items: { type: "string" }, + minItems: 1, + uniqueItems: true + } + }, + type: "object", + properties: { + id: { + type: "string" + }, + $schema: { + type: "string" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + default: { }, + multipleOf: { + type: "number", + minimum: 0, + exclusiveMinimum: true + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "boolean", + default: false + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "boolean", + default: false + }, + maxLength: { $ref: "#/definitions/positiveInteger" }, + minLength: { $ref: "#/definitions/positiveIntegerDefault0" }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { + anyOf: [ + { type: "boolean" }, + { $ref: "#" } + ], + default: { } + }, + items: { + anyOf: [ + { $ref: "#" }, + { $ref: "#/definitions/schemaArray" } + ], + default: { } + }, + maxItems: { $ref: "#/definitions/positiveInteger" }, + minItems: { $ref: "#/definitions/positiveIntegerDefault0" }, + uniqueItems: { + type: "boolean", + default: false + }, + maxProperties: { $ref: "#/definitions/positiveInteger" }, + minProperties: { $ref: "#/definitions/positiveIntegerDefault0" }, + required: { $ref: "#/definitions/stringArray" }, + additionalProperties: { + anyOf: [ + { type: "boolean" }, + { $ref: "#" } + ], + default: { } + }, + definitions: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + properties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + patternProperties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: { } + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [ + { $ref: "#" }, + { $ref: "#/definitions/stringArray" } + ] + } + }, + enum: { + type: "array", + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { $ref: "#/definitions/simpleTypes" }, + { + type: "array", + items: { $ref: "#/definitions/simpleTypes" }, + minItems: 1, + uniqueItems: true + } + ] + }, + format: { type: "string" }, + allOf: { $ref: "#/definitions/schemaArray" }, + anyOf: { $ref: "#/definitions/schemaArray" }, + oneOf: { $ref: "#/definitions/schemaArray" }, + not: { $ref: "#" } + }, + dependencies: { + exclusiveMaximum: ["maximum"], + exclusiveMinimum: ["minimum"] + }, + default: { } +}; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +var ajvOrig = (additionalOptions = {}) => { + const ajv = new Ajv__default["default"]({ + meta: false, + useDefaults: true, + validateSchema: false, + missingRefs: "ignore", + verbose: true, + schemaId: "auto", + ...additionalOptions + }); + + ajv.addMetaSchema(metaSchema); + // eslint-disable-next-line no-underscore-dangle + ajv._opts.defaultMeta = metaSchema.id; + + return ajv; +}; + +/** + * @fileoverview Defines a schema for configs. + * @author Sylvan Mably + */ + +const baseConfigProperties = { + $schema: { type: "string" }, + env: { type: "object" }, + extends: { $ref: "#/definitions/stringOrStrings" }, + globals: { type: "object" }, + overrides: { + type: "array", + items: { $ref: "#/definitions/overrideConfig" }, + additionalItems: false + }, + parser: { type: ["string", "null"] }, + parserOptions: { type: "object" }, + plugins: { type: "array" }, + processor: { type: "string" }, + rules: { type: "object" }, + settings: { type: "object" }, + noInlineConfig: { type: "boolean" }, + reportUnusedDisableDirectives: { type: "boolean" }, + + ecmaFeatures: { type: "object" } // deprecated; logs a warning when used +}; + +const configSchema = { + definitions: { + stringOrStrings: { + oneOf: [ + { type: "string" }, + { + type: "array", + items: { type: "string" }, + additionalItems: false + } + ] + }, + stringOrStringsRequired: { + oneOf: [ + { type: "string" }, + { + type: "array", + items: { type: "string" }, + additionalItems: false, + minItems: 1 + } + ] + }, + + // Config at top-level. + objectConfig: { + type: "object", + properties: { + root: { type: "boolean" }, + ignorePatterns: { $ref: "#/definitions/stringOrStrings" }, + ...baseConfigProperties + }, + additionalProperties: false + }, + + // Config in `overrides`. + overrideConfig: { + type: "object", + properties: { + excludedFiles: { $ref: "#/definitions/stringOrStrings" }, + files: { $ref: "#/definitions/stringOrStringsRequired" }, + ...baseConfigProperties + }, + required: ["files"], + additionalProperties: false + } + }, + + $ref: "#/definitions/objectConfig" +}; + +/** + * @fileoverview Defines environment settings and globals. + * @author Elan Shanker + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Get the object that has difference. + * @param {Record} current The newer object. + * @param {Record} prev The older object. + * @returns {Record} The difference object. + */ +function getDiff(current, prev) { + const retv = {}; + + for (const [key, value] of Object.entries(current)) { + if (!Object.hasOwnProperty.call(prev, key)) { + retv[key] = value; + } + } + + return retv; +} + +const newGlobals2015 = getDiff(globals__default["default"].es2015, globals__default["default"].es5); // 19 variables such as Promise, Map, ... +const newGlobals2017 = { + Atomics: false, + SharedArrayBuffer: false +}; +const newGlobals2020 = { + BigInt: false, + BigInt64Array: false, + BigUint64Array: false, + globalThis: false +}; + +const newGlobals2021 = { + AggregateError: false, + FinalizationRegistry: false, + WeakRef: false +}; + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** @type {Map} */ +var environments = new Map(Object.entries({ + + // Language + builtin: { + globals: globals__default["default"].es5 + }, + es6: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 6 + } + }, + es2015: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 6 + } + }, + es2016: { + globals: newGlobals2015, + parserOptions: { + ecmaVersion: 7 + } + }, + es2017: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 8 + } + }, + es2018: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 9 + } + }, + es2019: { + globals: { ...newGlobals2015, ...newGlobals2017 }, + parserOptions: { + ecmaVersion: 10 + } + }, + es2020: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 }, + parserOptions: { + ecmaVersion: 11 + } + }, + es2021: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 12 + } + }, + es2022: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 13 + } + }, + es2023: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 14 + } + }, + es2024: { + globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 }, + parserOptions: { + ecmaVersion: 15 + } + }, + + // Platforms + browser: { + globals: globals__default["default"].browser + }, + node: { + globals: globals__default["default"].node, + parserOptions: { + ecmaFeatures: { + globalReturn: true + } + } + }, + "shared-node-browser": { + globals: globals__default["default"]["shared-node-browser"] + }, + worker: { + globals: globals__default["default"].worker + }, + serviceworker: { + globals: globals__default["default"].serviceworker + }, + + // Frameworks + commonjs: { + globals: globals__default["default"].commonjs, + parserOptions: { + ecmaFeatures: { + globalReturn: true + } + } + }, + amd: { + globals: globals__default["default"].amd + }, + mocha: { + globals: globals__default["default"].mocha + }, + jasmine: { + globals: globals__default["default"].jasmine + }, + jest: { + globals: globals__default["default"].jest + }, + phantomjs: { + globals: globals__default["default"].phantomjs + }, + jquery: { + globals: globals__default["default"].jquery + }, + qunit: { + globals: globals__default["default"].qunit + }, + prototypejs: { + globals: globals__default["default"].prototypejs + }, + shelljs: { + globals: globals__default["default"].shelljs + }, + meteor: { + globals: globals__default["default"].meteor + }, + mongo: { + globals: globals__default["default"].mongo + }, + protractor: { + globals: globals__default["default"].protractor + }, + applescript: { + globals: globals__default["default"].applescript + }, + nashorn: { + globals: globals__default["default"].nashorn + }, + atomtest: { + globals: globals__default["default"].atomtest + }, + embertest: { + globals: globals__default["default"].embertest + }, + webextensions: { + globals: globals__default["default"].webextensions + }, + greasemonkey: { + globals: globals__default["default"].greasemonkey + } +})); + +/** + * @fileoverview Validates configs. + * @author Brandon Mills + */ + +const ajv = ajvOrig(); + +const ruleValidators = new WeakMap(); +const noop = Function.prototype; + +//------------------------------------------------------------------------------ +// Private +//------------------------------------------------------------------------------ +let validateSchema; +const severityMap = { + error: 2, + warn: 1, + off: 0 +}; + +const validated = new WeakSet(); + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +class ConfigValidator { + constructor({ builtInRules = new Map() } = {}) { + this.builtInRules = builtInRules; + } + + /** + * Gets a complete options schema for a rule. + * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object + * @returns {Object} JSON Schema for the rule's options. + */ + getRuleOptionsSchema(rule) { + if (!rule) { + return null; + } + + const schema = rule.schema || rule.meta && rule.meta.schema; + + // Given a tuple of schemas, insert warning level at the beginning + if (Array.isArray(schema)) { + if (schema.length) { + return { + type: "array", + items: schema, + minItems: 0, + maxItems: schema.length + }; + } + return { + type: "array", + minItems: 0, + maxItems: 0 + }; + + } + + // Given a full schema, leave it alone + return schema || null; + } + + /** + * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid. + * @param {options} options The given options for the rule. + * @returns {number|string} The rule's severity value + */ + validateRuleSeverity(options) { + const severity = Array.isArray(options) ? options[0] : options; + const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity; + + if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) { + return normSeverity; + } + + throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util__default["default"].inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`); + + } + + /** + * Validates the non-severity options passed to a rule, based on its schema. + * @param {{create: Function}} rule The rule to validate + * @param {Array} localOptions The options for the rule, excluding severity + * @returns {void} + */ + validateRuleSchema(rule, localOptions) { + if (!ruleValidators.has(rule)) { + const schema = this.getRuleOptionsSchema(rule); + + if (schema) { + ruleValidators.set(rule, ajv.compile(schema)); + } + } + + const validateRule = ruleValidators.get(rule); + + if (validateRule) { + validateRule(localOptions); + if (validateRule.errors) { + throw new Error(validateRule.errors.map( + error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n` + ).join("")); + } + } + } + + /** + * Validates a rule's options against its schema. + * @param {{create: Function}|null} rule The rule that the config is being validated for + * @param {string} ruleId The rule's unique name. + * @param {Array|number} options The given options for the rule. + * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined, + * no source is prepended to the message. + * @returns {void} + */ + validateRuleOptions(rule, ruleId, options, source = null) { + try { + const severity = this.validateRuleSeverity(options); + + if (severity !== 0) { + this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []); + } + } catch (err) { + const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`; + + if (typeof source === "string") { + throw new Error(`${source}:\n\t${enhancedMessage}`); + } else { + throw new Error(enhancedMessage); + } + } + } + + /** + * Validates an environment object + * @param {Object} environment The environment config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments. + * @returns {void} + */ + validateEnvironment( + environment, + source, + getAdditionalEnv = noop + ) { + + // not having an environment is ok + if (!environment) { + return; + } + + Object.keys(environment).forEach(id => { + const env = getAdditionalEnv(id) || environments.get(id) || null; + + if (!env) { + const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`; + + throw new Error(message); + } + }); + } + + /** + * Validates a rules config object + * @param {Object} rulesConfig The rules config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules + * @returns {void} + */ + validateRules( + rulesConfig, + source, + getAdditionalRule = noop + ) { + if (!rulesConfig) { + return; + } + + Object.keys(rulesConfig).forEach(id => { + const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null; + + this.validateRuleOptions(rule, id, rulesConfig[id], source); + }); + } + + /** + * Validates a `globals` section of a config file + * @param {Object} globalsConfig The `globals` section + * @param {string|null} source The name of the configuration source to report in the event of an error. + * @returns {void} + */ + validateGlobals(globalsConfig, source = null) { + if (!globalsConfig) { + return; + } + + Object.entries(globalsConfig) + .forEach(([configuredGlobal, configuredValue]) => { + try { + normalizeConfigGlobal(configuredValue); + } catch (err) { + throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`); + } + }); + } + + /** + * Validate `processor` configuration. + * @param {string|undefined} processorName The processor name. + * @param {string} source The name of config file. + * @param {function(id:string): Processor} getProcessor The getter of defined processors. + * @returns {void} + */ + validateProcessor(processorName, source, getProcessor) { + if (processorName && !getProcessor(processorName)) { + throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`); + } + } + + /** + * Formats an array of schema validation errors. + * @param {Array} errors An array of error messages to format. + * @returns {string} Formatted error message + */ + formatErrors(errors) { + return errors.map(error => { + if (error.keyword === "additionalProperties") { + const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty; + + return `Unexpected top-level property "${formattedPropertyPath}"`; + } + if (error.keyword === "type") { + const formattedField = error.dataPath.slice(1); + const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema; + const formattedValue = JSON.stringify(error.data); + + return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`; + } + + const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath; + + return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`; + }).map(message => `\t- ${message}.\n`).join(""); + } + + /** + * Validates the top level properties of the config object. + * @param {Object} config The config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @returns {void} + */ + validateConfigSchema(config, source = null) { + validateSchema = validateSchema || ajv.compile(configSchema); + + if (!validateSchema(config)) { + throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`); + } + + if (Object.hasOwnProperty.call(config, "ecmaFeatures")) { + emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES"); + } + } + + /** + * Validates an entire config object. + * @param {Object} config The config object to validate. + * @param {string} source The name of the configuration source to report in any errors. + * @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules. + * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs. + * @returns {void} + */ + validate(config, source, getAdditionalRule, getAdditionalEnv) { + this.validateConfigSchema(config, source); + this.validateRules(config.rules, source, getAdditionalRule); + this.validateEnvironment(config.env, source, getAdditionalEnv); + this.validateGlobals(config.globals, source); + + for (const override of config.overrides || []) { + this.validateRules(override.rules, source, getAdditionalRule); + this.validateEnvironment(override.env, source, getAdditionalEnv); + this.validateGlobals(config.globals, source); + } + } + + /** + * Validate config array object. + * @param {ConfigArray} configArray The config array to validate. + * @returns {void} + */ + validateConfigArray(configArray) { + const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments); + const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors); + const getPluginRule = Map.prototype.get.bind(configArray.pluginRules); + + // Validate. + for (const element of configArray) { + if (validated.has(element)) { + continue; + } + validated.add(element); + + this.validateEnvironment(element.env, element.name, getPluginEnv); + this.validateGlobals(element.globals, element.name); + this.validateProcessor(element.processor, element.name, getPluginProcessor); + this.validateRules(element.rules, element.name, getPluginRule); + } + } + +} + +/** + * @fileoverview Common helpers for naming of plugins, formatters and configs + */ + +const NAMESPACE_REGEX = /^@.*\//iu; + +/** + * Brings package name to correct format based on prefix + * @param {string} name The name of the package. + * @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter" + * @returns {string} Normalized name of the package + * @private + */ +function normalizePackageName(name, prefix) { + let normalizedName = name; + + /** + * On Windows, name can come in with Windows slashes instead of Unix slashes. + * Normalize to Unix first to avoid errors later on. + * https://github.com/eslint/eslint/issues/5644 + */ + if (normalizedName.includes("\\")) { + normalizedName = normalizedName.replace(/\\/gu, "/"); + } + + if (normalizedName.charAt(0) === "@") { + + /** + * it's a scoped package + * package name is the prefix, or just a username + */ + const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"), + scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u"); + + if (scopedPackageShortcutRegex.test(normalizedName)) { + normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`); + } else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) { + + /** + * for scoped packages, insert the prefix after the first / unless + * the path is already @scope/eslint or @scope/eslint-xxx-yyy + */ + normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`); + } + } else if (!normalizedName.startsWith(`${prefix}-`)) { + normalizedName = `${prefix}-${normalizedName}`; + } + + return normalizedName; +} + +/** + * Removes the prefix from a fullname. + * @param {string} fullname The term which may have the prefix. + * @param {string} prefix The prefix to remove. + * @returns {string} The term without prefix. + */ +function getShorthandName(fullname, prefix) { + if (fullname[0] === "@") { + let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname); + + if (matchResult) { + return matchResult[1]; + } + + matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname); + if (matchResult) { + return `${matchResult[1]}/${matchResult[2]}`; + } + } else if (fullname.startsWith(`${prefix}-`)) { + return fullname.slice(prefix.length + 1); + } + + return fullname; +} + +/** + * Gets the scope (namespace) of a term. + * @param {string} term The term which may have the namespace. + * @returns {string} The namespace of the term if it has one. + */ +function getNamespaceFromTerm(term) { + const match = term.match(NAMESPACE_REGEX); + + return match ? match[0] : ""; +} + +var naming = { + __proto__: null, + normalizePackageName: normalizePackageName, + getShorthandName: getShorthandName, + getNamespaceFromTerm: getNamespaceFromTerm +}; + +/** + * Utility for resolving a module relative to another module + * @author Teddy Katz + */ + +/* + * `Module.createRequire` is added in v12.2.0. It supports URL as well. + * We only support the case where the argument is a filepath, not a URL. + */ +const createRequire = Module__default["default"].createRequire; + +/** + * Resolves a Node module relative to another module + * @param {string} moduleName The name of a Node module, or a path to a Node module. + * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be + * a file rather than a directory, but the file need not actually exist. + * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath` + */ +function resolve(moduleName, relativeToPath) { + try { + return createRequire(relativeToPath).resolve(moduleName); + } catch (error) { + + // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future. + if ( + typeof error === "object" && + error !== null && + error.code === "MODULE_NOT_FOUND" && + !error.requireStack && + error.message.includes(moduleName) + ) { + error.message += `\nRequire stack:\n- ${relativeToPath}`; + } + throw error; + } +} + +var ModuleResolver = { + __proto__: null, + resolve: resolve +}; + +/** + * @fileoverview The factory of `ConfigArray` objects. + * + * This class provides methods to create `ConfigArray` instance. + * + * - `create(configData, options)` + * Create a `ConfigArray` instance from a config data. This is to handle CLI + * options except `--config`. + * - `loadFile(filePath, options)` + * Create a `ConfigArray` instance from a config file. This is to handle + * `--config` option. If the file was not found, throws the following error: + * - If the filename was `*.js`, a `MODULE_NOT_FOUND` error. + * - If the filename was `package.json`, an IO error or an + * `ESLINT_CONFIG_FIELD_NOT_FOUND` error. + * - Otherwise, an IO error such as `ENOENT`. + * - `loadInDirectory(directoryPath, options)` + * Create a `ConfigArray` instance from a config file which is on a given + * directory. This tries to load `.eslintrc.*` or `package.json`. If not + * found, returns an empty `ConfigArray`. + * - `loadESLintIgnore(filePath)` + * Create a `ConfigArray` instance from a config file that is `.eslintignore` + * format. This is to handle `--ignore-path` option. + * - `loadDefaultESLintIgnore()` + * Create a `ConfigArray` instance from `.eslintignore` or `package.json` in + * the current working directory. + * + * `ConfigArrayFactory` class has the responsibility that loads configuration + * files, including loading `extends`, `parser`, and `plugins`. The created + * `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`. + * + * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class + * handles cascading and hierarchy. + * + * @author Toru Nagashima + */ + +const require$1 = Module.createRequire(require('url').pathToFileURL(__filename).toString()); + +const debug$2 = debugOrig__default["default"]("eslintrc:config-array-factory"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const configFilenames = [ + ".eslintrc.js", + ".eslintrc.cjs", + ".eslintrc.yaml", + ".eslintrc.yml", + ".eslintrc.json", + ".eslintrc", + "package.json" +]; + +// Define types for VSCode IntelliSense. +/** @typedef {import("./shared/types").ConfigData} ConfigData */ +/** @typedef {import("./shared/types").OverrideConfigData} OverrideConfigData */ +/** @typedef {import("./shared/types").Parser} Parser */ +/** @typedef {import("./shared/types").Plugin} Plugin */ +/** @typedef {import("./shared/types").Rule} Rule */ +/** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */ +/** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */ +/** @typedef {ConfigArray[0]} ConfigArrayElement */ + +/** + * @typedef {Object} ConfigArrayFactoryOptions + * @property {Map} [additionalPluginPool] The map for additional plugins. + * @property {string} [cwd] The path to the current working directory. + * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`. + * @property {Map} builtInRules The rules that are built in to ESLint. + * @property {Object} [resolver=ModuleResolver] The module resolver object. + * @property {string} eslintAllPath The path to the definitions for eslint:all. + * @property {Function} getEslintAllConfig Returns the config data for eslint:all. + * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended. + * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended. + */ + +/** + * @typedef {Object} ConfigArrayFactoryInternalSlots + * @property {Map} additionalPluginPool The map for additional plugins. + * @property {string} cwd The path to the current working directory. + * @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from. + * @property {Map} builtInRules The rules that are built in to ESLint. + * @property {Object} [resolver=ModuleResolver] The module resolver object. + * @property {string} eslintAllPath The path to the definitions for eslint:all. + * @property {Function} getEslintAllConfig Returns the config data for eslint:all. + * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended. + * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended. + */ + +/** + * @typedef {Object} ConfigArrayFactoryLoadingContext + * @property {string} filePath The path to the current configuration. + * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @property {string} name The name of the current configuration. + * @property {string} pluginBasePath The base path to resolve plugins. + * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors. + */ + +/** + * @typedef {Object} ConfigArrayFactoryLoadingContext + * @property {string} filePath The path to the current configuration. + * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @property {string} name The name of the current configuration. + * @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors. + */ + +/** @type {WeakMap} */ +const internalSlotsMap$1 = new WeakMap(); + +/** @type {WeakMap} */ +const normalizedPlugins = new WeakMap(); + +/** + * Check if a given string is a file path. + * @param {string} nameOrPath A module name or file path. + * @returns {boolean} `true` if the `nameOrPath` is a file path. + */ +function isFilePath(nameOrPath) { + return ( + /^\.{1,2}[/\\]/u.test(nameOrPath) || + path__default["default"].isAbsolute(nameOrPath) + ); +} + +/** + * Convenience wrapper for synchronously reading file contents. + * @param {string} filePath The filename to read. + * @returns {string} The file contents, with the BOM removed. + * @private + */ +function readFile(filePath) { + return fs__default["default"].readFileSync(filePath, "utf8").replace(/^\ufeff/u, ""); +} + +/** + * Loads a YAML configuration from a file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadYAMLConfigFile(filePath) { + debug$2(`Loading YAML config file: ${filePath}`); + + // lazy load YAML to improve performance when not used + const yaml = require$1("js-yaml"); + + try { + + // empty YAML file can be null, so always use + return yaml.load(readFile(filePath)) || {}; + } catch (e) { + debug$2(`Error reading YAML file: ${filePath}`); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Loads a JSON configuration from a file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadJSONConfigFile(filePath) { + debug$2(`Loading JSON config file: ${filePath}`); + + try { + return JSON.parse(stripComments__default["default"](readFile(filePath))); + } catch (e) { + debug$2(`Error reading JSON file: ${filePath}`); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + e.messageTemplate = "failed-to-read-json"; + e.messageData = { + path: filePath, + message: e.message + }; + throw e; + } +} + +/** + * Loads a legacy (.eslintrc) configuration from a file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadLegacyConfigFile(filePath) { + debug$2(`Loading legacy config file: ${filePath}`); + + // lazy load YAML to improve performance when not used + const yaml = require$1("js-yaml"); + + try { + return yaml.load(stripComments__default["default"](readFile(filePath))) || /* istanbul ignore next */ {}; + } catch (e) { + debug$2("Error reading YAML file: %s\n%o", filePath, e); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Loads a JavaScript configuration from a file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadJSConfigFile(filePath) { + debug$2(`Loading JS config file: ${filePath}`); + try { + return importFresh__default["default"](filePath); + } catch (e) { + debug$2(`Error reading JavaScript file: ${filePath}`); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Loads a configuration from a package.json file. + * @param {string} filePath The filename to load. + * @returns {ConfigData} The configuration object from the file. + * @throws {Error} If the file cannot be read. + * @private + */ +function loadPackageJSONConfigFile(filePath) { + debug$2(`Loading package.json config file: ${filePath}`); + try { + const packageData = loadJSONConfigFile(filePath); + + if (!Object.hasOwnProperty.call(packageData, "eslintConfig")) { + throw Object.assign( + new Error("package.json file doesn't have 'eslintConfig' field."), + { code: "ESLINT_CONFIG_FIELD_NOT_FOUND" } + ); + } + + return packageData.eslintConfig; + } catch (e) { + debug$2(`Error reading package.json file: ${filePath}`); + e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Loads a `.eslintignore` from a file. + * @param {string} filePath The filename to load. + * @returns {string[]} The ignore patterns from the file. + * @private + */ +function loadESLintIgnoreFile(filePath) { + debug$2(`Loading .eslintignore file: ${filePath}`); + + try { + return readFile(filePath) + .split(/\r?\n/gu) + .filter(line => line.trim() !== "" && !line.startsWith("#")); + } catch (e) { + debug$2(`Error reading .eslintignore file: ${filePath}`); + e.message = `Cannot read .eslintignore file: ${filePath}\nError: ${e.message}`; + throw e; + } +} + +/** + * Creates an error to notify about a missing config to extend from. + * @param {string} configName The name of the missing config. + * @param {string} importerName The name of the config that imported the missing config + * @param {string} messageTemplate The text template to source error strings from. + * @returns {Error} The error object to throw + * @private + */ +function configInvalidError(configName, importerName, messageTemplate) { + return Object.assign( + new Error(`Failed to load config "${configName}" to extend from.`), + { + messageTemplate, + messageData: { configName, importerName } + } + ); +} + +/** + * Loads a configuration file regardless of the source. Inspects the file path + * to determine the correctly way to load the config file. + * @param {string} filePath The path to the configuration. + * @returns {ConfigData|null} The configuration information. + * @private + */ +function loadConfigFile(filePath) { + switch (path__default["default"].extname(filePath)) { + case ".js": + case ".cjs": + return loadJSConfigFile(filePath); + + case ".json": + if (path__default["default"].basename(filePath) === "package.json") { + return loadPackageJSONConfigFile(filePath); + } + return loadJSONConfigFile(filePath); + + case ".yaml": + case ".yml": + return loadYAMLConfigFile(filePath); + + default: + return loadLegacyConfigFile(filePath); + } +} + +/** + * Write debug log. + * @param {string} request The requested module name. + * @param {string} relativeTo The file path to resolve the request relative to. + * @param {string} filePath The resolved file path. + * @returns {void} + */ +function writeDebugLogForLoading(request, relativeTo, filePath) { + /* istanbul ignore next */ + if (debug$2.enabled) { + let nameAndVersion = null; + + try { + const packageJsonPath = resolve( + `${request}/package.json`, + relativeTo + ); + const { version = "unknown" } = require$1(packageJsonPath); + + nameAndVersion = `${request}@${version}`; + } catch (error) { + debug$2("package.json was not found:", error.message); + nameAndVersion = request; + } + + debug$2("Loaded: %s (%s)", nameAndVersion, filePath); + } +} + +/** + * Create a new context with default values. + * @param {ConfigArrayFactoryInternalSlots} slots The internal slots. + * @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`. + * @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`. + * @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string. + * @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`. + * @returns {ConfigArrayFactoryLoadingContext} The created context. + */ +function createContext( + { cwd, resolvePluginsRelativeTo }, + providedType, + providedName, + providedFilePath, + providedMatchBasePath +) { + const filePath = providedFilePath + ? path__default["default"].resolve(cwd, providedFilePath) + : ""; + const matchBasePath = + (providedMatchBasePath && path__default["default"].resolve(cwd, providedMatchBasePath)) || + (filePath && path__default["default"].dirname(filePath)) || + cwd; + const name = + providedName || + (filePath && path__default["default"].relative(cwd, filePath)) || + ""; + const pluginBasePath = + resolvePluginsRelativeTo || + (filePath && path__default["default"].dirname(filePath)) || + cwd; + const type = providedType || "config"; + + return { filePath, matchBasePath, name, pluginBasePath, type }; +} + +/** + * Normalize a given plugin. + * - Ensure the object to have four properties: configs, environments, processors, and rules. + * - Ensure the object to not have other properties. + * @param {Plugin} plugin The plugin to normalize. + * @returns {Plugin} The normalized plugin. + */ +function normalizePlugin(plugin) { + + // first check the cache + let normalizedPlugin = normalizedPlugins.get(plugin); + + if (normalizedPlugin) { + return normalizedPlugin; + } + + normalizedPlugin = { + configs: plugin.configs || {}, + environments: plugin.environments || {}, + processors: plugin.processors || {}, + rules: plugin.rules || {} + }; + + // save the reference for later + normalizedPlugins.set(plugin, normalizedPlugin); + + return normalizedPlugin; +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +/** + * The factory of `ConfigArray` objects. + */ +class ConfigArrayFactory { + + /** + * Initialize this instance. + * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins. + */ + constructor({ + additionalPluginPool = new Map(), + cwd = process.cwd(), + resolvePluginsRelativeTo, + builtInRules, + resolver = ModuleResolver, + eslintAllPath, + getEslintAllConfig, + eslintRecommendedPath, + getEslintRecommendedConfig + } = {}) { + internalSlotsMap$1.set(this, { + additionalPluginPool, + cwd, + resolvePluginsRelativeTo: + resolvePluginsRelativeTo && + path__default["default"].resolve(cwd, resolvePluginsRelativeTo), + builtInRules, + resolver, + eslintAllPath, + getEslintAllConfig, + eslintRecommendedPath, + getEslintRecommendedConfig + }); + } + + /** + * Create `ConfigArray` instance from a config data. + * @param {ConfigData|null} configData The config data to create. + * @param {Object} [options] The options. + * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @param {string} [options.filePath] The path to this config data. + * @param {string} [options.name] The config name. + * @returns {ConfigArray} Loaded config. + */ + create(configData, { basePath, filePath, name } = {}) { + if (!configData) { + return new ConfigArray(); + } + + const slots = internalSlotsMap$1.get(this); + const ctx = createContext(slots, "config", name, filePath, basePath); + const elements = this._normalizeConfigData(configData, ctx); + + return new ConfigArray(...elements); + } + + /** + * Load a config file. + * @param {string} filePath The path to a config file. + * @param {Object} [options] The options. + * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @param {string} [options.name] The config name. + * @returns {ConfigArray} Loaded config. + */ + loadFile(filePath, { basePath, name } = {}) { + const slots = internalSlotsMap$1.get(this); + const ctx = createContext(slots, "config", name, filePath, basePath); + + return new ConfigArray(...this._loadConfigData(ctx)); + } + + /** + * Load the config file on a given directory if exists. + * @param {string} directoryPath The path to a directory. + * @param {Object} [options] The options. + * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`. + * @param {string} [options.name] The config name. + * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist. + */ + loadInDirectory(directoryPath, { basePath, name } = {}) { + const slots = internalSlotsMap$1.get(this); + + for (const filename of configFilenames) { + const ctx = createContext( + slots, + "config", + name, + path__default["default"].join(directoryPath, filename), + basePath + ); + + if (fs__default["default"].existsSync(ctx.filePath) && fs__default["default"].statSync(ctx.filePath).isFile()) { + let configData; + + try { + configData = loadConfigFile(ctx.filePath); + } catch (error) { + if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") { + throw error; + } + } + + if (configData) { + debug$2(`Config file found: ${ctx.filePath}`); + return new ConfigArray( + ...this._normalizeConfigData(configData, ctx) + ); + } + } + } + + debug$2(`Config file not found on ${directoryPath}`); + return new ConfigArray(); + } + + /** + * Check if a config file on a given directory exists or not. + * @param {string} directoryPath The path to a directory. + * @returns {string | null} The path to the found config file. If not found then null. + */ + static getPathToConfigFileInDirectory(directoryPath) { + for (const filename of configFilenames) { + const filePath = path__default["default"].join(directoryPath, filename); + + if (fs__default["default"].existsSync(filePath)) { + if (filename === "package.json") { + try { + loadPackageJSONConfigFile(filePath); + return filePath; + } catch { /* ignore */ } + } else { + return filePath; + } + } + } + return null; + } + + /** + * Load `.eslintignore` file. + * @param {string} filePath The path to a `.eslintignore` file to load. + * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist. + */ + loadESLintIgnore(filePath) { + const slots = internalSlotsMap$1.get(this); + const ctx = createContext( + slots, + "ignore", + void 0, + filePath, + slots.cwd + ); + const ignorePatterns = loadESLintIgnoreFile(ctx.filePath); + + return new ConfigArray( + ...this._normalizeESLintIgnoreData(ignorePatterns, ctx) + ); + } + + /** + * Load `.eslintignore` file in the current working directory. + * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist. + */ + loadDefaultESLintIgnore() { + const slots = internalSlotsMap$1.get(this); + const eslintIgnorePath = path__default["default"].resolve(slots.cwd, ".eslintignore"); + const packageJsonPath = path__default["default"].resolve(slots.cwd, "package.json"); + + if (fs__default["default"].existsSync(eslintIgnorePath)) { + return this.loadESLintIgnore(eslintIgnorePath); + } + if (fs__default["default"].existsSync(packageJsonPath)) { + const data = loadJSONConfigFile(packageJsonPath); + + if (Object.hasOwnProperty.call(data, "eslintIgnore")) { + if (!Array.isArray(data.eslintIgnore)) { + throw new Error("Package.json eslintIgnore property requires an array of paths"); + } + const ctx = createContext( + slots, + "ignore", + "eslintIgnore in package.json", + packageJsonPath, + slots.cwd + ); + + return new ConfigArray( + ...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx) + ); + } + } + + return new ConfigArray(); + } + + /** + * Load a given config file. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} Loaded config. + * @private + */ + _loadConfigData(ctx) { + return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx); + } + + /** + * Normalize a given `.eslintignore` data to config array elements. + * @param {string[]} ignorePatterns The patterns to ignore files. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + *_normalizeESLintIgnoreData(ignorePatterns, ctx) { + const elements = this._normalizeObjectConfigData( + { ignorePatterns }, + ctx + ); + + // Set `ignorePattern.loose` flag for backward compatibility. + for (const element of elements) { + if (element.ignorePattern) { + element.ignorePattern.loose = true; + } + yield element; + } + } + + /** + * Normalize a given config to an array. + * @param {ConfigData} configData The config data to normalize. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + _normalizeConfigData(configData, ctx) { + const validator = new ConfigValidator(); + + validator.validateConfigSchema(configData, ctx.name || ctx.filePath); + return this._normalizeObjectConfigData(configData, ctx); + } + + /** + * Normalize a given config to an array. + * @param {ConfigData|OverrideConfigData} configData The config data to normalize. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + *_normalizeObjectConfigData(configData, ctx) { + const { files, excludedFiles, ...configBody } = configData; + const criteria = OverrideTester.create( + files, + excludedFiles, + ctx.matchBasePath + ); + const elements = this._normalizeObjectConfigDataBody(configBody, ctx); + + // Apply the criteria to every element. + for (const element of elements) { + + /* + * Merge the criteria. + * This is for the `overrides` entries that came from the + * configurations of `overrides[].extends`. + */ + element.criteria = OverrideTester.and(criteria, element.criteria); + + /* + * Remove `root` property to ignore `root` settings which came from + * `extends` in `overrides`. + */ + if (element.criteria) { + element.root = void 0; + } + + yield element; + } + } + + /** + * Normalize a given config to an array. + * @param {ConfigData} configData The config data to normalize. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + *_normalizeObjectConfigDataBody( + { + env, + extends: extend, + globals, + ignorePatterns, + noInlineConfig, + parser: parserName, + parserOptions, + plugins: pluginList, + processor, + reportUnusedDisableDirectives, + root, + rules, + settings, + overrides: overrideList = [] + }, + ctx + ) { + const extendList = Array.isArray(extend) ? extend : [extend]; + const ignorePattern = ignorePatterns && new IgnorePattern( + Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns], + ctx.matchBasePath + ); + + // Flatten `extends`. + for (const extendName of extendList.filter(Boolean)) { + yield* this._loadExtends(extendName, ctx); + } + + // Load parser & plugins. + const parser = parserName && this._loadParser(parserName, ctx); + const plugins = pluginList && this._loadPlugins(pluginList, ctx); + + // Yield pseudo config data for file extension processors. + if (plugins) { + yield* this._takeFileExtensionProcessors(plugins, ctx); + } + + // Yield the config data except `extends` and `overrides`. + yield { + + // Debug information. + type: ctx.type, + name: ctx.name, + filePath: ctx.filePath, + + // Config data. + criteria: null, + env, + globals, + ignorePattern, + noInlineConfig, + parser, + parserOptions, + plugins, + processor, + reportUnusedDisableDirectives, + root, + rules, + settings + }; + + // Flatten `overries`. + for (let i = 0; i < overrideList.length; ++i) { + yield* this._normalizeObjectConfigData( + overrideList[i], + { ...ctx, name: `${ctx.name}#overrides[${i}]` } + ); + } + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + _loadExtends(extendName, ctx) { + debug$2("Loading {extends:%j} relative to %s", extendName, ctx.filePath); + try { + if (extendName.startsWith("eslint:")) { + return this._loadExtendedBuiltInConfig(extendName, ctx); + } + if (extendName.startsWith("plugin:")) { + return this._loadExtendedPluginConfig(extendName, ctx); + } + return this._loadExtendedShareableConfig(extendName, ctx); + } catch (error) { + error.message += `\nReferenced from: ${ctx.filePath || ctx.name}`; + throw error; + } + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + _loadExtendedBuiltInConfig(extendName, ctx) { + const { + eslintAllPath, + getEslintAllConfig, + eslintRecommendedPath, + getEslintRecommendedConfig + } = internalSlotsMap$1.get(this); + + if (extendName === "eslint:recommended") { + const name = `${ctx.name} » ${extendName}`; + + if (getEslintRecommendedConfig) { + if (typeof getEslintRecommendedConfig !== "function") { + throw new Error(`getEslintRecommendedConfig must be a function instead of '${getEslintRecommendedConfig}'`); + } + return this._normalizeConfigData(getEslintRecommendedConfig(), { ...ctx, name, filePath: "" }); + } + return this._loadConfigData({ + ...ctx, + name, + filePath: eslintRecommendedPath + }); + } + if (extendName === "eslint:all") { + const name = `${ctx.name} » ${extendName}`; + + if (getEslintAllConfig) { + if (typeof getEslintAllConfig !== "function") { + throw new Error(`getEslintAllConfig must be a function instead of '${getEslintAllConfig}'`); + } + return this._normalizeConfigData(getEslintAllConfig(), { ...ctx, name, filePath: "" }); + } + return this._loadConfigData({ + ...ctx, + name, + filePath: eslintAllPath + }); + } + + throw configInvalidError(extendName, ctx.name, "extend-config-missing"); + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + _loadExtendedPluginConfig(extendName, ctx) { + const slashIndex = extendName.lastIndexOf("/"); + + if (slashIndex === -1) { + throw configInvalidError(extendName, ctx.filePath, "plugin-invalid"); + } + + const pluginName = extendName.slice("plugin:".length, slashIndex); + const configName = extendName.slice(slashIndex + 1); + + if (isFilePath(pluginName)) { + throw new Error("'extends' cannot use a file path for plugins."); + } + + const plugin = this._loadPlugin(pluginName, ctx); + const configData = + plugin.definition && + plugin.definition.configs[configName]; + + if (configData) { + return this._normalizeConfigData(configData, { + ...ctx, + filePath: plugin.filePath || ctx.filePath, + name: `${ctx.name} » plugin:${plugin.id}/${configName}` + }); + } + + throw plugin.error || configInvalidError(extendName, ctx.filePath, "extend-config-missing"); + } + + /** + * Load configs of an element in `extends`. + * @param {string} extendName The name of a base config. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The normalized config. + * @private + */ + _loadExtendedShareableConfig(extendName, ctx) { + const { cwd, resolver } = internalSlotsMap$1.get(this); + const relativeTo = ctx.filePath || path__default["default"].join(cwd, "__placeholder__.js"); + let request; + + if (isFilePath(extendName)) { + request = extendName; + } else if (extendName.startsWith(".")) { + request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior. + } else { + request = normalizePackageName( + extendName, + "eslint-config" + ); + } + + let filePath; + + try { + filePath = resolver.resolve(request, relativeTo); + } catch (error) { + /* istanbul ignore else */ + if (error && error.code === "MODULE_NOT_FOUND") { + throw configInvalidError(extendName, ctx.filePath, "extend-config-missing"); + } + throw error; + } + + writeDebugLogForLoading(request, relativeTo, filePath); + return this._loadConfigData({ + ...ctx, + filePath, + name: `${ctx.name} » ${request}` + }); + } + + /** + * Load given plugins. + * @param {string[]} names The plugin names to load. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {Record} The loaded parser. + * @private + */ + _loadPlugins(names, ctx) { + return names.reduce((map, name) => { + if (isFilePath(name)) { + throw new Error("Plugins array cannot includes file paths."); + } + const plugin = this._loadPlugin(name, ctx); + + map[plugin.id] = plugin; + + return map; + }, {}); + } + + /** + * Load a given parser. + * @param {string} nameOrPath The package name or the path to a parser file. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {DependentParser} The loaded parser. + */ + _loadParser(nameOrPath, ctx) { + debug$2("Loading parser %j from %s", nameOrPath, ctx.filePath); + + const { cwd, resolver } = internalSlotsMap$1.get(this); + const relativeTo = ctx.filePath || path__default["default"].join(cwd, "__placeholder__.js"); + + try { + const filePath = resolver.resolve(nameOrPath, relativeTo); + + writeDebugLogForLoading(nameOrPath, relativeTo, filePath); + + return new ConfigDependency({ + definition: require$1(filePath), + filePath, + id: nameOrPath, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } catch (error) { + + // If the parser name is "espree", load the espree of ESLint. + if (nameOrPath === "espree") { + debug$2("Fallback espree."); + return new ConfigDependency({ + definition: require$1("espree"), + filePath: require$1.resolve("espree"), + id: nameOrPath, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + + debug$2("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name); + error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`; + + return new ConfigDependency({ + error, + id: nameOrPath, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + } + + /** + * Load a given plugin. + * @param {string} name The plugin name to load. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {DependentPlugin} The loaded plugin. + * @private + */ + _loadPlugin(name, ctx) { + debug$2("Loading plugin %j from %s", name, ctx.filePath); + + const { additionalPluginPool, resolver } = internalSlotsMap$1.get(this); + const request = normalizePackageName(name, "eslint-plugin"); + const id = getShorthandName(request, "eslint-plugin"); + const relativeTo = path__default["default"].join(ctx.pluginBasePath, "__placeholder__.js"); + + if (name.match(/\s+/u)) { + const error = Object.assign( + new Error(`Whitespace found in plugin name '${name}'`), + { + messageTemplate: "whitespace-found", + messageData: { pluginName: request } + } + ); + + return new ConfigDependency({ + error, + id, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + + // Check for additional pool. + const plugin = + additionalPluginPool.get(request) || + additionalPluginPool.get(id); + + if (plugin) { + return new ConfigDependency({ + definition: normalizePlugin(plugin), + original: plugin, + filePath: "", // It's unknown where the plugin came from. + id, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + + let filePath; + let error; + + try { + filePath = resolver.resolve(request, relativeTo); + } catch (resolveError) { + error = resolveError; + /* istanbul ignore else */ + if (error && error.code === "MODULE_NOT_FOUND") { + error.messageTemplate = "plugin-missing"; + error.messageData = { + pluginName: request, + resolvePluginsRelativeTo: ctx.pluginBasePath, + importerName: ctx.name + }; + } + } + + if (filePath) { + try { + writeDebugLogForLoading(request, relativeTo, filePath); + + const startTime = Date.now(); + const pluginDefinition = require$1(filePath); + + debug$2(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`); + + return new ConfigDependency({ + definition: normalizePlugin(pluginDefinition), + original: pluginDefinition, + filePath, + id, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } catch (loadError) { + error = loadError; + } + } + + debug$2("Failed to load plugin '%s' declared in '%s'.", name, ctx.name); + error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`; + return new ConfigDependency({ + error, + id, + importerName: ctx.name, + importerPath: ctx.filePath + }); + } + + /** + * Take file expression processors as config array elements. + * @param {Record} plugins The plugin definitions. + * @param {ConfigArrayFactoryLoadingContext} ctx The loading context. + * @returns {IterableIterator} The config array elements of file expression processors. + * @private + */ + *_takeFileExtensionProcessors(plugins, ctx) { + for (const pluginId of Object.keys(plugins)) { + const processors = + plugins[pluginId] && + plugins[pluginId].definition && + plugins[pluginId].definition.processors; + + if (!processors) { + continue; + } + + for (const processorId of Object.keys(processors)) { + if (processorId.startsWith(".")) { + yield* this._normalizeObjectConfigData( + { + files: [`*${processorId}`], + processor: `${pluginId}/${processorId}` + }, + { + ...ctx, + type: "implicit-processor", + name: `${ctx.name}#processors["${pluginId}/${processorId}"]` + } + ); + } + } + } + } +} + +/** + * @fileoverview `CascadingConfigArrayFactory` class. + * + * `CascadingConfigArrayFactory` class has a responsibility: + * + * 1. Handles cascading of config files. + * + * It provides two methods: + * + * - `getConfigArrayForFile(filePath)` + * Get the corresponded configuration of a given file. This method doesn't + * throw even if the given file didn't exist. + * - `clearCache()` + * Clear the internal cache. You have to call this method when + * `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends + * on the additional plugins. (`CLIEngine#addPlugin()` method calls this.) + * + * @author Toru Nagashima + */ + +const debug$1 = debugOrig__default["default"]("eslintrc:cascading-config-array-factory"); + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +// Define types for VSCode IntelliSense. +/** @typedef {import("./shared/types").ConfigData} ConfigData */ +/** @typedef {import("./shared/types").Parser} Parser */ +/** @typedef {import("./shared/types").Plugin} Plugin */ +/** @typedef {import("./shared/types").Rule} Rule */ +/** @typedef {ReturnType} ConfigArray */ + +/** + * @typedef {Object} CascadingConfigArrayFactoryOptions + * @property {Map} [additionalPluginPool] The map for additional plugins. + * @property {ConfigData} [baseConfig] The config by `baseConfig` option. + * @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files. + * @property {string} [cwd] The base directory to start lookup. + * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`. + * @property {string[]} [rulePaths] The value of `--rulesdir` option. + * @property {string} [specificConfigPath] The value of `--config` option. + * @property {boolean} [useEslintrc] if `false` then it doesn't load config files. + * @property {Function} loadRules The function to use to load rules. + * @property {Map} builtInRules The rules that are built in to ESLint. + * @property {Object} [resolver=ModuleResolver] The module resolver object. + * @property {string} eslintAllPath The path to the definitions for eslint:all. + * @property {Function} getEslintAllConfig Returns the config data for eslint:all. + * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended. + * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended. + */ + +/** + * @typedef {Object} CascadingConfigArrayFactoryInternalSlots + * @property {ConfigArray} baseConfigArray The config array of `baseConfig` option. + * @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`. + * @property {ConfigArray} cliConfigArray The config array of CLI options. + * @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`. + * @property {ConfigArrayFactory} configArrayFactory The factory for config arrays. + * @property {Map} configCache The cache from directory paths to config arrays. + * @property {string} cwd The base directory to start lookup. + * @property {WeakMap} finalizeCache The cache from config arrays to finalized config arrays. + * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`. + * @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`. + * @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`. + * @property {boolean} useEslintrc if `false` then it doesn't load config files. + * @property {Function} loadRules The function to use to load rules. + * @property {Map} builtInRules The rules that are built in to ESLint. + * @property {Object} [resolver=ModuleResolver] The module resolver object. + * @property {string} eslintAllPath The path to the definitions for eslint:all. + * @property {Function} getEslintAllConfig Returns the config data for eslint:all. + * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended. + * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended. + */ + +/** @type {WeakMap} */ +const internalSlotsMap = new WeakMap(); + +/** + * Create the config array from `baseConfig` and `rulePaths`. + * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots. + * @returns {ConfigArray} The config array of the base configs. + */ +function createBaseConfigArray({ + configArrayFactory, + baseConfigData, + rulePaths, + cwd, + loadRules +}) { + const baseConfigArray = configArrayFactory.create( + baseConfigData, + { name: "BaseConfig" } + ); + + /* + * Create the config array element for the default ignore patterns. + * This element has `ignorePattern` property that ignores the default + * patterns in the current working directory. + */ + baseConfigArray.unshift(configArrayFactory.create( + { ignorePatterns: IgnorePattern.DefaultPatterns }, + { name: "DefaultIgnorePattern" } + )[0]); + + /* + * Load rules `--rulesdir` option as a pseudo plugin. + * Use a pseudo plugin to define rules of `--rulesdir`, so we can validate + * the rule's options with only information in the config array. + */ + if (rulePaths && rulePaths.length > 0) { + baseConfigArray.push({ + type: "config", + name: "--rulesdir", + filePath: "", + plugins: { + "": new ConfigDependency({ + definition: { + rules: rulePaths.reduce( + (map, rulesPath) => Object.assign( + map, + loadRules(rulesPath, cwd) + ), + {} + ) + }, + filePath: "", + id: "", + importerName: "--rulesdir", + importerPath: "" + }) + } + }); + } + + return baseConfigArray; +} + +/** + * Create the config array from CLI options. + * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots. + * @returns {ConfigArray} The config array of the base configs. + */ +function createCLIConfigArray({ + cliConfigData, + configArrayFactory, + cwd, + ignorePath, + specificConfigPath +}) { + const cliConfigArray = configArrayFactory.create( + cliConfigData, + { name: "CLIOptions" } + ); + + cliConfigArray.unshift( + ...(ignorePath + ? configArrayFactory.loadESLintIgnore(ignorePath) + : configArrayFactory.loadDefaultESLintIgnore()) + ); + + if (specificConfigPath) { + cliConfigArray.unshift( + ...configArrayFactory.loadFile( + specificConfigPath, + { name: "--config", basePath: cwd } + ) + ); + } + + return cliConfigArray; +} + +/** + * The error type when there are files matched by a glob, but all of them have been ignored. + */ +class ConfigurationNotFoundError extends Error { + + // eslint-disable-next-line jsdoc/require-description + /** + * @param {string} directoryPath The directory path. + */ + constructor(directoryPath) { + super(`No ESLint configuration found in ${directoryPath}.`); + this.messageTemplate = "no-config-found"; + this.messageData = { directoryPath }; + } +} + +/** + * This class provides the functionality that enumerates every file which is + * matched by given glob patterns and that configuration. + */ +class CascadingConfigArrayFactory { + + /** + * Initialize this enumerator. + * @param {CascadingConfigArrayFactoryOptions} options The options. + */ + constructor({ + additionalPluginPool = new Map(), + baseConfig: baseConfigData = null, + cliConfig: cliConfigData = null, + cwd = process.cwd(), + ignorePath, + resolvePluginsRelativeTo, + rulePaths = [], + specificConfigPath = null, + useEslintrc = true, + builtInRules = new Map(), + loadRules, + resolver, + eslintRecommendedPath, + getEslintRecommendedConfig, + eslintAllPath, + getEslintAllConfig + } = {}) { + const configArrayFactory = new ConfigArrayFactory({ + additionalPluginPool, + cwd, + resolvePluginsRelativeTo, + builtInRules, + resolver, + eslintRecommendedPath, + getEslintRecommendedConfig, + eslintAllPath, + getEslintAllConfig + }); + + internalSlotsMap.set(this, { + baseConfigArray: createBaseConfigArray({ + baseConfigData, + configArrayFactory, + cwd, + rulePaths, + loadRules + }), + baseConfigData, + cliConfigArray: createCLIConfigArray({ + cliConfigData, + configArrayFactory, + cwd, + ignorePath, + specificConfigPath + }), + cliConfigData, + configArrayFactory, + configCache: new Map(), + cwd, + finalizeCache: new WeakMap(), + ignorePath, + rulePaths, + specificConfigPath, + useEslintrc, + builtInRules, + loadRules + }); + } + + /** + * The path to the current working directory. + * This is used by tests. + * @type {string} + */ + get cwd() { + const { cwd } = internalSlotsMap.get(this); + + return cwd; + } + + /** + * Get the config array of a given file. + * If `filePath` was not given, it returns the config which contains only + * `baseConfigData` and `cliConfigData`. + * @param {string} [filePath] The file path to a file. + * @param {Object} [options] The options. + * @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`. + * @returns {ConfigArray} The config array of the file. + */ + getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) { + const { + baseConfigArray, + cliConfigArray, + cwd + } = internalSlotsMap.get(this); + + if (!filePath) { + return new ConfigArray(...baseConfigArray, ...cliConfigArray); + } + + const directoryPath = path__default["default"].dirname(path__default["default"].resolve(cwd, filePath)); + + debug$1(`Load config files for ${directoryPath}.`); + + return this._finalizeConfigArray( + this._loadConfigInAncestors(directoryPath), + directoryPath, + ignoreNotFoundError + ); + } + + /** + * Set the config data to override all configs. + * Require to call `clearCache()` method after this method is called. + * @param {ConfigData} configData The config data to override all configs. + * @returns {void} + */ + setOverrideConfig(configData) { + const slots = internalSlotsMap.get(this); + + slots.cliConfigData = configData; + } + + /** + * Clear config cache. + * @returns {void} + */ + clearCache() { + const slots = internalSlotsMap.get(this); + + slots.baseConfigArray = createBaseConfigArray(slots); + slots.cliConfigArray = createCLIConfigArray(slots); + slots.configCache.clear(); + } + + /** + * Load and normalize config files from the ancestor directories. + * @param {string} directoryPath The path to a leaf directory. + * @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories. + * @returns {ConfigArray} The loaded config. + * @private + */ + _loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) { + const { + baseConfigArray, + configArrayFactory, + configCache, + cwd, + useEslintrc + } = internalSlotsMap.get(this); + + if (!useEslintrc) { + return baseConfigArray; + } + + let configArray = configCache.get(directoryPath); + + // Hit cache. + if (configArray) { + debug$1(`Cache hit: ${directoryPath}.`); + return configArray; + } + debug$1(`No cache found: ${directoryPath}.`); + + const homePath = os__default["default"].homedir(); + + // Consider this is root. + if (directoryPath === homePath && cwd !== homePath) { + debug$1("Stop traversing because of considered root."); + if (configsExistInSubdirs) { + const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath); + + if (filePath) { + emitDeprecationWarning( + filePath, + "ESLINT_PERSONAL_CONFIG_SUPPRESS" + ); + } + } + return this._cacheConfig(directoryPath, baseConfigArray); + } + + // Load the config on this directory. + try { + configArray = configArrayFactory.loadInDirectory(directoryPath); + } catch (error) { + /* istanbul ignore next */ + if (error.code === "EACCES") { + debug$1("Stop traversing because of 'EACCES' error."); + return this._cacheConfig(directoryPath, baseConfigArray); + } + throw error; + } + + if (configArray.length > 0 && configArray.isRoot()) { + debug$1("Stop traversing because of 'root:true'."); + configArray.unshift(...baseConfigArray); + return this._cacheConfig(directoryPath, configArray); + } + + // Load from the ancestors and merge it. + const parentPath = path__default["default"].dirname(directoryPath); + const parentConfigArray = parentPath && parentPath !== directoryPath + ? this._loadConfigInAncestors( + parentPath, + configsExistInSubdirs || configArray.length > 0 + ) + : baseConfigArray; + + if (configArray.length > 0) { + configArray.unshift(...parentConfigArray); + } else { + configArray = parentConfigArray; + } + + // Cache and return. + return this._cacheConfig(directoryPath, configArray); + } + + /** + * Freeze and cache a given config. + * @param {string} directoryPath The path to a directory as a cache key. + * @param {ConfigArray} configArray The config array as a cache value. + * @returns {ConfigArray} The `configArray` (frozen). + */ + _cacheConfig(directoryPath, configArray) { + const { configCache } = internalSlotsMap.get(this); + + Object.freeze(configArray); + configCache.set(directoryPath, configArray); + + return configArray; + } + + /** + * Finalize a given config array. + * Concatenate `--config` and other CLI options. + * @param {ConfigArray} configArray The parent config array. + * @param {string} directoryPath The path to the leaf directory to find config files. + * @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`. + * @returns {ConfigArray} The loaded config. + * @private + */ + _finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) { + const { + cliConfigArray, + configArrayFactory, + finalizeCache, + useEslintrc, + builtInRules + } = internalSlotsMap.get(this); + + let finalConfigArray = finalizeCache.get(configArray); + + if (!finalConfigArray) { + finalConfigArray = configArray; + + // Load the personal config if there are no regular config files. + if ( + useEslintrc && + configArray.every(c => !c.filePath) && + cliConfigArray.every(c => !c.filePath) // `--config` option can be a file. + ) { + const homePath = os__default["default"].homedir(); + + debug$1("Loading the config file of the home directory:", homePath); + + const personalConfigArray = configArrayFactory.loadInDirectory( + homePath, + { name: "PersonalConfig" } + ); + + if ( + personalConfigArray.length > 0 && + !directoryPath.startsWith(homePath) + ) { + const lastElement = + personalConfigArray[personalConfigArray.length - 1]; + + emitDeprecationWarning( + lastElement.filePath, + "ESLINT_PERSONAL_CONFIG_LOAD" + ); + } + + finalConfigArray = finalConfigArray.concat(personalConfigArray); + } + + // Apply CLI options. + if (cliConfigArray.length > 0) { + finalConfigArray = finalConfigArray.concat(cliConfigArray); + } + + // Validate rule settings and environments. + const validator = new ConfigValidator({ + builtInRules + }); + + validator.validateConfigArray(finalConfigArray); + + // Cache it. + Object.freeze(finalConfigArray); + finalizeCache.set(configArray, finalConfigArray); + + debug$1( + "Configuration was determined: %o on %s", + finalConfigArray, + directoryPath + ); + } + + // At least one element (the default ignore patterns) exists. + if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) { + throw new ConfigurationNotFoundError(directoryPath); + } + + return finalConfigArray; + } +} + +/** + * @fileoverview Compatibility class for flat config. + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +/** @typedef {import("../../shared/types").Environment} Environment */ +/** @typedef {import("../../shared/types").Processor} Processor */ + +const debug = debugOrig__default["default"]("eslintrc:flat-compat"); +const cafactory = Symbol("cafactory"); + +/** + * Translates an ESLintRC-style config object into a flag-config-style config + * object. + * @param {Object} eslintrcConfig An ESLintRC-style config object. + * @param {Object} options Options to help translate the config. + * @param {string} options.resolveConfigRelativeTo To the directory to resolve + * configs from. + * @param {string} options.resolvePluginsRelativeTo The directory to resolve + * plugins from. + * @param {ReadOnlyMap} options.pluginEnvironments A map of plugin environment + * names to objects. + * @param {ReadOnlyMap} options.pluginProcessors A map of plugin processor + * names to objects. + * @returns {Object} A flag-config-style config object. + */ +function translateESLintRC(eslintrcConfig, { + resolveConfigRelativeTo, + resolvePluginsRelativeTo, + pluginEnvironments, + pluginProcessors +}) { + + const flatConfig = {}; + const configs = []; + const languageOptions = {}; + const linterOptions = {}; + const keysToCopy = ["settings", "rules", "processor"]; + const languageOptionsKeysToCopy = ["globals", "parser", "parserOptions"]; + const linterOptionsKeysToCopy = ["noInlineConfig", "reportUnusedDisableDirectives"]; + + // copy over simple translations + for (const key of keysToCopy) { + if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") { + flatConfig[key] = eslintrcConfig[key]; + } + } + + // copy over languageOptions + for (const key of languageOptionsKeysToCopy) { + if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") { + + // create the languageOptions key in the flat config + flatConfig.languageOptions = languageOptions; + + if (key === "parser") { + debug(`Resolving parser '${languageOptions[key]}' relative to ${resolveConfigRelativeTo}`); + + if (eslintrcConfig[key].error) { + throw eslintrcConfig[key].error; + } + + languageOptions[key] = eslintrcConfig[key].definition; + continue; + } + + // clone any object values that are in the eslintrc config + if (eslintrcConfig[key] && typeof eslintrcConfig[key] === "object") { + languageOptions[key] = { + ...eslintrcConfig[key] + }; + } else { + languageOptions[key] = eslintrcConfig[key]; + } + } + } + + // copy over linterOptions + for (const key of linterOptionsKeysToCopy) { + if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") { + flatConfig.linterOptions = linterOptions; + linterOptions[key] = eslintrcConfig[key]; + } + } + + // move ecmaVersion a level up + if (languageOptions.parserOptions) { + + if ("ecmaVersion" in languageOptions.parserOptions) { + languageOptions.ecmaVersion = languageOptions.parserOptions.ecmaVersion; + delete languageOptions.parserOptions.ecmaVersion; + } + + if ("sourceType" in languageOptions.parserOptions) { + languageOptions.sourceType = languageOptions.parserOptions.sourceType; + delete languageOptions.parserOptions.sourceType; + } + + // check to see if we even need parserOptions anymore and remove it if not + if (Object.keys(languageOptions.parserOptions).length === 0) { + delete languageOptions.parserOptions; + } + } + + // overrides + if (eslintrcConfig.criteria) { + flatConfig.files = [absoluteFilePath => eslintrcConfig.criteria.test(absoluteFilePath)]; + } + + // translate plugins + if (eslintrcConfig.plugins && typeof eslintrcConfig.plugins === "object") { + debug(`Translating plugins: ${eslintrcConfig.plugins}`); + + flatConfig.plugins = {}; + + for (const pluginName of Object.keys(eslintrcConfig.plugins)) { + + debug(`Translating plugin: ${pluginName}`); + debug(`Resolving plugin '${pluginName} relative to ${resolvePluginsRelativeTo}`); + + const { original: plugin, error } = eslintrcConfig.plugins[pluginName]; + + if (error) { + throw error; + } + + flatConfig.plugins[pluginName] = plugin; + + // create a config for any processors + if (plugin.processors) { + for (const processorName of Object.keys(plugin.processors)) { + if (processorName.startsWith(".")) { + debug(`Assigning processor: ${pluginName}/${processorName}`); + + configs.unshift({ + files: [`**/*${processorName}`], + processor: pluginProcessors.get(`${pluginName}/${processorName}`) + }); + } + + } + } + } + } + + // translate env - must come after plugins + if (eslintrcConfig.env && typeof eslintrcConfig.env === "object") { + for (const envName of Object.keys(eslintrcConfig.env)) { + + // only add environments that are true + if (eslintrcConfig.env[envName]) { + debug(`Translating environment: ${envName}`); + + if (environments.has(envName)) { + + // built-in environments should be defined first + configs.unshift(...translateESLintRC({ + criteria: eslintrcConfig.criteria, + ...environments.get(envName) + }, { + resolveConfigRelativeTo, + resolvePluginsRelativeTo + })); + } else if (pluginEnvironments.has(envName)) { + + // if the environment comes from a plugin, it should come after the plugin config + configs.push(...translateESLintRC({ + criteria: eslintrcConfig.criteria, + ...pluginEnvironments.get(envName) + }, { + resolveConfigRelativeTo, + resolvePluginsRelativeTo + })); + } + } + } + } + + // only add if there are actually keys in the config + if (Object.keys(flatConfig).length > 0) { + configs.push(flatConfig); + } + + return configs; +} + + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +/** + * A compatibility class for working with configs. + */ +class FlatCompat { + + constructor({ + baseDirectory = process.cwd(), + resolvePluginsRelativeTo = baseDirectory, + recommendedConfig, + allConfig + } = {}) { + this.baseDirectory = baseDirectory; + this.resolvePluginsRelativeTo = resolvePluginsRelativeTo; + this[cafactory] = new ConfigArrayFactory({ + cwd: baseDirectory, + resolvePluginsRelativeTo, + getEslintAllConfig: () => { + + if (!allConfig) { + throw new TypeError("Missing parameter 'allConfig' in FlatCompat constructor."); + } + + return allConfig; + }, + getEslintRecommendedConfig: () => { + + if (!recommendedConfig) { + throw new TypeError("Missing parameter 'recommendedConfig' in FlatCompat constructor."); + } + + return recommendedConfig; + } + }); + } + + /** + * Translates an ESLintRC-style config into a flag-config-style config. + * @param {Object} eslintrcConfig The ESLintRC-style config object. + * @returns {Object} A flag-config-style config object. + */ + config(eslintrcConfig) { + const eslintrcArray = this[cafactory].create(eslintrcConfig, { + basePath: this.baseDirectory + }); + + const flatArray = []; + let hasIgnorePatterns = false; + + eslintrcArray.forEach(configData => { + if (configData.type === "config") { + hasIgnorePatterns = hasIgnorePatterns || configData.ignorePattern; + flatArray.push(...translateESLintRC(configData, { + resolveConfigRelativeTo: path__default["default"].join(this.baseDirectory, "__placeholder.js"), + resolvePluginsRelativeTo: path__default["default"].join(this.resolvePluginsRelativeTo, "__placeholder.js"), + pluginEnvironments: eslintrcArray.pluginEnvironments, + pluginProcessors: eslintrcArray.pluginProcessors + })); + } + }); + + // combine ignorePatterns to emulate ESLintRC behavior better + if (hasIgnorePatterns) { + flatArray.unshift({ + ignores: [filePath => { + + // Compute the final config for this file. + // This filters config array elements by `files`/`excludedFiles` then merges the elements. + const finalConfig = eslintrcArray.extractConfig(filePath); + + // Test the `ignorePattern` properties of the final config. + return Boolean(finalConfig.ignores) && finalConfig.ignores(filePath); + }] + }); + } + + return flatArray; + } + + /** + * Translates the `env` section of an ESLintRC-style config. + * @param {Object} envConfig The `env` section of an ESLintRC config. + * @returns {Object[]} An array of flag-config objects representing the environments. + */ + env(envConfig) { + return this.config({ + env: envConfig + }); + } + + /** + * Translates the `extends` section of an ESLintRC-style config. + * @param {...string} configsToExtend The names of the configs to load. + * @returns {Object[]} An array of flag-config objects representing the config. + */ + extends(...configsToExtend) { + return this.config({ + extends: configsToExtend + }); + } + + /** + * Translates the `plugins` section of an ESLintRC-style config. + * @param {...string} plugins The names of the plugins to load. + * @returns {Object[]} An array of flag-config objects representing the plugins. + */ + plugins(...plugins) { + return this.config({ + plugins + }); + } +} + +/** + * @fileoverview Package exports for @eslint/eslintrc + * @author Nicholas C. Zakas + */ + +//----------------------------------------------------------------------------- +// Exports +//----------------------------------------------------------------------------- + +const Legacy = { + ConfigArray, + createConfigArrayFactoryContext: createContext, + CascadingConfigArrayFactory, + ConfigArrayFactory, + ConfigDependency, + ExtractedConfig, + IgnorePattern, + OverrideTester, + getUsedExtractedConfigs, + environments, + + // shared + ConfigOps, + ConfigValidator, + ModuleResolver, + naming +}; + +exports.FlatCompat = FlatCompat; +exports.Legacy = Legacy; +//# sourceMappingURL=eslintrc.cjs.map diff --git a/node_modules/@eslint/eslintrc/dist/eslintrc.cjs.map b/node_modules/@eslint/eslintrc/dist/eslintrc.cjs.map new file mode 100644 index 0000000..c4f4fce --- /dev/null +++ b/node_modules/@eslint/eslintrc/dist/eslintrc.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"eslintrc.cjs","sources":["../lib/config-array/ignore-pattern.js","../lib/config-array/extracted-config.js","../lib/config-array/config-array.js","../lib/config-array/config-dependency.js","../lib/config-array/override-tester.js","../lib/config-array/index.js","../lib/shared/config-ops.js","../lib/shared/deprecation-warnings.js","../lib/shared/ajv.js","../conf/config-schema.js","../conf/environments.js","../lib/shared/config-validator.js","../lib/shared/naming.js","../lib/shared/relative-module-resolver.js","../lib/config-array-factory.js","../lib/cascading-config-array-factory.js","../lib/flat-compat.js","../lib/index.js"],"sourcesContent":["/**\n * @fileoverview `IgnorePattern` class.\n *\n * `IgnorePattern` class has the set of glob patterns and the base path.\n *\n * It provides two static methods.\n *\n * - `IgnorePattern.createDefaultIgnore(cwd)`\n * Create the default predicate function.\n * - `IgnorePattern.createIgnore(ignorePatterns)`\n * Create the predicate function from multiple `IgnorePattern` objects.\n *\n * It provides two properties and a method.\n *\n * - `patterns`\n * The glob patterns that ignore to lint.\n * - `basePath`\n * The base path of the glob patterns. If absolute paths existed in the\n * glob patterns, those are handled as relative paths to the base path.\n * - `getPatternsRelativeTo(basePath)`\n * Get `patterns` as modified for a given base path. It modifies the\n * absolute paths in the patterns as prepending the difference of two base\n * paths.\n *\n * `ConfigArrayFactory` creates `IgnorePattern` objects when it processes\n * `ignorePatterns` properties.\n *\n * @author Toru Nagashima \n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport assert from \"assert\";\nimport path from \"path\";\nimport ignore from \"ignore\";\nimport debugOrig from \"debug\";\n\nconst debug = debugOrig(\"eslintrc:ignore-pattern\");\n\n/** @typedef {ReturnType} Ignore */\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\n/**\n * Get the path to the common ancestor directory of given paths.\n * @param {string[]} sourcePaths The paths to calculate the common ancestor.\n * @returns {string} The path to the common ancestor directory.\n */\nfunction getCommonAncestorPath(sourcePaths) {\n let result = sourcePaths[0];\n\n for (let i = 1; i < sourcePaths.length; ++i) {\n const a = result;\n const b = sourcePaths[i];\n\n // Set the shorter one (it's the common ancestor if one includes the other).\n result = a.length < b.length ? a : b;\n\n // Set the common ancestor.\n for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) {\n if (a[j] !== b[j]) {\n result = a.slice(0, lastSepPos);\n break;\n }\n if (a[j] === path.sep) {\n lastSepPos = j;\n }\n }\n }\n\n let resolvedResult = result || path.sep;\n\n // if Windows common ancestor is root of drive must have trailing slash to be absolute.\n if (resolvedResult && resolvedResult.endsWith(\":\") && process.platform === \"win32\") {\n resolvedResult += path.sep;\n }\n return resolvedResult;\n}\n\n/**\n * Make relative path.\n * @param {string} from The source path to get relative path.\n * @param {string} to The destination path to get relative path.\n * @returns {string} The relative path.\n */\nfunction relative(from, to) {\n const relPath = path.relative(from, to);\n\n if (path.sep === \"/\") {\n return relPath;\n }\n return relPath.split(path.sep).join(\"/\");\n}\n\n/**\n * Get the trailing slash if existed.\n * @param {string} filePath The path to check.\n * @returns {string} The trailing slash if existed.\n */\nfunction dirSuffix(filePath) {\n const isDir = (\n filePath.endsWith(path.sep) ||\n (process.platform === \"win32\" && filePath.endsWith(\"/\"))\n );\n\n return isDir ? \"/\" : \"\";\n}\n\nconst DefaultPatterns = Object.freeze([\"/**/node_modules/*\"]);\nconst DotPatterns = Object.freeze([\".*\", \"!.eslintrc.*\", \"!../\"]);\n\n//------------------------------------------------------------------------------\n// Public\n//------------------------------------------------------------------------------\n\nclass IgnorePattern {\n\n /**\n * The default patterns.\n * @type {string[]}\n */\n static get DefaultPatterns() {\n return DefaultPatterns;\n }\n\n /**\n * Create the default predicate function.\n * @param {string} cwd The current working directory.\n * @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}}\n * The preficate function.\n * The first argument is an absolute path that is checked.\n * The second argument is the flag to not ignore dotfiles.\n * If the predicate function returned `true`, it means the path should be ignored.\n */\n static createDefaultIgnore(cwd) {\n return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]);\n }\n\n /**\n * Create the predicate function from multiple `IgnorePattern` objects.\n * @param {IgnorePattern[]} ignorePatterns The list of ignore patterns.\n * @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}}\n * The preficate function.\n * The first argument is an absolute path that is checked.\n * The second argument is the flag to not ignore dotfiles.\n * If the predicate function returned `true`, it means the path should be ignored.\n */\n static createIgnore(ignorePatterns) {\n debug(\"Create with: %o\", ignorePatterns);\n\n const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath));\n const patterns = [].concat(\n ...ignorePatterns.map(p => p.getPatternsRelativeTo(basePath))\n );\n const ig = ignore({ allowRelativePaths: true }).add([...DotPatterns, ...patterns]);\n const dotIg = ignore({ allowRelativePaths: true }).add(patterns);\n\n debug(\" processed: %o\", { basePath, patterns });\n\n return Object.assign(\n (filePath, dot = false) => {\n assert(path.isAbsolute(filePath), \"'filePath' should be an absolute path.\");\n const relPathRaw = relative(basePath, filePath);\n const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath));\n const adoptedIg = dot ? dotIg : ig;\n const result = relPath !== \"\" && adoptedIg.ignores(relPath);\n\n debug(\"Check\", { filePath, dot, relativePath: relPath, result });\n return result;\n },\n { basePath, patterns }\n );\n }\n\n /**\n * Initialize a new `IgnorePattern` instance.\n * @param {string[]} patterns The glob patterns that ignore to lint.\n * @param {string} basePath The base path of `patterns`.\n */\n constructor(patterns, basePath) {\n assert(path.isAbsolute(basePath), \"'basePath' should be an absolute path.\");\n\n /**\n * The glob patterns that ignore to lint.\n * @type {string[]}\n */\n this.patterns = patterns;\n\n /**\n * The base path of `patterns`.\n * @type {string}\n */\n this.basePath = basePath;\n\n /**\n * If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`.\n *\n * It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility.\n * It's `false` as-is for `ignorePatterns` property in config files.\n * @type {boolean}\n */\n this.loose = false;\n }\n\n /**\n * Get `patterns` as modified for a given base path. It modifies the\n * absolute paths in the patterns as prepending the difference of two base\n * paths.\n * @param {string} newBasePath The base path.\n * @returns {string[]} Modifired patterns.\n */\n getPatternsRelativeTo(newBasePath) {\n assert(path.isAbsolute(newBasePath), \"'newBasePath' should be an absolute path.\");\n const { basePath, loose, patterns } = this;\n\n if (newBasePath === basePath) {\n return patterns;\n }\n const prefix = `/${relative(newBasePath, basePath)}`;\n\n return patterns.map(pattern => {\n const negative = pattern.startsWith(\"!\");\n const head = negative ? \"!\" : \"\";\n const body = negative ? pattern.slice(1) : pattern;\n\n if (body.startsWith(\"/\") || body.startsWith(\"../\")) {\n return `${head}${prefix}${body}`;\n }\n return loose ? pattern : `${head}${prefix}/**/${body}`;\n });\n }\n}\n\nexport { IgnorePattern };\n","/**\n * @fileoverview `ExtractedConfig` class.\n *\n * `ExtractedConfig` class expresses a final configuration for a specific file.\n *\n * It provides one method.\n *\n * - `toCompatibleObjectAsConfigFileContent()`\n * Convert this configuration to the compatible object as the content of\n * config files. It converts the loaded parser and plugins to strings.\n * `CLIEngine#getConfigForFile(filePath)` method uses this method.\n *\n * `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance.\n *\n * @author Toru Nagashima \n */\n\nimport { IgnorePattern } from \"./ignore-pattern.js\";\n\n// For VSCode intellisense\n/** @typedef {import(\"../../shared/types\").ConfigData} ConfigData */\n/** @typedef {import(\"../../shared/types\").GlobalConf} GlobalConf */\n/** @typedef {import(\"../../shared/types\").SeverityConf} SeverityConf */\n/** @typedef {import(\"./config-dependency\").DependentParser} DependentParser */\n/** @typedef {import(\"./config-dependency\").DependentPlugin} DependentPlugin */\n\n/**\n * Check if `xs` starts with `ys`.\n * @template T\n * @param {T[]} xs The array to check.\n * @param {T[]} ys The array that may be the first part of `xs`.\n * @returns {boolean} `true` if `xs` starts with `ys`.\n */\nfunction startsWith(xs, ys) {\n return xs.length >= ys.length && ys.every((y, i) => y === xs[i]);\n}\n\n/**\n * The class for extracted config data.\n */\nclass ExtractedConfig {\n constructor() {\n\n /**\n * The config name what `noInlineConfig` setting came from.\n * @type {string}\n */\n this.configNameOfNoInlineConfig = \"\";\n\n /**\n * Environments.\n * @type {Record}\n */\n this.env = {};\n\n /**\n * Global variables.\n * @type {Record}\n */\n this.globals = {};\n\n /**\n * The glob patterns that ignore to lint.\n * @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined}\n */\n this.ignores = void 0;\n\n /**\n * The flag that disables directive comments.\n * @type {boolean|undefined}\n */\n this.noInlineConfig = void 0;\n\n /**\n * Parser definition.\n * @type {DependentParser|null}\n */\n this.parser = null;\n\n /**\n * Options for the parser.\n * @type {Object}\n */\n this.parserOptions = {};\n\n /**\n * Plugin definitions.\n * @type {Record}\n */\n this.plugins = {};\n\n /**\n * Processor ID.\n * @type {string|null}\n */\n this.processor = null;\n\n /**\n * The flag that reports unused `eslint-disable` directive comments.\n * @type {boolean|undefined}\n */\n this.reportUnusedDisableDirectives = void 0;\n\n /**\n * Rule settings.\n * @type {Record}\n */\n this.rules = {};\n\n /**\n * Shared settings.\n * @type {Object}\n */\n this.settings = {};\n }\n\n /**\n * Convert this config to the compatible object as a config file content.\n * @returns {ConfigData} The converted object.\n */\n toCompatibleObjectAsConfigFileContent() {\n const {\n /* eslint-disable no-unused-vars */\n configNameOfNoInlineConfig: _ignore1,\n processor: _ignore2,\n /* eslint-enable no-unused-vars */\n ignores,\n ...config\n } = this;\n\n config.parser = config.parser && config.parser.filePath;\n config.plugins = Object.keys(config.plugins).filter(Boolean).reverse();\n config.ignorePatterns = ignores ? ignores.patterns : [];\n\n // Strip the default patterns from `ignorePatterns`.\n if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) {\n config.ignorePatterns =\n config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length);\n }\n\n return config;\n }\n}\n\nexport { ExtractedConfig };\n","/**\n * @fileoverview `ConfigArray` class.\n *\n * `ConfigArray` class expresses the full of a configuration. It has the entry\n * config file, base config files that were extended, loaded parsers, and loaded\n * plugins.\n *\n * `ConfigArray` class provides three properties and two methods.\n *\n * - `pluginEnvironments`\n * - `pluginProcessors`\n * - `pluginRules`\n * The `Map` objects that contain the members of all plugins that this\n * config array contains. Those map objects don't have mutation methods.\n * Those keys are the member ID such as `pluginId/memberName`.\n * - `isRoot()`\n * If `true` then this configuration has `root:true` property.\n * - `extractConfig(filePath)`\n * Extract the final configuration for a given file. This means merging\n * every config array element which that `criteria` property matched. The\n * `filePath` argument must be an absolute path.\n *\n * `ConfigArrayFactory` provides the loading logic of config files.\n *\n * @author Toru Nagashima \n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport { ExtractedConfig } from \"./extracted-config.js\";\nimport { IgnorePattern } from \"./ignore-pattern.js\";\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\n// Define types for VSCode IntelliSense.\n/** @typedef {import(\"../../shared/types\").Environment} Environment */\n/** @typedef {import(\"../../shared/types\").GlobalConf} GlobalConf */\n/** @typedef {import(\"../../shared/types\").RuleConf} RuleConf */\n/** @typedef {import(\"../../shared/types\").Rule} Rule */\n/** @typedef {import(\"../../shared/types\").Plugin} Plugin */\n/** @typedef {import(\"../../shared/types\").Processor} Processor */\n/** @typedef {import(\"./config-dependency\").DependentParser} DependentParser */\n/** @typedef {import(\"./config-dependency\").DependentPlugin} DependentPlugin */\n/** @typedef {import(\"./override-tester\")[\"OverrideTester\"]} OverrideTester */\n\n/**\n * @typedef {Object} ConfigArrayElement\n * @property {string} name The name of this config element.\n * @property {string} filePath The path to the source file of this config element.\n * @property {InstanceType|null} criteria The tester for the `files` and `excludedFiles` of this config element.\n * @property {Record|undefined} env The environment settings.\n * @property {Record|undefined} globals The global variable settings.\n * @property {IgnorePattern|undefined} ignorePattern The ignore patterns.\n * @property {boolean|undefined} noInlineConfig The flag that disables directive comments.\n * @property {DependentParser|undefined} parser The parser loader.\n * @property {Object|undefined} parserOptions The parser options.\n * @property {Record|undefined} plugins The plugin loaders.\n * @property {string|undefined} processor The processor name to refer plugin's processor.\n * @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.\n * @property {boolean|undefined} root The flag to express root.\n * @property {Record|undefined} rules The rule settings\n * @property {Object|undefined} settings The shared settings.\n * @property {\"config\" | \"ignore\" | \"implicit-processor\"} type The element type.\n */\n\n/**\n * @typedef {Object} ConfigArrayInternalSlots\n * @property {Map} cache The cache to extract configs.\n * @property {ReadonlyMap|null} envMap The map from environment ID to environment definition.\n * @property {ReadonlyMap|null} processorMap The map from processor ID to environment definition.\n * @property {ReadonlyMap|null} ruleMap The map from rule ID to rule definition.\n */\n\n/** @type {WeakMap} */\nconst internalSlotsMap = new class extends WeakMap {\n get(key) {\n let value = super.get(key);\n\n if (!value) {\n value = {\n cache: new Map(),\n envMap: null,\n processorMap: null,\n ruleMap: null\n };\n super.set(key, value);\n }\n\n return value;\n }\n}();\n\n/**\n * Get the indices which are matched to a given file.\n * @param {ConfigArrayElement[]} elements The elements.\n * @param {string} filePath The path to a target file.\n * @returns {number[]} The indices.\n */\nfunction getMatchedIndices(elements, filePath) {\n const indices = [];\n\n for (let i = elements.length - 1; i >= 0; --i) {\n const element = elements[i];\n\n if (!element.criteria || (filePath && element.criteria.test(filePath))) {\n indices.push(i);\n }\n }\n\n return indices;\n}\n\n/**\n * Check if a value is a non-null object.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is a non-null object.\n */\nfunction isNonNullObject(x) {\n return typeof x === \"object\" && x !== null;\n}\n\n/**\n * Merge two objects.\n *\n * Assign every property values of `y` to `x` if `x` doesn't have the property.\n * If `x`'s property value is an object, it does recursive.\n * @param {Object} target The destination to merge\n * @param {Object|undefined} source The source to merge.\n * @returns {void}\n */\nfunction mergeWithoutOverwrite(target, source) {\n if (!isNonNullObject(source)) {\n return;\n }\n\n for (const key of Object.keys(source)) {\n if (key === \"__proto__\") {\n continue;\n }\n\n if (isNonNullObject(target[key])) {\n mergeWithoutOverwrite(target[key], source[key]);\n } else if (target[key] === void 0) {\n if (isNonNullObject(source[key])) {\n target[key] = Array.isArray(source[key]) ? [] : {};\n mergeWithoutOverwrite(target[key], source[key]);\n } else if (source[key] !== void 0) {\n target[key] = source[key];\n }\n }\n }\n}\n\n/**\n * The error for plugin conflicts.\n */\nclass PluginConflictError extends Error {\n\n /**\n * Initialize this error object.\n * @param {string} pluginId The plugin ID.\n * @param {{filePath:string, importerName:string}[]} plugins The resolved plugins.\n */\n constructor(pluginId, plugins) {\n super(`Plugin \"${pluginId}\" was conflicted between ${plugins.map(p => `\"${p.importerName}\"`).join(\" and \")}.`);\n this.messageTemplate = \"plugin-conflict\";\n this.messageData = { pluginId, plugins };\n }\n}\n\n/**\n * Merge plugins.\n * `target`'s definition is prior to `source`'s.\n * @param {Record} target The destination to merge\n * @param {Record|undefined} source The source to merge.\n * @returns {void}\n */\nfunction mergePlugins(target, source) {\n if (!isNonNullObject(source)) {\n return;\n }\n\n for (const key of Object.keys(source)) {\n if (key === \"__proto__\") {\n continue;\n }\n const targetValue = target[key];\n const sourceValue = source[key];\n\n // Adopt the plugin which was found at first.\n if (targetValue === void 0) {\n if (sourceValue.error) {\n throw sourceValue.error;\n }\n target[key] = sourceValue;\n } else if (sourceValue.filePath !== targetValue.filePath) {\n throw new PluginConflictError(key, [\n {\n filePath: targetValue.filePath,\n importerName: targetValue.importerName\n },\n {\n filePath: sourceValue.filePath,\n importerName: sourceValue.importerName\n }\n ]);\n }\n }\n}\n\n/**\n * Merge rule configs.\n * `target`'s definition is prior to `source`'s.\n * @param {Record} target The destination to merge\n * @param {Record|undefined} source The source to merge.\n * @returns {void}\n */\nfunction mergeRuleConfigs(target, source) {\n if (!isNonNullObject(source)) {\n return;\n }\n\n for (const key of Object.keys(source)) {\n if (key === \"__proto__\") {\n continue;\n }\n const targetDef = target[key];\n const sourceDef = source[key];\n\n // Adopt the rule config which was found at first.\n if (targetDef === void 0) {\n if (Array.isArray(sourceDef)) {\n target[key] = [...sourceDef];\n } else {\n target[key] = [sourceDef];\n }\n\n /*\n * If the first found rule config is severity only and the current rule\n * config has options, merge the severity and the options.\n */\n } else if (\n targetDef.length === 1 &&\n Array.isArray(sourceDef) &&\n sourceDef.length >= 2\n ) {\n targetDef.push(...sourceDef.slice(1));\n }\n }\n}\n\n/**\n * Create the extracted config.\n * @param {ConfigArray} instance The config elements.\n * @param {number[]} indices The indices to use.\n * @returns {ExtractedConfig} The extracted config.\n */\nfunction createConfig(instance, indices) {\n const config = new ExtractedConfig();\n const ignorePatterns = [];\n\n // Merge elements.\n for (const index of indices) {\n const element = instance[index];\n\n // Adopt the parser which was found at first.\n if (!config.parser && element.parser) {\n if (element.parser.error) {\n throw element.parser.error;\n }\n config.parser = element.parser;\n }\n\n // Adopt the processor which was found at first.\n if (!config.processor && element.processor) {\n config.processor = element.processor;\n }\n\n // Adopt the noInlineConfig which was found at first.\n if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {\n config.noInlineConfig = element.noInlineConfig;\n config.configNameOfNoInlineConfig = element.name;\n }\n\n // Adopt the reportUnusedDisableDirectives which was found at first.\n if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {\n config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;\n }\n\n // Collect ignorePatterns\n if (element.ignorePattern) {\n ignorePatterns.push(element.ignorePattern);\n }\n\n // Merge others.\n mergeWithoutOverwrite(config.env, element.env);\n mergeWithoutOverwrite(config.globals, element.globals);\n mergeWithoutOverwrite(config.parserOptions, element.parserOptions);\n mergeWithoutOverwrite(config.settings, element.settings);\n mergePlugins(config.plugins, element.plugins);\n mergeRuleConfigs(config.rules, element.rules);\n }\n\n // Create the predicate function for ignore patterns.\n if (ignorePatterns.length > 0) {\n config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());\n }\n\n return config;\n}\n\n/**\n * Collect definitions.\n * @template T, U\n * @param {string} pluginId The plugin ID for prefix.\n * @param {Record} defs The definitions to collect.\n * @param {Map} map The map to output.\n * @param {function(T): U} [normalize] The normalize function for each value.\n * @returns {void}\n */\nfunction collect(pluginId, defs, map, normalize) {\n if (defs) {\n const prefix = pluginId && `${pluginId}/`;\n\n for (const [key, value] of Object.entries(defs)) {\n map.set(\n `${prefix}${key}`,\n normalize ? normalize(value) : value\n );\n }\n }\n}\n\n/**\n * Normalize a rule definition.\n * @param {Function|Rule} rule The rule definition to normalize.\n * @returns {Rule} The normalized rule definition.\n */\nfunction normalizePluginRule(rule) {\n return typeof rule === \"function\" ? { create: rule } : rule;\n}\n\n/**\n * Delete the mutation methods from a given map.\n * @param {Map} map The map object to delete.\n * @returns {void}\n */\nfunction deleteMutationMethods(map) {\n Object.defineProperties(map, {\n clear: { configurable: true, value: void 0 },\n delete: { configurable: true, value: void 0 },\n set: { configurable: true, value: void 0 }\n });\n}\n\n/**\n * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.\n * @param {ConfigArrayElement[]} elements The config elements.\n * @param {ConfigArrayInternalSlots} slots The internal slots.\n * @returns {void}\n */\nfunction initPluginMemberMaps(elements, slots) {\n const processed = new Set();\n\n slots.envMap = new Map();\n slots.processorMap = new Map();\n slots.ruleMap = new Map();\n\n for (const element of elements) {\n if (!element.plugins) {\n continue;\n }\n\n for (const [pluginId, value] of Object.entries(element.plugins)) {\n const plugin = value.definition;\n\n if (!plugin || processed.has(pluginId)) {\n continue;\n }\n processed.add(pluginId);\n\n collect(pluginId, plugin.environments, slots.envMap);\n collect(pluginId, plugin.processors, slots.processorMap);\n collect(pluginId, plugin.rules, slots.ruleMap, normalizePluginRule);\n }\n }\n\n deleteMutationMethods(slots.envMap);\n deleteMutationMethods(slots.processorMap);\n deleteMutationMethods(slots.ruleMap);\n}\n\n/**\n * Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.\n * @param {ConfigArray} instance The config elements.\n * @returns {ConfigArrayInternalSlots} The extracted config.\n */\nfunction ensurePluginMemberMaps(instance) {\n const slots = internalSlotsMap.get(instance);\n\n if (!slots.ruleMap) {\n initPluginMemberMaps(instance, slots);\n }\n\n return slots;\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/**\n * The Config Array.\n *\n * `ConfigArray` instance contains all settings, parsers, and plugins.\n * You need to call `ConfigArray#extractConfig(filePath)` method in order to\n * extract, merge and get only the config data which is related to an arbitrary\n * file.\n * @extends {Array}\n */\nclass ConfigArray extends Array {\n\n /**\n * Get the plugin environments.\n * The returned map cannot be mutated.\n * @type {ReadonlyMap} The plugin environments.\n */\n get pluginEnvironments() {\n return ensurePluginMemberMaps(this).envMap;\n }\n\n /**\n * Get the plugin processors.\n * The returned map cannot be mutated.\n * @type {ReadonlyMap} The plugin processors.\n */\n get pluginProcessors() {\n return ensurePluginMemberMaps(this).processorMap;\n }\n\n /**\n * Get the plugin rules.\n * The returned map cannot be mutated.\n * @returns {ReadonlyMap} The plugin rules.\n */\n get pluginRules() {\n return ensurePluginMemberMaps(this).ruleMap;\n }\n\n /**\n * Check if this config has `root` flag.\n * @returns {boolean} `true` if this config array is root.\n */\n isRoot() {\n for (let i = this.length - 1; i >= 0; --i) {\n const root = this[i].root;\n\n if (typeof root === \"boolean\") {\n return root;\n }\n }\n return false;\n }\n\n /**\n * Extract the config data which is related to a given file.\n * @param {string} filePath The absolute path to the target file.\n * @returns {ExtractedConfig} The extracted config data.\n */\n extractConfig(filePath) {\n const { cache } = internalSlotsMap.get(this);\n const indices = getMatchedIndices(this, filePath);\n const cacheKey = indices.join(\",\");\n\n if (!cache.has(cacheKey)) {\n cache.set(cacheKey, createConfig(this, indices));\n }\n\n return cache.get(cacheKey);\n }\n\n /**\n * Check if a given path is an additional lint target.\n * @param {string} filePath The absolute path to the target file.\n * @returns {boolean} `true` if the file is an additional lint target.\n */\n isAdditionalTargetPath(filePath) {\n for (const { criteria, type } of this) {\n if (\n type === \"config\" &&\n criteria &&\n !criteria.endsWithWildcard &&\n criteria.test(filePath)\n ) {\n return true;\n }\n }\n return false;\n }\n}\n\n/**\n * Get the used extracted configs.\n * CLIEngine will use this method to collect used deprecated rules.\n * @param {ConfigArray} instance The config array object to get.\n * @returns {ExtractedConfig[]} The used extracted configs.\n * @private\n */\nfunction getUsedExtractedConfigs(instance) {\n const { cache } = internalSlotsMap.get(instance);\n\n return Array.from(cache.values());\n}\n\n\nexport {\n ConfigArray,\n getUsedExtractedConfigs\n};\n","/**\n * @fileoverview `ConfigDependency` class.\n *\n * `ConfigDependency` class expresses a loaded parser or plugin.\n *\n * If the parser or plugin was loaded successfully, it has `definition` property\n * and `filePath` property. Otherwise, it has `error` property.\n *\n * When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it\n * omits `definition` property.\n *\n * `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers\n * or plugins.\n *\n * @author Toru Nagashima \n */\n\nimport util from \"util\";\n\n/**\n * The class is to store parsers or plugins.\n * This class hides the loaded object from `JSON.stringify()` and `console.log`.\n * @template T\n */\nclass ConfigDependency {\n\n /**\n * Initialize this instance.\n * @param {Object} data The dependency data.\n * @param {T} [data.definition] The dependency if the loading succeeded.\n * @param {T} [data.original] The original, non-normalized dependency if the loading succeeded.\n * @param {Error} [data.error] The error object if the loading failed.\n * @param {string} [data.filePath] The actual path to the dependency if the loading succeeded.\n * @param {string} data.id The ID of this dependency.\n * @param {string} data.importerName The name of the config file which loads this dependency.\n * @param {string} data.importerPath The path to the config file which loads this dependency.\n */\n constructor({\n definition = null,\n original = null,\n error = null,\n filePath = null,\n id,\n importerName,\n importerPath\n }) {\n\n /**\n * The loaded dependency if the loading succeeded.\n * @type {T|null}\n */\n this.definition = definition;\n\n /**\n * The original dependency as loaded directly from disk if the loading succeeded.\n * @type {T|null}\n */\n this.original = original;\n\n /**\n * The error object if the loading failed.\n * @type {Error|null}\n */\n this.error = error;\n\n /**\n * The loaded dependency if the loading succeeded.\n * @type {string|null}\n */\n this.filePath = filePath;\n\n /**\n * The ID of this dependency.\n * @type {string}\n */\n this.id = id;\n\n /**\n * The name of the config file which loads this dependency.\n * @type {string}\n */\n this.importerName = importerName;\n\n /**\n * The path to the config file which loads this dependency.\n * @type {string}\n */\n this.importerPath = importerPath;\n }\n\n // eslint-disable-next-line jsdoc/require-description\n /**\n * @returns {Object} a JSON compatible object.\n */\n toJSON() {\n const obj = this[util.inspect.custom]();\n\n // Display `error.message` (`Error#message` is unenumerable).\n if (obj.error instanceof Error) {\n obj.error = { ...obj.error, message: obj.error.message };\n }\n\n return obj;\n }\n\n // eslint-disable-next-line jsdoc/require-description\n /**\n * @returns {Object} an object to display by `console.log()`.\n */\n [util.inspect.custom]() {\n const {\n definition: _ignore1, // eslint-disable-line no-unused-vars\n original: _ignore2, // eslint-disable-line no-unused-vars\n ...obj\n } = this;\n\n return obj;\n }\n}\n\n/** @typedef {ConfigDependency} DependentParser */\n/** @typedef {ConfigDependency} DependentPlugin */\n\nexport { ConfigDependency };\n","/**\n * @fileoverview `OverrideTester` class.\n *\n * `OverrideTester` class handles `files` property and `excludedFiles` property\n * of `overrides` config.\n *\n * It provides one method.\n *\n * - `test(filePath)`\n * Test if a file path matches the pair of `files` property and\n * `excludedFiles` property. The `filePath` argument must be an absolute\n * path.\n *\n * `ConfigArrayFactory` creates `OverrideTester` objects when it processes\n * `overrides` properties.\n *\n * @author Toru Nagashima \n */\n\nimport assert from \"assert\";\nimport path from \"path\";\nimport util from \"util\";\nimport minimatch from \"minimatch\";\n\nconst { Minimatch } = minimatch;\n\nconst minimatchOpts = { dot: true, matchBase: true };\n\n/**\n * @typedef {Object} Pattern\n * @property {InstanceType[] | null} includes The positive matchers.\n * @property {InstanceType[] | null} excludes The negative matchers.\n */\n\n/**\n * Normalize a given pattern to an array.\n * @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns.\n * @returns {string[]|null} Normalized patterns.\n * @private\n */\nfunction normalizePatterns(patterns) {\n if (Array.isArray(patterns)) {\n return patterns.filter(Boolean);\n }\n if (typeof patterns === \"string\" && patterns) {\n return [patterns];\n }\n return [];\n}\n\n/**\n * Create the matchers of given patterns.\n * @param {string[]} patterns The patterns.\n * @returns {InstanceType[] | null} The matchers.\n */\nfunction toMatcher(patterns) {\n if (patterns.length === 0) {\n return null;\n }\n return patterns.map(pattern => {\n if (/^\\.[/\\\\]/u.test(pattern)) {\n return new Minimatch(\n pattern.slice(2),\n\n // `./*.js` should not match with `subdir/foo.js`\n { ...minimatchOpts, matchBase: false }\n );\n }\n return new Minimatch(pattern, minimatchOpts);\n });\n}\n\n/**\n * Convert a given matcher to string.\n * @param {Pattern} matchers The matchers.\n * @returns {string} The string expression of the matcher.\n */\nfunction patternToJson({ includes, excludes }) {\n return {\n includes: includes && includes.map(m => m.pattern),\n excludes: excludes && excludes.map(m => m.pattern)\n };\n}\n\n/**\n * The class to test given paths are matched by the patterns.\n */\nclass OverrideTester {\n\n /**\n * Create a tester with given criteria.\n * If there are no criteria, returns `null`.\n * @param {string|string[]} files The glob patterns for included files.\n * @param {string|string[]} excludedFiles The glob patterns for excluded files.\n * @param {string} basePath The path to the base directory to test paths.\n * @returns {OverrideTester|null} The created instance or `null`.\n */\n static create(files, excludedFiles, basePath) {\n const includePatterns = normalizePatterns(files);\n const excludePatterns = normalizePatterns(excludedFiles);\n let endsWithWildcard = false;\n\n if (includePatterns.length === 0) {\n return null;\n }\n\n // Rejects absolute paths or relative paths to parents.\n for (const pattern of includePatterns) {\n if (path.isAbsolute(pattern) || pattern.includes(\"..\")) {\n throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);\n }\n if (pattern.endsWith(\"*\")) {\n endsWithWildcard = true;\n }\n }\n for (const pattern of excludePatterns) {\n if (path.isAbsolute(pattern) || pattern.includes(\"..\")) {\n throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);\n }\n }\n\n const includes = toMatcher(includePatterns);\n const excludes = toMatcher(excludePatterns);\n\n return new OverrideTester(\n [{ includes, excludes }],\n basePath,\n endsWithWildcard\n );\n }\n\n /**\n * Combine two testers by logical and.\n * If either of the testers was `null`, returns the other tester.\n * The `basePath` property of the two must be the same value.\n * @param {OverrideTester|null} a A tester.\n * @param {OverrideTester|null} b Another tester.\n * @returns {OverrideTester|null} Combined tester.\n */\n static and(a, b) {\n if (!b) {\n return a && new OverrideTester(\n a.patterns,\n a.basePath,\n a.endsWithWildcard\n );\n }\n if (!a) {\n return new OverrideTester(\n b.patterns,\n b.basePath,\n b.endsWithWildcard\n );\n }\n\n assert.strictEqual(a.basePath, b.basePath);\n return new OverrideTester(\n a.patterns.concat(b.patterns),\n a.basePath,\n a.endsWithWildcard || b.endsWithWildcard\n );\n }\n\n /**\n * Initialize this instance.\n * @param {Pattern[]} patterns The matchers.\n * @param {string} basePath The base path.\n * @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`.\n */\n constructor(patterns, basePath, endsWithWildcard = false) {\n\n /** @type {Pattern[]} */\n this.patterns = patterns;\n\n /** @type {string} */\n this.basePath = basePath;\n\n /** @type {boolean} */\n this.endsWithWildcard = endsWithWildcard;\n }\n\n /**\n * Test if a given path is matched or not.\n * @param {string} filePath The absolute path to the target file.\n * @returns {boolean} `true` if the path was matched.\n */\n test(filePath) {\n if (typeof filePath !== \"string\" || !path.isAbsolute(filePath)) {\n throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`);\n }\n const relativePath = path.relative(this.basePath, filePath);\n\n return this.patterns.every(({ includes, excludes }) => (\n (!includes || includes.some(m => m.match(relativePath))) &&\n (!excludes || !excludes.some(m => m.match(relativePath)))\n ));\n }\n\n // eslint-disable-next-line jsdoc/require-description\n /**\n * @returns {Object} a JSON compatible object.\n */\n toJSON() {\n if (this.patterns.length === 1) {\n return {\n ...patternToJson(this.patterns[0]),\n basePath: this.basePath\n };\n }\n return {\n AND: this.patterns.map(patternToJson),\n basePath: this.basePath\n };\n }\n\n // eslint-disable-next-line jsdoc/require-description\n /**\n * @returns {Object} an object to display by `console.log()`.\n */\n [util.inspect.custom]() {\n return this.toJSON();\n }\n}\n\nexport { OverrideTester };\n","/**\n * @fileoverview `ConfigArray` class.\n * @author Toru Nagashima \n */\n\nimport { ConfigArray, getUsedExtractedConfigs } from \"./config-array.js\";\nimport { ConfigDependency } from \"./config-dependency.js\";\nimport { ExtractedConfig } from \"./extracted-config.js\";\nimport { IgnorePattern } from \"./ignore-pattern.js\";\nimport { OverrideTester } from \"./override-tester.js\";\n\nexport {\n ConfigArray,\n ConfigDependency,\n ExtractedConfig,\n IgnorePattern,\n OverrideTester,\n getUsedExtractedConfigs\n};\n","/**\n * @fileoverview Config file operations. This file must be usable in the browser,\n * so no Node-specific code can be here.\n * @author Nicholas C. Zakas\n */\n\n//------------------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------------------\n\nconst RULE_SEVERITY_STRINGS = [\"off\", \"warn\", \"error\"],\n RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {\n map[value] = index;\n return map;\n }, {}),\n VALID_SEVERITIES = [0, 1, 2, \"off\", \"warn\", \"error\"];\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/**\n * Normalizes the severity value of a rule's configuration to a number\n * @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally\n * received from the user. A valid config value is either 0, 1, 2, the string \"off\" (treated the same as 0),\n * the string \"warn\" (treated the same as 1), the string \"error\" (treated the same as 2), or an array\n * whose first element is one of the above values. Strings are matched case-insensitively.\n * @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.\n */\nfunction getRuleSeverity(ruleConfig) {\n const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;\n\n if (severityValue === 0 || severityValue === 1 || severityValue === 2) {\n return severityValue;\n }\n\n if (typeof severityValue === \"string\") {\n return RULE_SEVERITY[severityValue.toLowerCase()] || 0;\n }\n\n return 0;\n}\n\n/**\n * Converts old-style severity settings (0, 1, 2) into new-style\n * severity settings (off, warn, error) for all rules. Assumption is that severity\n * values have already been validated as correct.\n * @param {Object} config The config object to normalize.\n * @returns {void}\n */\nfunction normalizeToStrings(config) {\n\n if (config.rules) {\n Object.keys(config.rules).forEach(ruleId => {\n const ruleConfig = config.rules[ruleId];\n\n if (typeof ruleConfig === \"number\") {\n config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];\n } else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === \"number\") {\n ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];\n }\n });\n }\n}\n\n/**\n * Determines if the severity for the given rule configuration represents an error.\n * @param {int|string|Array} ruleConfig The configuration for an individual rule.\n * @returns {boolean} True if the rule represents an error, false if not.\n */\nfunction isErrorSeverity(ruleConfig) {\n return getRuleSeverity(ruleConfig) === 2;\n}\n\n/**\n * Checks whether a given config has valid severity or not.\n * @param {number|string|Array} ruleConfig The configuration for an individual rule.\n * @returns {boolean} `true` if the configuration has valid severity.\n */\nfunction isValidSeverity(ruleConfig) {\n let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;\n\n if (typeof severity === \"string\") {\n severity = severity.toLowerCase();\n }\n return VALID_SEVERITIES.indexOf(severity) !== -1;\n}\n\n/**\n * Checks whether every rule of a given config has valid severity or not.\n * @param {Object} config The configuration for rules.\n * @returns {boolean} `true` if the configuration has valid severity.\n */\nfunction isEverySeverityValid(config) {\n return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));\n}\n\n/**\n * Normalizes a value for a global in a config\n * @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in\n * a global directive comment\n * @returns {(\"readable\"|\"writeable\"|\"off\")} The value normalized as a string\n * @throws Error if global value is invalid\n */\nfunction normalizeConfigGlobal(configuredValue) {\n switch (configuredValue) {\n case \"off\":\n return \"off\";\n\n case true:\n case \"true\":\n case \"writeable\":\n case \"writable\":\n return \"writable\";\n\n case null:\n case false:\n case \"false\":\n case \"readable\":\n case \"readonly\":\n return \"readonly\";\n\n default:\n throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);\n }\n}\n\nexport {\n getRuleSeverity,\n normalizeToStrings,\n isErrorSeverity,\n isValidSeverity,\n isEverySeverityValid,\n normalizeConfigGlobal\n};\n","/**\n * @fileoverview Provide the function that emits deprecation warnings.\n * @author Toru Nagashima \n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport path from \"path\";\n\n//------------------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------------------\n\n// Defitions for deprecation warnings.\nconst deprecationWarningMessages = {\n ESLINT_LEGACY_ECMAFEATURES:\n \"The 'ecmaFeatures' config file property is deprecated and has no effect.\",\n ESLINT_PERSONAL_CONFIG_LOAD:\n \"'~/.eslintrc.*' config files have been deprecated. \" +\n \"Please use a config file per project or the '--config' option.\",\n ESLINT_PERSONAL_CONFIG_SUPPRESS:\n \"'~/.eslintrc.*' config files have been deprecated. \" +\n \"Please remove it or add 'root:true' to the config files in your \" +\n \"projects in order to avoid loading '~/.eslintrc.*' accidentally.\"\n};\n\nconst sourceFileErrorCache = new Set();\n\n/**\n * Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted\n * for each unique file path, but repeated invocations with the same file path have no effect.\n * No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.\n * @param {string} source The name of the configuration source to report the warning for.\n * @param {string} errorCode The warning message to show.\n * @returns {void}\n */\nfunction emitDeprecationWarning(source, errorCode) {\n const cacheKey = JSON.stringify({ source, errorCode });\n\n if (sourceFileErrorCache.has(cacheKey)) {\n return;\n }\n sourceFileErrorCache.add(cacheKey);\n\n const rel = path.relative(process.cwd(), source);\n const message = deprecationWarningMessages[errorCode];\n\n process.emitWarning(\n `${message} (found in \"${rel}\")`,\n \"DeprecationWarning\",\n errorCode\n );\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport {\n emitDeprecationWarning\n};\n","/**\n * @fileoverview The instance of Ajv validator.\n * @author Evgeny Poberezkin\n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport Ajv from \"ajv\";\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/*\n * Copied from ajv/lib/refs/json-schema-draft-04.json\n * The MIT License (MIT)\n * Copyright (c) 2015-2017 Evgeny Poberezkin\n */\nconst metaSchema = {\n id: \"http://json-schema.org/draft-04/schema#\",\n $schema: \"http://json-schema.org/draft-04/schema#\",\n description: \"Core schema meta-schema\",\n definitions: {\n schemaArray: {\n type: \"array\",\n minItems: 1,\n items: { $ref: \"#\" }\n },\n positiveInteger: {\n type: \"integer\",\n minimum: 0\n },\n positiveIntegerDefault0: {\n allOf: [{ $ref: \"#/definitions/positiveInteger\" }, { default: 0 }]\n },\n simpleTypes: {\n enum: [\"array\", \"boolean\", \"integer\", \"null\", \"number\", \"object\", \"string\"]\n },\n stringArray: {\n type: \"array\",\n items: { type: \"string\" },\n minItems: 1,\n uniqueItems: true\n }\n },\n type: \"object\",\n properties: {\n id: {\n type: \"string\"\n },\n $schema: {\n type: \"string\"\n },\n title: {\n type: \"string\"\n },\n description: {\n type: \"string\"\n },\n default: { },\n multipleOf: {\n type: \"number\",\n minimum: 0,\n exclusiveMinimum: true\n },\n maximum: {\n type: \"number\"\n },\n exclusiveMaximum: {\n type: \"boolean\",\n default: false\n },\n minimum: {\n type: \"number\"\n },\n exclusiveMinimum: {\n type: \"boolean\",\n default: false\n },\n maxLength: { $ref: \"#/definitions/positiveInteger\" },\n minLength: { $ref: \"#/definitions/positiveIntegerDefault0\" },\n pattern: {\n type: \"string\",\n format: \"regex\"\n },\n additionalItems: {\n anyOf: [\n { type: \"boolean\" },\n { $ref: \"#\" }\n ],\n default: { }\n },\n items: {\n anyOf: [\n { $ref: \"#\" },\n { $ref: \"#/definitions/schemaArray\" }\n ],\n default: { }\n },\n maxItems: { $ref: \"#/definitions/positiveInteger\" },\n minItems: { $ref: \"#/definitions/positiveIntegerDefault0\" },\n uniqueItems: {\n type: \"boolean\",\n default: false\n },\n maxProperties: { $ref: \"#/definitions/positiveInteger\" },\n minProperties: { $ref: \"#/definitions/positiveIntegerDefault0\" },\n required: { $ref: \"#/definitions/stringArray\" },\n additionalProperties: {\n anyOf: [\n { type: \"boolean\" },\n { $ref: \"#\" }\n ],\n default: { }\n },\n definitions: {\n type: \"object\",\n additionalProperties: { $ref: \"#\" },\n default: { }\n },\n properties: {\n type: \"object\",\n additionalProperties: { $ref: \"#\" },\n default: { }\n },\n patternProperties: {\n type: \"object\",\n additionalProperties: { $ref: \"#\" },\n default: { }\n },\n dependencies: {\n type: \"object\",\n additionalProperties: {\n anyOf: [\n { $ref: \"#\" },\n { $ref: \"#/definitions/stringArray\" }\n ]\n }\n },\n enum: {\n type: \"array\",\n minItems: 1,\n uniqueItems: true\n },\n type: {\n anyOf: [\n { $ref: \"#/definitions/simpleTypes\" },\n {\n type: \"array\",\n items: { $ref: \"#/definitions/simpleTypes\" },\n minItems: 1,\n uniqueItems: true\n }\n ]\n },\n format: { type: \"string\" },\n allOf: { $ref: \"#/definitions/schemaArray\" },\n anyOf: { $ref: \"#/definitions/schemaArray\" },\n oneOf: { $ref: \"#/definitions/schemaArray\" },\n not: { $ref: \"#\" }\n },\n dependencies: {\n exclusiveMaximum: [\"maximum\"],\n exclusiveMinimum: [\"minimum\"]\n },\n default: { }\n};\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport default (additionalOptions = {}) => {\n const ajv = new Ajv({\n meta: false,\n useDefaults: true,\n validateSchema: false,\n missingRefs: \"ignore\",\n verbose: true,\n schemaId: \"auto\",\n ...additionalOptions\n });\n\n ajv.addMetaSchema(metaSchema);\n // eslint-disable-next-line no-underscore-dangle\n ajv._opts.defaultMeta = metaSchema.id;\n\n return ajv;\n};\n","/**\n * @fileoverview Defines a schema for configs.\n * @author Sylvan Mably\n */\n\nconst baseConfigProperties = {\n $schema: { type: \"string\" },\n env: { type: \"object\" },\n extends: { $ref: \"#/definitions/stringOrStrings\" },\n globals: { type: \"object\" },\n overrides: {\n type: \"array\",\n items: { $ref: \"#/definitions/overrideConfig\" },\n additionalItems: false\n },\n parser: { type: [\"string\", \"null\"] },\n parserOptions: { type: \"object\" },\n plugins: { type: \"array\" },\n processor: { type: \"string\" },\n rules: { type: \"object\" },\n settings: { type: \"object\" },\n noInlineConfig: { type: \"boolean\" },\n reportUnusedDisableDirectives: { type: \"boolean\" },\n\n ecmaFeatures: { type: \"object\" } // deprecated; logs a warning when used\n};\n\nconst configSchema = {\n definitions: {\n stringOrStrings: {\n oneOf: [\n { type: \"string\" },\n {\n type: \"array\",\n items: { type: \"string\" },\n additionalItems: false\n }\n ]\n },\n stringOrStringsRequired: {\n oneOf: [\n { type: \"string\" },\n {\n type: \"array\",\n items: { type: \"string\" },\n additionalItems: false,\n minItems: 1\n }\n ]\n },\n\n // Config at top-level.\n objectConfig: {\n type: \"object\",\n properties: {\n root: { type: \"boolean\" },\n ignorePatterns: { $ref: \"#/definitions/stringOrStrings\" },\n ...baseConfigProperties\n },\n additionalProperties: false\n },\n\n // Config in `overrides`.\n overrideConfig: {\n type: \"object\",\n properties: {\n excludedFiles: { $ref: \"#/definitions/stringOrStrings\" },\n files: { $ref: \"#/definitions/stringOrStringsRequired\" },\n ...baseConfigProperties\n },\n required: [\"files\"],\n additionalProperties: false\n }\n },\n\n $ref: \"#/definitions/objectConfig\"\n};\n\nexport default configSchema;\n","/**\n * @fileoverview Defines environment settings and globals.\n * @author Elan Shanker\n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport globals from \"globals\";\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\n/**\n * Get the object that has difference.\n * @param {Record} current The newer object.\n * @param {Record} prev The older object.\n * @returns {Record} The difference object.\n */\nfunction getDiff(current, prev) {\n const retv = {};\n\n for (const [key, value] of Object.entries(current)) {\n if (!Object.hasOwnProperty.call(prev, key)) {\n retv[key] = value;\n }\n }\n\n return retv;\n}\n\nconst newGlobals2015 = getDiff(globals.es2015, globals.es5); // 19 variables such as Promise, Map, ...\nconst newGlobals2017 = {\n Atomics: false,\n SharedArrayBuffer: false\n};\nconst newGlobals2020 = {\n BigInt: false,\n BigInt64Array: false,\n BigUint64Array: false,\n globalThis: false\n};\n\nconst newGlobals2021 = {\n AggregateError: false,\n FinalizationRegistry: false,\n WeakRef: false\n};\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/** @type {Map} */\nexport default new Map(Object.entries({\n\n // Language\n builtin: {\n globals: globals.es5\n },\n es6: {\n globals: newGlobals2015,\n parserOptions: {\n ecmaVersion: 6\n }\n },\n es2015: {\n globals: newGlobals2015,\n parserOptions: {\n ecmaVersion: 6\n }\n },\n es2016: {\n globals: newGlobals2015,\n parserOptions: {\n ecmaVersion: 7\n }\n },\n es2017: {\n globals: { ...newGlobals2015, ...newGlobals2017 },\n parserOptions: {\n ecmaVersion: 8\n }\n },\n es2018: {\n globals: { ...newGlobals2015, ...newGlobals2017 },\n parserOptions: {\n ecmaVersion: 9\n }\n },\n es2019: {\n globals: { ...newGlobals2015, ...newGlobals2017 },\n parserOptions: {\n ecmaVersion: 10\n }\n },\n es2020: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },\n parserOptions: {\n ecmaVersion: 11\n }\n },\n es2021: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 12\n }\n },\n es2022: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 13\n }\n },\n es2023: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 14\n }\n },\n es2024: {\n globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },\n parserOptions: {\n ecmaVersion: 15\n }\n },\n\n // Platforms\n browser: {\n globals: globals.browser\n },\n node: {\n globals: globals.node,\n parserOptions: {\n ecmaFeatures: {\n globalReturn: true\n }\n }\n },\n \"shared-node-browser\": {\n globals: globals[\"shared-node-browser\"]\n },\n worker: {\n globals: globals.worker\n },\n serviceworker: {\n globals: globals.serviceworker\n },\n\n // Frameworks\n commonjs: {\n globals: globals.commonjs,\n parserOptions: {\n ecmaFeatures: {\n globalReturn: true\n }\n }\n },\n amd: {\n globals: globals.amd\n },\n mocha: {\n globals: globals.mocha\n },\n jasmine: {\n globals: globals.jasmine\n },\n jest: {\n globals: globals.jest\n },\n phantomjs: {\n globals: globals.phantomjs\n },\n jquery: {\n globals: globals.jquery\n },\n qunit: {\n globals: globals.qunit\n },\n prototypejs: {\n globals: globals.prototypejs\n },\n shelljs: {\n globals: globals.shelljs\n },\n meteor: {\n globals: globals.meteor\n },\n mongo: {\n globals: globals.mongo\n },\n protractor: {\n globals: globals.protractor\n },\n applescript: {\n globals: globals.applescript\n },\n nashorn: {\n globals: globals.nashorn\n },\n atomtest: {\n globals: globals.atomtest\n },\n embertest: {\n globals: globals.embertest\n },\n webextensions: {\n globals: globals.webextensions\n },\n greasemonkey: {\n globals: globals.greasemonkey\n }\n}));\n","/**\n * @fileoverview Validates configs.\n * @author Brandon Mills\n */\n\n/* eslint class-methods-use-this: \"off\" */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport util from \"util\";\nimport * as ConfigOps from \"./config-ops.js\";\nimport { emitDeprecationWarning } from \"./deprecation-warnings.js\";\nimport ajvOrig from \"./ajv.js\";\nimport configSchema from \"../../conf/config-schema.js\";\nimport BuiltInEnvironments from \"../../conf/environments.js\";\n\nconst ajv = ajvOrig();\n\nconst ruleValidators = new WeakMap();\nconst noop = Function.prototype;\n\n//------------------------------------------------------------------------------\n// Private\n//------------------------------------------------------------------------------\nlet validateSchema;\nconst severityMap = {\n error: 2,\n warn: 1,\n off: 0\n};\n\nconst validated = new WeakSet();\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\nexport default class ConfigValidator {\n constructor({ builtInRules = new Map() } = {}) {\n this.builtInRules = builtInRules;\n }\n\n /**\n * Gets a complete options schema for a rule.\n * @param {{create: Function, schema: (Array|null)}} rule A new-style rule object\n * @returns {Object} JSON Schema for the rule's options.\n */\n getRuleOptionsSchema(rule) {\n if (!rule) {\n return null;\n }\n\n const schema = rule.schema || rule.meta && rule.meta.schema;\n\n // Given a tuple of schemas, insert warning level at the beginning\n if (Array.isArray(schema)) {\n if (schema.length) {\n return {\n type: \"array\",\n items: schema,\n minItems: 0,\n maxItems: schema.length\n };\n }\n return {\n type: \"array\",\n minItems: 0,\n maxItems: 0\n };\n\n }\n\n // Given a full schema, leave it alone\n return schema || null;\n }\n\n /**\n * Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.\n * @param {options} options The given options for the rule.\n * @returns {number|string} The rule's severity value\n */\n validateRuleSeverity(options) {\n const severity = Array.isArray(options) ? options[0] : options;\n const normSeverity = typeof severity === \"string\" ? severityMap[severity.toLowerCase()] : severity;\n\n if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {\n return normSeverity;\n }\n\n throw new Error(`\\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, \"\\\"\").replace(/\\n/gu, \"\")}').\\n`);\n\n }\n\n /**\n * Validates the non-severity options passed to a rule, based on its schema.\n * @param {{create: Function}} rule The rule to validate\n * @param {Array} localOptions The options for the rule, excluding severity\n * @returns {void}\n */\n validateRuleSchema(rule, localOptions) {\n if (!ruleValidators.has(rule)) {\n const schema = this.getRuleOptionsSchema(rule);\n\n if (schema) {\n ruleValidators.set(rule, ajv.compile(schema));\n }\n }\n\n const validateRule = ruleValidators.get(rule);\n\n if (validateRule) {\n validateRule(localOptions);\n if (validateRule.errors) {\n throw new Error(validateRule.errors.map(\n error => `\\tValue ${JSON.stringify(error.data)} ${error.message}.\\n`\n ).join(\"\"));\n }\n }\n }\n\n /**\n * Validates a rule's options against its schema.\n * @param {{create: Function}|null} rule The rule that the config is being validated for\n * @param {string} ruleId The rule's unique name.\n * @param {Array|number} options The given options for the rule.\n * @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,\n * no source is prepended to the message.\n * @returns {void}\n */\n validateRuleOptions(rule, ruleId, options, source = null) {\n try {\n const severity = this.validateRuleSeverity(options);\n\n if (severity !== 0) {\n this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);\n }\n } catch (err) {\n const enhancedMessage = `Configuration for rule \"${ruleId}\" is invalid:\\n${err.message}`;\n\n if (typeof source === \"string\") {\n throw new Error(`${source}:\\n\\t${enhancedMessage}`);\n } else {\n throw new Error(enhancedMessage);\n }\n }\n }\n\n /**\n * Validates an environment object\n * @param {Object} environment The environment config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.\n * @returns {void}\n */\n validateEnvironment(\n environment,\n source,\n getAdditionalEnv = noop\n ) {\n\n // not having an environment is ok\n if (!environment) {\n return;\n }\n\n Object.keys(environment).forEach(id => {\n const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null;\n\n if (!env) {\n const message = `${source}:\\n\\tEnvironment key \"${id}\" is unknown\\n`;\n\n throw new Error(message);\n }\n });\n }\n\n /**\n * Validates a rules config object\n * @param {Object} rulesConfig The rules config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules\n * @returns {void}\n */\n validateRules(\n rulesConfig,\n source,\n getAdditionalRule = noop\n ) {\n if (!rulesConfig) {\n return;\n }\n\n Object.keys(rulesConfig).forEach(id => {\n const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;\n\n this.validateRuleOptions(rule, id, rulesConfig[id], source);\n });\n }\n\n /**\n * Validates a `globals` section of a config file\n * @param {Object} globalsConfig The `globals` section\n * @param {string|null} source The name of the configuration source to report in the event of an error.\n * @returns {void}\n */\n validateGlobals(globalsConfig, source = null) {\n if (!globalsConfig) {\n return;\n }\n\n Object.entries(globalsConfig)\n .forEach(([configuredGlobal, configuredValue]) => {\n try {\n ConfigOps.normalizeConfigGlobal(configuredValue);\n } catch (err) {\n throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\\n${err.message}`);\n }\n });\n }\n\n /**\n * Validate `processor` configuration.\n * @param {string|undefined} processorName The processor name.\n * @param {string} source The name of config file.\n * @param {function(id:string): Processor} getProcessor The getter of defined processors.\n * @returns {void}\n */\n validateProcessor(processorName, source, getProcessor) {\n if (processorName && !getProcessor(processorName)) {\n throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);\n }\n }\n\n /**\n * Formats an array of schema validation errors.\n * @param {Array} errors An array of error messages to format.\n * @returns {string} Formatted error message\n */\n formatErrors(errors) {\n return errors.map(error => {\n if (error.keyword === \"additionalProperties\") {\n const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;\n\n return `Unexpected top-level property \"${formattedPropertyPath}\"`;\n }\n if (error.keyword === \"type\") {\n const formattedField = error.dataPath.slice(1);\n const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join(\"/\") : error.schema;\n const formattedValue = JSON.stringify(error.data);\n\n return `Property \"${formattedField}\" is the wrong type (expected ${formattedExpectedType} but got \\`${formattedValue}\\`)`;\n }\n\n const field = error.dataPath[0] === \".\" ? error.dataPath.slice(1) : error.dataPath;\n\n return `\"${field}\" ${error.message}. Value: ${JSON.stringify(error.data)}`;\n }).map(message => `\\t- ${message}.\\n`).join(\"\");\n }\n\n /**\n * Validates the top level properties of the config object.\n * @param {Object} config The config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @returns {void}\n */\n validateConfigSchema(config, source = null) {\n validateSchema = validateSchema || ajv.compile(configSchema);\n\n if (!validateSchema(config)) {\n throw new Error(`ESLint configuration in ${source} is invalid:\\n${this.formatErrors(validateSchema.errors)}`);\n }\n\n if (Object.hasOwnProperty.call(config, \"ecmaFeatures\")) {\n emitDeprecationWarning(source, \"ESLINT_LEGACY_ECMAFEATURES\");\n }\n }\n\n /**\n * Validates an entire config object.\n * @param {Object} config The config object to validate.\n * @param {string} source The name of the configuration source to report in any errors.\n * @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.\n * @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.\n * @returns {void}\n */\n validate(config, source, getAdditionalRule, getAdditionalEnv) {\n this.validateConfigSchema(config, source);\n this.validateRules(config.rules, source, getAdditionalRule);\n this.validateEnvironment(config.env, source, getAdditionalEnv);\n this.validateGlobals(config.globals, source);\n\n for (const override of config.overrides || []) {\n this.validateRules(override.rules, source, getAdditionalRule);\n this.validateEnvironment(override.env, source, getAdditionalEnv);\n this.validateGlobals(config.globals, source);\n }\n }\n\n /**\n * Validate config array object.\n * @param {ConfigArray} configArray The config array to validate.\n * @returns {void}\n */\n validateConfigArray(configArray) {\n const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);\n const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);\n const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);\n\n // Validate.\n for (const element of configArray) {\n if (validated.has(element)) {\n continue;\n }\n validated.add(element);\n\n this.validateEnvironment(element.env, element.name, getPluginEnv);\n this.validateGlobals(element.globals, element.name);\n this.validateProcessor(element.processor, element.name, getPluginProcessor);\n this.validateRules(element.rules, element.name, getPluginRule);\n }\n }\n\n}\n","/**\n * @fileoverview Common helpers for naming of plugins, formatters and configs\n */\n\nconst NAMESPACE_REGEX = /^@.*\\//iu;\n\n/**\n * Brings package name to correct format based on prefix\n * @param {string} name The name of the package.\n * @param {string} prefix Can be either \"eslint-plugin\", \"eslint-config\" or \"eslint-formatter\"\n * @returns {string} Normalized name of the package\n * @private\n */\nfunction normalizePackageName(name, prefix) {\n let normalizedName = name;\n\n /**\n * On Windows, name can come in with Windows slashes instead of Unix slashes.\n * Normalize to Unix first to avoid errors later on.\n * https://github.com/eslint/eslint/issues/5644\n */\n if (normalizedName.includes(\"\\\\\")) {\n normalizedName = normalizedName.replace(/\\\\/gu, \"/\");\n }\n\n if (normalizedName.charAt(0) === \"@\") {\n\n /**\n * it's a scoped package\n * package name is the prefix, or just a username\n */\n const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, \"u\"),\n scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, \"u\");\n\n if (scopedPackageShortcutRegex.test(normalizedName)) {\n normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);\n } else if (!scopedPackageNameRegex.test(normalizedName.split(\"/\")[1])) {\n\n /**\n * for scoped packages, insert the prefix after the first / unless\n * the path is already @scope/eslint or @scope/eslint-xxx-yyy\n */\n normalizedName = normalizedName.replace(/^@([^/]+)\\/(.*)$/u, `@$1/${prefix}-$2`);\n }\n } else if (!normalizedName.startsWith(`${prefix}-`)) {\n normalizedName = `${prefix}-${normalizedName}`;\n }\n\n return normalizedName;\n}\n\n/**\n * Removes the prefix from a fullname.\n * @param {string} fullname The term which may have the prefix.\n * @param {string} prefix The prefix to remove.\n * @returns {string} The term without prefix.\n */\nfunction getShorthandName(fullname, prefix) {\n if (fullname[0] === \"@\") {\n let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, \"u\").exec(fullname);\n\n if (matchResult) {\n return matchResult[1];\n }\n\n matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, \"u\").exec(fullname);\n if (matchResult) {\n return `${matchResult[1]}/${matchResult[2]}`;\n }\n } else if (fullname.startsWith(`${prefix}-`)) {\n return fullname.slice(prefix.length + 1);\n }\n\n return fullname;\n}\n\n/**\n * Gets the scope (namespace) of a term.\n * @param {string} term The term which may have the namespace.\n * @returns {string} The namespace of the term if it has one.\n */\nfunction getNamespaceFromTerm(term) {\n const match = term.match(NAMESPACE_REGEX);\n\n return match ? match[0] : \"\";\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport {\n normalizePackageName,\n getShorthandName,\n getNamespaceFromTerm\n};\n","/**\n * Utility for resolving a module relative to another module\n * @author Teddy Katz\n */\n\nimport Module from \"module\";\n\n/*\n * `Module.createRequire` is added in v12.2.0. It supports URL as well.\n * We only support the case where the argument is a filepath, not a URL.\n */\nconst createRequire = Module.createRequire;\n\n/**\n * Resolves a Node module relative to another module\n * @param {string} moduleName The name of a Node module, or a path to a Node module.\n * @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be\n * a file rather than a directory, but the file need not actually exist.\n * @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`\n */\nfunction resolve(moduleName, relativeToPath) {\n try {\n return createRequire(relativeToPath).resolve(moduleName);\n } catch (error) {\n\n // This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.\n if (\n typeof error === \"object\" &&\n error !== null &&\n error.code === \"MODULE_NOT_FOUND\" &&\n !error.requireStack &&\n error.message.includes(moduleName)\n ) {\n error.message += `\\nRequire stack:\\n- ${relativeToPath}`;\n }\n throw error;\n }\n}\n\nexport {\n resolve\n};\n","/**\n * @fileoverview The factory of `ConfigArray` objects.\n *\n * This class provides methods to create `ConfigArray` instance.\n *\n * - `create(configData, options)`\n * Create a `ConfigArray` instance from a config data. This is to handle CLI\n * options except `--config`.\n * - `loadFile(filePath, options)`\n * Create a `ConfigArray` instance from a config file. This is to handle\n * `--config` option. If the file was not found, throws the following error:\n * - If the filename was `*.js`, a `MODULE_NOT_FOUND` error.\n * - If the filename was `package.json`, an IO error or an\n * `ESLINT_CONFIG_FIELD_NOT_FOUND` error.\n * - Otherwise, an IO error such as `ENOENT`.\n * - `loadInDirectory(directoryPath, options)`\n * Create a `ConfigArray` instance from a config file which is on a given\n * directory. This tries to load `.eslintrc.*` or `package.json`. If not\n * found, returns an empty `ConfigArray`.\n * - `loadESLintIgnore(filePath)`\n * Create a `ConfigArray` instance from a config file that is `.eslintignore`\n * format. This is to handle `--ignore-path` option.\n * - `loadDefaultESLintIgnore()`\n * Create a `ConfigArray` instance from `.eslintignore` or `package.json` in\n * the current working directory.\n *\n * `ConfigArrayFactory` class has the responsibility that loads configuration\n * files, including loading `extends`, `parser`, and `plugins`. The created\n * `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`.\n *\n * But this class doesn't handle cascading. `CascadingConfigArrayFactory` class\n * handles cascading and hierarchy.\n *\n * @author Toru Nagashima \n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport debugOrig from \"debug\";\nimport fs from \"fs\";\nimport importFresh from \"import-fresh\";\nimport { createRequire } from \"module\";\nimport path from \"path\";\nimport stripComments from \"strip-json-comments\";\n\nimport {\n ConfigArray,\n ConfigDependency,\n IgnorePattern,\n OverrideTester\n} from \"./config-array/index.js\";\nimport ConfigValidator from \"./shared/config-validator.js\";\nimport * as naming from \"./shared/naming.js\";\nimport * as ModuleResolver from \"./shared/relative-module-resolver.js\";\n\nconst require = createRequire(import.meta.url);\n\nconst debug = debugOrig(\"eslintrc:config-array-factory\");\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\nconst configFilenames = [\n \".eslintrc.js\",\n \".eslintrc.cjs\",\n \".eslintrc.yaml\",\n \".eslintrc.yml\",\n \".eslintrc.json\",\n \".eslintrc\",\n \"package.json\"\n];\n\n// Define types for VSCode IntelliSense.\n/** @typedef {import(\"./shared/types\").ConfigData} ConfigData */\n/** @typedef {import(\"./shared/types\").OverrideConfigData} OverrideConfigData */\n/** @typedef {import(\"./shared/types\").Parser} Parser */\n/** @typedef {import(\"./shared/types\").Plugin} Plugin */\n/** @typedef {import(\"./shared/types\").Rule} Rule */\n/** @typedef {import(\"./config-array/config-dependency\").DependentParser} DependentParser */\n/** @typedef {import(\"./config-array/config-dependency\").DependentPlugin} DependentPlugin */\n/** @typedef {ConfigArray[0]} ConfigArrayElement */\n\n/**\n * @typedef {Object} ConfigArrayFactoryOptions\n * @property {Map} [additionalPluginPool] The map for additional plugins.\n * @property {string} [cwd] The path to the current working directory.\n * @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`.\n * @property {Map} builtInRules The rules that are built in to ESLint.\n * @property {Object} [resolver=ModuleResolver] The module resolver object.\n * @property {string} eslintAllPath The path to the definitions for eslint:all.\n * @property {Function} getEslintAllConfig Returns the config data for eslint:all.\n * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.\n * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.\n */\n\n/**\n * @typedef {Object} ConfigArrayFactoryInternalSlots\n * @property {Map} additionalPluginPool The map for additional plugins.\n * @property {string} cwd The path to the current working directory.\n * @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from.\n * @property {Map} builtInRules The rules that are built in to ESLint.\n * @property {Object} [resolver=ModuleResolver] The module resolver object.\n * @property {string} eslintAllPath The path to the definitions for eslint:all.\n * @property {Function} getEslintAllConfig Returns the config data for eslint:all.\n * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.\n * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.\n */\n\n/**\n * @typedef {Object} ConfigArrayFactoryLoadingContext\n * @property {string} filePath The path to the current configuration.\n * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.\n * @property {string} name The name of the current configuration.\n * @property {string} pluginBasePath The base path to resolve plugins.\n * @property {\"config\" | \"ignore\" | \"implicit-processor\"} type The type of the current configuration. This is `\"config\"` in normal. This is `\"ignore\"` if it came from `.eslintignore`. This is `\"implicit-processor\"` if it came from legacy file-extension processors.\n */\n\n/**\n * @typedef {Object} ConfigArrayFactoryLoadingContext\n * @property {string} filePath The path to the current configuration.\n * @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.\n * @property {string} name The name of the current configuration.\n * @property {\"config\" | \"ignore\" | \"implicit-processor\"} type The type of the current configuration. This is `\"config\"` in normal. This is `\"ignore\"` if it came from `.eslintignore`. This is `\"implicit-processor\"` if it came from legacy file-extension processors.\n */\n\n/** @type {WeakMap} */\nconst internalSlotsMap = new WeakMap();\n\n/** @type {WeakMap} */\nconst normalizedPlugins = new WeakMap();\n\n/**\n * Check if a given string is a file path.\n * @param {string} nameOrPath A module name or file path.\n * @returns {boolean} `true` if the `nameOrPath` is a file path.\n */\nfunction isFilePath(nameOrPath) {\n return (\n /^\\.{1,2}[/\\\\]/u.test(nameOrPath) ||\n path.isAbsolute(nameOrPath)\n );\n}\n\n/**\n * Convenience wrapper for synchronously reading file contents.\n * @param {string} filePath The filename to read.\n * @returns {string} The file contents, with the BOM removed.\n * @private\n */\nfunction readFile(filePath) {\n return fs.readFileSync(filePath, \"utf8\").replace(/^\\ufeff/u, \"\");\n}\n\n/**\n * Loads a YAML configuration from a file.\n * @param {string} filePath The filename to load.\n * @returns {ConfigData} The configuration object from the file.\n * @throws {Error} If the file cannot be read.\n * @private\n */\nfunction loadYAMLConfigFile(filePath) {\n debug(`Loading YAML config file: ${filePath}`);\n\n // lazy load YAML to improve performance when not used\n const yaml = require(\"js-yaml\");\n\n try {\n\n // empty YAML file can be null, so always use\n return yaml.load(readFile(filePath)) || {};\n } catch (e) {\n debug(`Error reading YAML file: ${filePath}`);\n e.message = `Cannot read config file: ${filePath}\\nError: ${e.message}`;\n throw e;\n }\n}\n\n/**\n * Loads a JSON configuration from a file.\n * @param {string} filePath The filename to load.\n * @returns {ConfigData} The configuration object from the file.\n * @throws {Error} If the file cannot be read.\n * @private\n */\nfunction loadJSONConfigFile(filePath) {\n debug(`Loading JSON config file: ${filePath}`);\n\n try {\n return JSON.parse(stripComments(readFile(filePath)));\n } catch (e) {\n debug(`Error reading JSON file: ${filePath}`);\n e.message = `Cannot read config file: ${filePath}\\nError: ${e.message}`;\n e.messageTemplate = \"failed-to-read-json\";\n e.messageData = {\n path: filePath,\n message: e.message\n };\n throw e;\n }\n}\n\n/**\n * Loads a legacy (.eslintrc) configuration from a file.\n * @param {string} filePath The filename to load.\n * @returns {ConfigData} The configuration object from the file.\n * @throws {Error} If the file cannot be read.\n * @private\n */\nfunction loadLegacyConfigFile(filePath) {\n debug(`Loading legacy config file: ${filePath}`);\n\n // lazy load YAML to improve performance when not used\n const yaml = require(\"js-yaml\");\n\n try {\n return yaml.load(stripComments(readFile(filePath))) || /* istanbul ignore next */ {};\n } catch (e) {\n debug(\"Error reading YAML file: %s\\n%o\", filePath, e);\n e.message = `Cannot read config file: ${filePath}\\nError: ${e.message}`;\n throw e;\n }\n}\n\n/**\n * Loads a JavaScript configuration from a file.\n * @param {string} filePath The filename to load.\n * @returns {ConfigData} The configuration object from the file.\n * @throws {Error} If the file cannot be read.\n * @private\n */\nfunction loadJSConfigFile(filePath) {\n debug(`Loading JS config file: ${filePath}`);\n try {\n return importFresh(filePath);\n } catch (e) {\n debug(`Error reading JavaScript file: ${filePath}`);\n e.message = `Cannot read config file: ${filePath}\\nError: ${e.message}`;\n throw e;\n }\n}\n\n/**\n * Loads a configuration from a package.json file.\n * @param {string} filePath The filename to load.\n * @returns {ConfigData} The configuration object from the file.\n * @throws {Error} If the file cannot be read.\n * @private\n */\nfunction loadPackageJSONConfigFile(filePath) {\n debug(`Loading package.json config file: ${filePath}`);\n try {\n const packageData = loadJSONConfigFile(filePath);\n\n if (!Object.hasOwnProperty.call(packageData, \"eslintConfig\")) {\n throw Object.assign(\n new Error(\"package.json file doesn't have 'eslintConfig' field.\"),\n { code: \"ESLINT_CONFIG_FIELD_NOT_FOUND\" }\n );\n }\n\n return packageData.eslintConfig;\n } catch (e) {\n debug(`Error reading package.json file: ${filePath}`);\n e.message = `Cannot read config file: ${filePath}\\nError: ${e.message}`;\n throw e;\n }\n}\n\n/**\n * Loads a `.eslintignore` from a file.\n * @param {string} filePath The filename to load.\n * @returns {string[]} The ignore patterns from the file.\n * @private\n */\nfunction loadESLintIgnoreFile(filePath) {\n debug(`Loading .eslintignore file: ${filePath}`);\n\n try {\n return readFile(filePath)\n .split(/\\r?\\n/gu)\n .filter(line => line.trim() !== \"\" && !line.startsWith(\"#\"));\n } catch (e) {\n debug(`Error reading .eslintignore file: ${filePath}`);\n e.message = `Cannot read .eslintignore file: ${filePath}\\nError: ${e.message}`;\n throw e;\n }\n}\n\n/**\n * Creates an error to notify about a missing config to extend from.\n * @param {string} configName The name of the missing config.\n * @param {string} importerName The name of the config that imported the missing config\n * @param {string} messageTemplate The text template to source error strings from.\n * @returns {Error} The error object to throw\n * @private\n */\nfunction configInvalidError(configName, importerName, messageTemplate) {\n return Object.assign(\n new Error(`Failed to load config \"${configName}\" to extend from.`),\n {\n messageTemplate,\n messageData: { configName, importerName }\n }\n );\n}\n\n/**\n * Loads a configuration file regardless of the source. Inspects the file path\n * to determine the correctly way to load the config file.\n * @param {string} filePath The path to the configuration.\n * @returns {ConfigData|null} The configuration information.\n * @private\n */\nfunction loadConfigFile(filePath) {\n switch (path.extname(filePath)) {\n case \".js\":\n case \".cjs\":\n return loadJSConfigFile(filePath);\n\n case \".json\":\n if (path.basename(filePath) === \"package.json\") {\n return loadPackageJSONConfigFile(filePath);\n }\n return loadJSONConfigFile(filePath);\n\n case \".yaml\":\n case \".yml\":\n return loadYAMLConfigFile(filePath);\n\n default:\n return loadLegacyConfigFile(filePath);\n }\n}\n\n/**\n * Write debug log.\n * @param {string} request The requested module name.\n * @param {string} relativeTo The file path to resolve the request relative to.\n * @param {string} filePath The resolved file path.\n * @returns {void}\n */\nfunction writeDebugLogForLoading(request, relativeTo, filePath) {\n /* istanbul ignore next */\n if (debug.enabled) {\n let nameAndVersion = null;\n\n try {\n const packageJsonPath = ModuleResolver.resolve(\n `${request}/package.json`,\n relativeTo\n );\n const { version = \"unknown\" } = require(packageJsonPath);\n\n nameAndVersion = `${request}@${version}`;\n } catch (error) {\n debug(\"package.json was not found:\", error.message);\n nameAndVersion = request;\n }\n\n debug(\"Loaded: %s (%s)\", nameAndVersion, filePath);\n }\n}\n\n/**\n * Create a new context with default values.\n * @param {ConfigArrayFactoryInternalSlots} slots The internal slots.\n * @param {\"config\" | \"ignore\" | \"implicit-processor\" | undefined} providedType The type of the current configuration. Default is `\"config\"`.\n * @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`.\n * @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string.\n * @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`.\n * @returns {ConfigArrayFactoryLoadingContext} The created context.\n */\nfunction createContext(\n { cwd, resolvePluginsRelativeTo },\n providedType,\n providedName,\n providedFilePath,\n providedMatchBasePath\n) {\n const filePath = providedFilePath\n ? path.resolve(cwd, providedFilePath)\n : \"\";\n const matchBasePath =\n (providedMatchBasePath && path.resolve(cwd, providedMatchBasePath)) ||\n (filePath && path.dirname(filePath)) ||\n cwd;\n const name =\n providedName ||\n (filePath && path.relative(cwd, filePath)) ||\n \"\";\n const pluginBasePath =\n resolvePluginsRelativeTo ||\n (filePath && path.dirname(filePath)) ||\n cwd;\n const type = providedType || \"config\";\n\n return { filePath, matchBasePath, name, pluginBasePath, type };\n}\n\n/**\n * Normalize a given plugin.\n * - Ensure the object to have four properties: configs, environments, processors, and rules.\n * - Ensure the object to not have other properties.\n * @param {Plugin} plugin The plugin to normalize.\n * @returns {Plugin} The normalized plugin.\n */\nfunction normalizePlugin(plugin) {\n\n // first check the cache\n let normalizedPlugin = normalizedPlugins.get(plugin);\n\n if (normalizedPlugin) {\n return normalizedPlugin;\n }\n\n normalizedPlugin = {\n configs: plugin.configs || {},\n environments: plugin.environments || {},\n processors: plugin.processors || {},\n rules: plugin.rules || {}\n };\n\n // save the reference for later\n normalizedPlugins.set(plugin, normalizedPlugin);\n\n return normalizedPlugin;\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\n/**\n * The factory of `ConfigArray` objects.\n */\nclass ConfigArrayFactory {\n\n /**\n * Initialize this instance.\n * @param {ConfigArrayFactoryOptions} [options] The map for additional plugins.\n */\n constructor({\n additionalPluginPool = new Map(),\n cwd = process.cwd(),\n resolvePluginsRelativeTo,\n builtInRules,\n resolver = ModuleResolver,\n eslintAllPath,\n getEslintAllConfig,\n eslintRecommendedPath,\n getEslintRecommendedConfig\n } = {}) {\n internalSlotsMap.set(this, {\n additionalPluginPool,\n cwd,\n resolvePluginsRelativeTo:\n resolvePluginsRelativeTo &&\n path.resolve(cwd, resolvePluginsRelativeTo),\n builtInRules,\n resolver,\n eslintAllPath,\n getEslintAllConfig,\n eslintRecommendedPath,\n getEslintRecommendedConfig\n });\n }\n\n /**\n * Create `ConfigArray` instance from a config data.\n * @param {ConfigData|null} configData The config data to create.\n * @param {Object} [options] The options.\n * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.\n * @param {string} [options.filePath] The path to this config data.\n * @param {string} [options.name] The config name.\n * @returns {ConfigArray} Loaded config.\n */\n create(configData, { basePath, filePath, name } = {}) {\n if (!configData) {\n return new ConfigArray();\n }\n\n const slots = internalSlotsMap.get(this);\n const ctx = createContext(slots, \"config\", name, filePath, basePath);\n const elements = this._normalizeConfigData(configData, ctx);\n\n return new ConfigArray(...elements);\n }\n\n /**\n * Load a config file.\n * @param {string} filePath The path to a config file.\n * @param {Object} [options] The options.\n * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.\n * @param {string} [options.name] The config name.\n * @returns {ConfigArray} Loaded config.\n */\n loadFile(filePath, { basePath, name } = {}) {\n const slots = internalSlotsMap.get(this);\n const ctx = createContext(slots, \"config\", name, filePath, basePath);\n\n return new ConfigArray(...this._loadConfigData(ctx));\n }\n\n /**\n * Load the config file on a given directory if exists.\n * @param {string} directoryPath The path to a directory.\n * @param {Object} [options] The options.\n * @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.\n * @param {string} [options.name] The config name.\n * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.\n */\n loadInDirectory(directoryPath, { basePath, name } = {}) {\n const slots = internalSlotsMap.get(this);\n\n for (const filename of configFilenames) {\n const ctx = createContext(\n slots,\n \"config\",\n name,\n path.join(directoryPath, filename),\n basePath\n );\n\n if (fs.existsSync(ctx.filePath) && fs.statSync(ctx.filePath).isFile()) {\n let configData;\n\n try {\n configData = loadConfigFile(ctx.filePath);\n } catch (error) {\n if (!error || error.code !== \"ESLINT_CONFIG_FIELD_NOT_FOUND\") {\n throw error;\n }\n }\n\n if (configData) {\n debug(`Config file found: ${ctx.filePath}`);\n return new ConfigArray(\n ...this._normalizeConfigData(configData, ctx)\n );\n }\n }\n }\n\n debug(`Config file not found on ${directoryPath}`);\n return new ConfigArray();\n }\n\n /**\n * Check if a config file on a given directory exists or not.\n * @param {string} directoryPath The path to a directory.\n * @returns {string | null} The path to the found config file. If not found then null.\n */\n static getPathToConfigFileInDirectory(directoryPath) {\n for (const filename of configFilenames) {\n const filePath = path.join(directoryPath, filename);\n\n if (fs.existsSync(filePath)) {\n if (filename === \"package.json\") {\n try {\n loadPackageJSONConfigFile(filePath);\n return filePath;\n } catch { /* ignore */ }\n } else {\n return filePath;\n }\n }\n }\n return null;\n }\n\n /**\n * Load `.eslintignore` file.\n * @param {string} filePath The path to a `.eslintignore` file to load.\n * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.\n */\n loadESLintIgnore(filePath) {\n const slots = internalSlotsMap.get(this);\n const ctx = createContext(\n slots,\n \"ignore\",\n void 0,\n filePath,\n slots.cwd\n );\n const ignorePatterns = loadESLintIgnoreFile(ctx.filePath);\n\n return new ConfigArray(\n ...this._normalizeESLintIgnoreData(ignorePatterns, ctx)\n );\n }\n\n /**\n * Load `.eslintignore` file in the current working directory.\n * @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.\n */\n loadDefaultESLintIgnore() {\n const slots = internalSlotsMap.get(this);\n const eslintIgnorePath = path.resolve(slots.cwd, \".eslintignore\");\n const packageJsonPath = path.resolve(slots.cwd, \"package.json\");\n\n if (fs.existsSync(eslintIgnorePath)) {\n return this.loadESLintIgnore(eslintIgnorePath);\n }\n if (fs.existsSync(packageJsonPath)) {\n const data = loadJSONConfigFile(packageJsonPath);\n\n if (Object.hasOwnProperty.call(data, \"eslintIgnore\")) {\n if (!Array.isArray(data.eslintIgnore)) {\n throw new Error(\"Package.json eslintIgnore property requires an array of paths\");\n }\n const ctx = createContext(\n slots,\n \"ignore\",\n \"eslintIgnore in package.json\",\n packageJsonPath,\n slots.cwd\n );\n\n return new ConfigArray(\n ...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx)\n );\n }\n }\n\n return new ConfigArray();\n }\n\n /**\n * Load a given config file.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} Loaded config.\n * @private\n */\n _loadConfigData(ctx) {\n return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx);\n }\n\n /**\n * Normalize a given `.eslintignore` data to config array elements.\n * @param {string[]} ignorePatterns The patterns to ignore files.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @private\n */\n *_normalizeESLintIgnoreData(ignorePatterns, ctx) {\n const elements = this._normalizeObjectConfigData(\n { ignorePatterns },\n ctx\n );\n\n // Set `ignorePattern.loose` flag for backward compatibility.\n for (const element of elements) {\n if (element.ignorePattern) {\n element.ignorePattern.loose = true;\n }\n yield element;\n }\n }\n\n /**\n * Normalize a given config to an array.\n * @param {ConfigData} configData The config data to normalize.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @private\n */\n _normalizeConfigData(configData, ctx) {\n const validator = new ConfigValidator();\n\n validator.validateConfigSchema(configData, ctx.name || ctx.filePath);\n return this._normalizeObjectConfigData(configData, ctx);\n }\n\n /**\n * Normalize a given config to an array.\n * @param {ConfigData|OverrideConfigData} configData The config data to normalize.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @private\n */\n *_normalizeObjectConfigData(configData, ctx) {\n const { files, excludedFiles, ...configBody } = configData;\n const criteria = OverrideTester.create(\n files,\n excludedFiles,\n ctx.matchBasePath\n );\n const elements = this._normalizeObjectConfigDataBody(configBody, ctx);\n\n // Apply the criteria to every element.\n for (const element of elements) {\n\n /*\n * Merge the criteria.\n * This is for the `overrides` entries that came from the\n * configurations of `overrides[].extends`.\n */\n element.criteria = OverrideTester.and(criteria, element.criteria);\n\n /*\n * Remove `root` property to ignore `root` settings which came from\n * `extends` in `overrides`.\n */\n if (element.criteria) {\n element.root = void 0;\n }\n\n yield element;\n }\n }\n\n /**\n * Normalize a given config to an array.\n * @param {ConfigData} configData The config data to normalize.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @private\n */\n *_normalizeObjectConfigDataBody(\n {\n env,\n extends: extend,\n globals,\n ignorePatterns,\n noInlineConfig,\n parser: parserName,\n parserOptions,\n plugins: pluginList,\n processor,\n reportUnusedDisableDirectives,\n root,\n rules,\n settings,\n overrides: overrideList = []\n },\n ctx\n ) {\n const extendList = Array.isArray(extend) ? extend : [extend];\n const ignorePattern = ignorePatterns && new IgnorePattern(\n Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns],\n ctx.matchBasePath\n );\n\n // Flatten `extends`.\n for (const extendName of extendList.filter(Boolean)) {\n yield* this._loadExtends(extendName, ctx);\n }\n\n // Load parser & plugins.\n const parser = parserName && this._loadParser(parserName, ctx);\n const plugins = pluginList && this._loadPlugins(pluginList, ctx);\n\n // Yield pseudo config data for file extension processors.\n if (plugins) {\n yield* this._takeFileExtensionProcessors(plugins, ctx);\n }\n\n // Yield the config data except `extends` and `overrides`.\n yield {\n\n // Debug information.\n type: ctx.type,\n name: ctx.name,\n filePath: ctx.filePath,\n\n // Config data.\n criteria: null,\n env,\n globals,\n ignorePattern,\n noInlineConfig,\n parser,\n parserOptions,\n plugins,\n processor,\n reportUnusedDisableDirectives,\n root,\n rules,\n settings\n };\n\n // Flatten `overries`.\n for (let i = 0; i < overrideList.length; ++i) {\n yield* this._normalizeObjectConfigData(\n overrideList[i],\n { ...ctx, name: `${ctx.name}#overrides[${i}]` }\n );\n }\n }\n\n /**\n * Load configs of an element in `extends`.\n * @param {string} extendName The name of a base config.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @private\n */\n _loadExtends(extendName, ctx) {\n debug(\"Loading {extends:%j} relative to %s\", extendName, ctx.filePath);\n try {\n if (extendName.startsWith(\"eslint:\")) {\n return this._loadExtendedBuiltInConfig(extendName, ctx);\n }\n if (extendName.startsWith(\"plugin:\")) {\n return this._loadExtendedPluginConfig(extendName, ctx);\n }\n return this._loadExtendedShareableConfig(extendName, ctx);\n } catch (error) {\n error.message += `\\nReferenced from: ${ctx.filePath || ctx.name}`;\n throw error;\n }\n }\n\n /**\n * Load configs of an element in `extends`.\n * @param {string} extendName The name of a base config.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @private\n */\n _loadExtendedBuiltInConfig(extendName, ctx) {\n const {\n eslintAllPath,\n getEslintAllConfig,\n eslintRecommendedPath,\n getEslintRecommendedConfig\n } = internalSlotsMap.get(this);\n\n if (extendName === \"eslint:recommended\") {\n const name = `${ctx.name} » ${extendName}`;\n\n if (getEslintRecommendedConfig) {\n if (typeof getEslintRecommendedConfig !== \"function\") {\n throw new Error(`getEslintRecommendedConfig must be a function instead of '${getEslintRecommendedConfig}'`);\n }\n return this._normalizeConfigData(getEslintRecommendedConfig(), { ...ctx, name, filePath: \"\" });\n }\n return this._loadConfigData({\n ...ctx,\n name,\n filePath: eslintRecommendedPath\n });\n }\n if (extendName === \"eslint:all\") {\n const name = `${ctx.name} » ${extendName}`;\n\n if (getEslintAllConfig) {\n if (typeof getEslintAllConfig !== \"function\") {\n throw new Error(`getEslintAllConfig must be a function instead of '${getEslintAllConfig}'`);\n }\n return this._normalizeConfigData(getEslintAllConfig(), { ...ctx, name, filePath: \"\" });\n }\n return this._loadConfigData({\n ...ctx,\n name,\n filePath: eslintAllPath\n });\n }\n\n throw configInvalidError(extendName, ctx.name, \"extend-config-missing\");\n }\n\n /**\n * Load configs of an element in `extends`.\n * @param {string} extendName The name of a base config.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @private\n */\n _loadExtendedPluginConfig(extendName, ctx) {\n const slashIndex = extendName.lastIndexOf(\"/\");\n\n if (slashIndex === -1) {\n throw configInvalidError(extendName, ctx.filePath, \"plugin-invalid\");\n }\n\n const pluginName = extendName.slice(\"plugin:\".length, slashIndex);\n const configName = extendName.slice(slashIndex + 1);\n\n if (isFilePath(pluginName)) {\n throw new Error(\"'extends' cannot use a file path for plugins.\");\n }\n\n const plugin = this._loadPlugin(pluginName, ctx);\n const configData =\n plugin.definition &&\n plugin.definition.configs[configName];\n\n if (configData) {\n return this._normalizeConfigData(configData, {\n ...ctx,\n filePath: plugin.filePath || ctx.filePath,\n name: `${ctx.name} » plugin:${plugin.id}/${configName}`\n });\n }\n\n throw plugin.error || configInvalidError(extendName, ctx.filePath, \"extend-config-missing\");\n }\n\n /**\n * Load configs of an element in `extends`.\n * @param {string} extendName The name of a base config.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The normalized config.\n * @private\n */\n _loadExtendedShareableConfig(extendName, ctx) {\n const { cwd, resolver } = internalSlotsMap.get(this);\n const relativeTo = ctx.filePath || path.join(cwd, \"__placeholder__.js\");\n let request;\n\n if (isFilePath(extendName)) {\n request = extendName;\n } else if (extendName.startsWith(\".\")) {\n request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior.\n } else {\n request = naming.normalizePackageName(\n extendName,\n \"eslint-config\"\n );\n }\n\n let filePath;\n\n try {\n filePath = resolver.resolve(request, relativeTo);\n } catch (error) {\n /* istanbul ignore else */\n if (error && error.code === \"MODULE_NOT_FOUND\") {\n throw configInvalidError(extendName, ctx.filePath, \"extend-config-missing\");\n }\n throw error;\n }\n\n writeDebugLogForLoading(request, relativeTo, filePath);\n return this._loadConfigData({\n ...ctx,\n filePath,\n name: `${ctx.name} » ${request}`\n });\n }\n\n /**\n * Load given plugins.\n * @param {string[]} names The plugin names to load.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {Record} The loaded parser.\n * @private\n */\n _loadPlugins(names, ctx) {\n return names.reduce((map, name) => {\n if (isFilePath(name)) {\n throw new Error(\"Plugins array cannot includes file paths.\");\n }\n const plugin = this._loadPlugin(name, ctx);\n\n map[plugin.id] = plugin;\n\n return map;\n }, {});\n }\n\n /**\n * Load a given parser.\n * @param {string} nameOrPath The package name or the path to a parser file.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {DependentParser} The loaded parser.\n */\n _loadParser(nameOrPath, ctx) {\n debug(\"Loading parser %j from %s\", nameOrPath, ctx.filePath);\n\n const { cwd, resolver } = internalSlotsMap.get(this);\n const relativeTo = ctx.filePath || path.join(cwd, \"__placeholder__.js\");\n\n try {\n const filePath = resolver.resolve(nameOrPath, relativeTo);\n\n writeDebugLogForLoading(nameOrPath, relativeTo, filePath);\n\n return new ConfigDependency({\n definition: require(filePath),\n filePath,\n id: nameOrPath,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n } catch (error) {\n\n // If the parser name is \"espree\", load the espree of ESLint.\n if (nameOrPath === \"espree\") {\n debug(\"Fallback espree.\");\n return new ConfigDependency({\n definition: require(\"espree\"),\n filePath: require.resolve(\"espree\"),\n id: nameOrPath,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n }\n\n debug(\"Failed to load parser '%s' declared in '%s'.\", nameOrPath, ctx.name);\n error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`;\n\n return new ConfigDependency({\n error,\n id: nameOrPath,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n }\n }\n\n /**\n * Load a given plugin.\n * @param {string} name The plugin name to load.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {DependentPlugin} The loaded plugin.\n * @private\n */\n _loadPlugin(name, ctx) {\n debug(\"Loading plugin %j from %s\", name, ctx.filePath);\n\n const { additionalPluginPool, resolver } = internalSlotsMap.get(this);\n const request = naming.normalizePackageName(name, \"eslint-plugin\");\n const id = naming.getShorthandName(request, \"eslint-plugin\");\n const relativeTo = path.join(ctx.pluginBasePath, \"__placeholder__.js\");\n\n if (name.match(/\\s+/u)) {\n const error = Object.assign(\n new Error(`Whitespace found in plugin name '${name}'`),\n {\n messageTemplate: \"whitespace-found\",\n messageData: { pluginName: request }\n }\n );\n\n return new ConfigDependency({\n error,\n id,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n }\n\n // Check for additional pool.\n const plugin =\n additionalPluginPool.get(request) ||\n additionalPluginPool.get(id);\n\n if (plugin) {\n return new ConfigDependency({\n definition: normalizePlugin(plugin),\n original: plugin,\n filePath: \"\", // It's unknown where the plugin came from.\n id,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n }\n\n let filePath;\n let error;\n\n try {\n filePath = resolver.resolve(request, relativeTo);\n } catch (resolveError) {\n error = resolveError;\n /* istanbul ignore else */\n if (error && error.code === \"MODULE_NOT_FOUND\") {\n error.messageTemplate = \"plugin-missing\";\n error.messageData = {\n pluginName: request,\n resolvePluginsRelativeTo: ctx.pluginBasePath,\n importerName: ctx.name\n };\n }\n }\n\n if (filePath) {\n try {\n writeDebugLogForLoading(request, relativeTo, filePath);\n\n const startTime = Date.now();\n const pluginDefinition = require(filePath);\n\n debug(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`);\n\n return new ConfigDependency({\n definition: normalizePlugin(pluginDefinition),\n original: pluginDefinition,\n filePath,\n id,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n } catch (loadError) {\n error = loadError;\n }\n }\n\n debug(\"Failed to load plugin '%s' declared in '%s'.\", name, ctx.name);\n error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`;\n return new ConfigDependency({\n error,\n id,\n importerName: ctx.name,\n importerPath: ctx.filePath\n });\n }\n\n /**\n * Take file expression processors as config array elements.\n * @param {Record} plugins The plugin definitions.\n * @param {ConfigArrayFactoryLoadingContext} ctx The loading context.\n * @returns {IterableIterator} The config array elements of file expression processors.\n * @private\n */\n *_takeFileExtensionProcessors(plugins, ctx) {\n for (const pluginId of Object.keys(plugins)) {\n const processors =\n plugins[pluginId] &&\n plugins[pluginId].definition &&\n plugins[pluginId].definition.processors;\n\n if (!processors) {\n continue;\n }\n\n for (const processorId of Object.keys(processors)) {\n if (processorId.startsWith(\".\")) {\n yield* this._normalizeObjectConfigData(\n {\n files: [`*${processorId}`],\n processor: `${pluginId}/${processorId}`\n },\n {\n ...ctx,\n type: \"implicit-processor\",\n name: `${ctx.name}#processors[\"${pluginId}/${processorId}\"]`\n }\n );\n }\n }\n }\n }\n}\n\nexport { ConfigArrayFactory, createContext };\n","/**\n * @fileoverview `CascadingConfigArrayFactory` class.\n *\n * `CascadingConfigArrayFactory` class has a responsibility:\n *\n * 1. Handles cascading of config files.\n *\n * It provides two methods:\n *\n * - `getConfigArrayForFile(filePath)`\n * Get the corresponded configuration of a given file. This method doesn't\n * throw even if the given file didn't exist.\n * - `clearCache()`\n * Clear the internal cache. You have to call this method when\n * `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends\n * on the additional plugins. (`CLIEngine#addPlugin()` method calls this.)\n *\n * @author Toru Nagashima \n */\n\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport debugOrig from \"debug\";\nimport os from \"os\";\nimport path from \"path\";\n\nimport { ConfigArrayFactory } from \"./config-array-factory.js\";\nimport {\n ConfigArray,\n ConfigDependency,\n IgnorePattern\n} from \"./config-array/index.js\";\nimport ConfigValidator from \"./shared/config-validator.js\";\nimport { emitDeprecationWarning } from \"./shared/deprecation-warnings.js\";\n\nconst debug = debugOrig(\"eslintrc:cascading-config-array-factory\");\n\n//------------------------------------------------------------------------------\n// Helpers\n//------------------------------------------------------------------------------\n\n// Define types for VSCode IntelliSense.\n/** @typedef {import(\"./shared/types\").ConfigData} ConfigData */\n/** @typedef {import(\"./shared/types\").Parser} Parser */\n/** @typedef {import(\"./shared/types\").Plugin} Plugin */\n/** @typedef {import(\"./shared/types\").Rule} Rule */\n/** @typedef {ReturnType} ConfigArray */\n\n/**\n * @typedef {Object} CascadingConfigArrayFactoryOptions\n * @property {Map} [additionalPluginPool] The map for additional plugins.\n * @property {ConfigData} [baseConfig] The config by `baseConfig` option.\n * @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files.\n * @property {string} [cwd] The base directory to start lookup.\n * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.\n * @property {string[]} [rulePaths] The value of `--rulesdir` option.\n * @property {string} [specificConfigPath] The value of `--config` option.\n * @property {boolean} [useEslintrc] if `false` then it doesn't load config files.\n * @property {Function} loadRules The function to use to load rules.\n * @property {Map} builtInRules The rules that are built in to ESLint.\n * @property {Object} [resolver=ModuleResolver] The module resolver object.\n * @property {string} eslintAllPath The path to the definitions for eslint:all.\n * @property {Function} getEslintAllConfig Returns the config data for eslint:all.\n * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.\n * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.\n */\n\n/**\n * @typedef {Object} CascadingConfigArrayFactoryInternalSlots\n * @property {ConfigArray} baseConfigArray The config array of `baseConfig` option.\n * @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`.\n * @property {ConfigArray} cliConfigArray The config array of CLI options.\n * @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`.\n * @property {ConfigArrayFactory} configArrayFactory The factory for config arrays.\n * @property {Map} configCache The cache from directory paths to config arrays.\n * @property {string} cwd The base directory to start lookup.\n * @property {WeakMap} finalizeCache The cache from config arrays to finalized config arrays.\n * @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.\n * @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`.\n * @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`.\n * @property {boolean} useEslintrc if `false` then it doesn't load config files.\n * @property {Function} loadRules The function to use to load rules.\n * @property {Map} builtInRules The rules that are built in to ESLint.\n * @property {Object} [resolver=ModuleResolver] The module resolver object.\n * @property {string} eslintAllPath The path to the definitions for eslint:all.\n * @property {Function} getEslintAllConfig Returns the config data for eslint:all.\n * @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.\n * @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.\n */\n\n/** @type {WeakMap} */\nconst internalSlotsMap = new WeakMap();\n\n/**\n * Create the config array from `baseConfig` and `rulePaths`.\n * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.\n * @returns {ConfigArray} The config array of the base configs.\n */\nfunction createBaseConfigArray({\n configArrayFactory,\n baseConfigData,\n rulePaths,\n cwd,\n loadRules\n}) {\n const baseConfigArray = configArrayFactory.create(\n baseConfigData,\n { name: \"BaseConfig\" }\n );\n\n /*\n * Create the config array element for the default ignore patterns.\n * This element has `ignorePattern` property that ignores the default\n * patterns in the current working directory.\n */\n baseConfigArray.unshift(configArrayFactory.create(\n { ignorePatterns: IgnorePattern.DefaultPatterns },\n { name: \"DefaultIgnorePattern\" }\n )[0]);\n\n /*\n * Load rules `--rulesdir` option as a pseudo plugin.\n * Use a pseudo plugin to define rules of `--rulesdir`, so we can validate\n * the rule's options with only information in the config array.\n */\n if (rulePaths && rulePaths.length > 0) {\n baseConfigArray.push({\n type: \"config\",\n name: \"--rulesdir\",\n filePath: \"\",\n plugins: {\n \"\": new ConfigDependency({\n definition: {\n rules: rulePaths.reduce(\n (map, rulesPath) => Object.assign(\n map,\n loadRules(rulesPath, cwd)\n ),\n {}\n )\n },\n filePath: \"\",\n id: \"\",\n importerName: \"--rulesdir\",\n importerPath: \"\"\n })\n }\n });\n }\n\n return baseConfigArray;\n}\n\n/**\n * Create the config array from CLI options.\n * @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.\n * @returns {ConfigArray} The config array of the base configs.\n */\nfunction createCLIConfigArray({\n cliConfigData,\n configArrayFactory,\n cwd,\n ignorePath,\n specificConfigPath\n}) {\n const cliConfigArray = configArrayFactory.create(\n cliConfigData,\n { name: \"CLIOptions\" }\n );\n\n cliConfigArray.unshift(\n ...(ignorePath\n ? configArrayFactory.loadESLintIgnore(ignorePath)\n : configArrayFactory.loadDefaultESLintIgnore())\n );\n\n if (specificConfigPath) {\n cliConfigArray.unshift(\n ...configArrayFactory.loadFile(\n specificConfigPath,\n { name: \"--config\", basePath: cwd }\n )\n );\n }\n\n return cliConfigArray;\n}\n\n/**\n * The error type when there are files matched by a glob, but all of them have been ignored.\n */\nclass ConfigurationNotFoundError extends Error {\n\n // eslint-disable-next-line jsdoc/require-description\n /**\n * @param {string} directoryPath The directory path.\n */\n constructor(directoryPath) {\n super(`No ESLint configuration found in ${directoryPath}.`);\n this.messageTemplate = \"no-config-found\";\n this.messageData = { directoryPath };\n }\n}\n\n/**\n * This class provides the functionality that enumerates every file which is\n * matched by given glob patterns and that configuration.\n */\nclass CascadingConfigArrayFactory {\n\n /**\n * Initialize this enumerator.\n * @param {CascadingConfigArrayFactoryOptions} options The options.\n */\n constructor({\n additionalPluginPool = new Map(),\n baseConfig: baseConfigData = null,\n cliConfig: cliConfigData = null,\n cwd = process.cwd(),\n ignorePath,\n resolvePluginsRelativeTo,\n rulePaths = [],\n specificConfigPath = null,\n useEslintrc = true,\n builtInRules = new Map(),\n loadRules,\n resolver,\n eslintRecommendedPath,\n getEslintRecommendedConfig,\n eslintAllPath,\n getEslintAllConfig\n } = {}) {\n const configArrayFactory = new ConfigArrayFactory({\n additionalPluginPool,\n cwd,\n resolvePluginsRelativeTo,\n builtInRules,\n resolver,\n eslintRecommendedPath,\n getEslintRecommendedConfig,\n eslintAllPath,\n getEslintAllConfig\n });\n\n internalSlotsMap.set(this, {\n baseConfigArray: createBaseConfigArray({\n baseConfigData,\n configArrayFactory,\n cwd,\n rulePaths,\n loadRules\n }),\n baseConfigData,\n cliConfigArray: createCLIConfigArray({\n cliConfigData,\n configArrayFactory,\n cwd,\n ignorePath,\n specificConfigPath\n }),\n cliConfigData,\n configArrayFactory,\n configCache: new Map(),\n cwd,\n finalizeCache: new WeakMap(),\n ignorePath,\n rulePaths,\n specificConfigPath,\n useEslintrc,\n builtInRules,\n loadRules\n });\n }\n\n /**\n * The path to the current working directory.\n * This is used by tests.\n * @type {string}\n */\n get cwd() {\n const { cwd } = internalSlotsMap.get(this);\n\n return cwd;\n }\n\n /**\n * Get the config array of a given file.\n * If `filePath` was not given, it returns the config which contains only\n * `baseConfigData` and `cliConfigData`.\n * @param {string} [filePath] The file path to a file.\n * @param {Object} [options] The options.\n * @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`.\n * @returns {ConfigArray} The config array of the file.\n */\n getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) {\n const {\n baseConfigArray,\n cliConfigArray,\n cwd\n } = internalSlotsMap.get(this);\n\n if (!filePath) {\n return new ConfigArray(...baseConfigArray, ...cliConfigArray);\n }\n\n const directoryPath = path.dirname(path.resolve(cwd, filePath));\n\n debug(`Load config files for ${directoryPath}.`);\n\n return this._finalizeConfigArray(\n this._loadConfigInAncestors(directoryPath),\n directoryPath,\n ignoreNotFoundError\n );\n }\n\n /**\n * Set the config data to override all configs.\n * Require to call `clearCache()` method after this method is called.\n * @param {ConfigData} configData The config data to override all configs.\n * @returns {void}\n */\n setOverrideConfig(configData) {\n const slots = internalSlotsMap.get(this);\n\n slots.cliConfigData = configData;\n }\n\n /**\n * Clear config cache.\n * @returns {void}\n */\n clearCache() {\n const slots = internalSlotsMap.get(this);\n\n slots.baseConfigArray = createBaseConfigArray(slots);\n slots.cliConfigArray = createCLIConfigArray(slots);\n slots.configCache.clear();\n }\n\n /**\n * Load and normalize config files from the ancestor directories.\n * @param {string} directoryPath The path to a leaf directory.\n * @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories.\n * @returns {ConfigArray} The loaded config.\n * @private\n */\n _loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) {\n const {\n baseConfigArray,\n configArrayFactory,\n configCache,\n cwd,\n useEslintrc\n } = internalSlotsMap.get(this);\n\n if (!useEslintrc) {\n return baseConfigArray;\n }\n\n let configArray = configCache.get(directoryPath);\n\n // Hit cache.\n if (configArray) {\n debug(`Cache hit: ${directoryPath}.`);\n return configArray;\n }\n debug(`No cache found: ${directoryPath}.`);\n\n const homePath = os.homedir();\n\n // Consider this is root.\n if (directoryPath === homePath && cwd !== homePath) {\n debug(\"Stop traversing because of considered root.\");\n if (configsExistInSubdirs) {\n const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath);\n\n if (filePath) {\n emitDeprecationWarning(\n filePath,\n \"ESLINT_PERSONAL_CONFIG_SUPPRESS\"\n );\n }\n }\n return this._cacheConfig(directoryPath, baseConfigArray);\n }\n\n // Load the config on this directory.\n try {\n configArray = configArrayFactory.loadInDirectory(directoryPath);\n } catch (error) {\n /* istanbul ignore next */\n if (error.code === \"EACCES\") {\n debug(\"Stop traversing because of 'EACCES' error.\");\n return this._cacheConfig(directoryPath, baseConfigArray);\n }\n throw error;\n }\n\n if (configArray.length > 0 && configArray.isRoot()) {\n debug(\"Stop traversing because of 'root:true'.\");\n configArray.unshift(...baseConfigArray);\n return this._cacheConfig(directoryPath, configArray);\n }\n\n // Load from the ancestors and merge it.\n const parentPath = path.dirname(directoryPath);\n const parentConfigArray = parentPath && parentPath !== directoryPath\n ? this._loadConfigInAncestors(\n parentPath,\n configsExistInSubdirs || configArray.length > 0\n )\n : baseConfigArray;\n\n if (configArray.length > 0) {\n configArray.unshift(...parentConfigArray);\n } else {\n configArray = parentConfigArray;\n }\n\n // Cache and return.\n return this._cacheConfig(directoryPath, configArray);\n }\n\n /**\n * Freeze and cache a given config.\n * @param {string} directoryPath The path to a directory as a cache key.\n * @param {ConfigArray} configArray The config array as a cache value.\n * @returns {ConfigArray} The `configArray` (frozen).\n */\n _cacheConfig(directoryPath, configArray) {\n const { configCache } = internalSlotsMap.get(this);\n\n Object.freeze(configArray);\n configCache.set(directoryPath, configArray);\n\n return configArray;\n }\n\n /**\n * Finalize a given config array.\n * Concatenate `--config` and other CLI options.\n * @param {ConfigArray} configArray The parent config array.\n * @param {string} directoryPath The path to the leaf directory to find config files.\n * @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`.\n * @returns {ConfigArray} The loaded config.\n * @private\n */\n _finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) {\n const {\n cliConfigArray,\n configArrayFactory,\n finalizeCache,\n useEslintrc,\n builtInRules\n } = internalSlotsMap.get(this);\n\n let finalConfigArray = finalizeCache.get(configArray);\n\n if (!finalConfigArray) {\n finalConfigArray = configArray;\n\n // Load the personal config if there are no regular config files.\n if (\n useEslintrc &&\n configArray.every(c => !c.filePath) &&\n cliConfigArray.every(c => !c.filePath) // `--config` option can be a file.\n ) {\n const homePath = os.homedir();\n\n debug(\"Loading the config file of the home directory:\", homePath);\n\n const personalConfigArray = configArrayFactory.loadInDirectory(\n homePath,\n { name: \"PersonalConfig\" }\n );\n\n if (\n personalConfigArray.length > 0 &&\n !directoryPath.startsWith(homePath)\n ) {\n const lastElement =\n personalConfigArray[personalConfigArray.length - 1];\n\n emitDeprecationWarning(\n lastElement.filePath,\n \"ESLINT_PERSONAL_CONFIG_LOAD\"\n );\n }\n\n finalConfigArray = finalConfigArray.concat(personalConfigArray);\n }\n\n // Apply CLI options.\n if (cliConfigArray.length > 0) {\n finalConfigArray = finalConfigArray.concat(cliConfigArray);\n }\n\n // Validate rule settings and environments.\n const validator = new ConfigValidator({\n builtInRules\n });\n\n validator.validateConfigArray(finalConfigArray);\n\n // Cache it.\n Object.freeze(finalConfigArray);\n finalizeCache.set(configArray, finalConfigArray);\n\n debug(\n \"Configuration was determined: %o on %s\",\n finalConfigArray,\n directoryPath\n );\n }\n\n // At least one element (the default ignore patterns) exists.\n if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) {\n throw new ConfigurationNotFoundError(directoryPath);\n }\n\n return finalConfigArray;\n }\n}\n\n//------------------------------------------------------------------------------\n// Public Interface\n//------------------------------------------------------------------------------\n\nexport { CascadingConfigArrayFactory };\n","/**\n * @fileoverview Compatibility class for flat config.\n * @author Nicholas C. Zakas\n */\n\n//-----------------------------------------------------------------------------\n// Requirements\n//-----------------------------------------------------------------------------\n\nimport createDebug from \"debug\";\nimport path from \"path\";\n\nimport environments from \"../conf/environments.js\";\nimport { ConfigArrayFactory } from \"./config-array-factory.js\";\n\n//-----------------------------------------------------------------------------\n// Helpers\n//-----------------------------------------------------------------------------\n\n/** @typedef {import(\"../../shared/types\").Environment} Environment */\n/** @typedef {import(\"../../shared/types\").Processor} Processor */\n\nconst debug = createDebug(\"eslintrc:flat-compat\");\nconst cafactory = Symbol(\"cafactory\");\n\n/**\n * Translates an ESLintRC-style config object into a flag-config-style config\n * object.\n * @param {Object} eslintrcConfig An ESLintRC-style config object.\n * @param {Object} options Options to help translate the config.\n * @param {string} options.resolveConfigRelativeTo To the directory to resolve\n * configs from.\n * @param {string} options.resolvePluginsRelativeTo The directory to resolve\n * plugins from.\n * @param {ReadOnlyMap} options.pluginEnvironments A map of plugin environment\n * names to objects.\n * @param {ReadOnlyMap} options.pluginProcessors A map of plugin processor\n * names to objects.\n * @returns {Object} A flag-config-style config object.\n */\nfunction translateESLintRC(eslintrcConfig, {\n resolveConfigRelativeTo,\n resolvePluginsRelativeTo,\n pluginEnvironments,\n pluginProcessors\n}) {\n\n const flatConfig = {};\n const configs = [];\n const languageOptions = {};\n const linterOptions = {};\n const keysToCopy = [\"settings\", \"rules\", \"processor\"];\n const languageOptionsKeysToCopy = [\"globals\", \"parser\", \"parserOptions\"];\n const linterOptionsKeysToCopy = [\"noInlineConfig\", \"reportUnusedDisableDirectives\"];\n\n // copy over simple translations\n for (const key of keysToCopy) {\n if (key in eslintrcConfig && typeof eslintrcConfig[key] !== \"undefined\") {\n flatConfig[key] = eslintrcConfig[key];\n }\n }\n\n // copy over languageOptions\n for (const key of languageOptionsKeysToCopy) {\n if (key in eslintrcConfig && typeof eslintrcConfig[key] !== \"undefined\") {\n\n // create the languageOptions key in the flat config\n flatConfig.languageOptions = languageOptions;\n\n if (key === \"parser\") {\n debug(`Resolving parser '${languageOptions[key]}' relative to ${resolveConfigRelativeTo}`);\n\n if (eslintrcConfig[key].error) {\n throw eslintrcConfig[key].error;\n }\n\n languageOptions[key] = eslintrcConfig[key].definition;\n continue;\n }\n\n // clone any object values that are in the eslintrc config\n if (eslintrcConfig[key] && typeof eslintrcConfig[key] === \"object\") {\n languageOptions[key] = {\n ...eslintrcConfig[key]\n };\n } else {\n languageOptions[key] = eslintrcConfig[key];\n }\n }\n }\n\n // copy over linterOptions\n for (const key of linterOptionsKeysToCopy) {\n if (key in eslintrcConfig && typeof eslintrcConfig[key] !== \"undefined\") {\n flatConfig.linterOptions = linterOptions;\n linterOptions[key] = eslintrcConfig[key];\n }\n }\n\n // move ecmaVersion a level up\n if (languageOptions.parserOptions) {\n\n if (\"ecmaVersion\" in languageOptions.parserOptions) {\n languageOptions.ecmaVersion = languageOptions.parserOptions.ecmaVersion;\n delete languageOptions.parserOptions.ecmaVersion;\n }\n\n if (\"sourceType\" in languageOptions.parserOptions) {\n languageOptions.sourceType = languageOptions.parserOptions.sourceType;\n delete languageOptions.parserOptions.sourceType;\n }\n\n // check to see if we even need parserOptions anymore and remove it if not\n if (Object.keys(languageOptions.parserOptions).length === 0) {\n delete languageOptions.parserOptions;\n }\n }\n\n // overrides\n if (eslintrcConfig.criteria) {\n flatConfig.files = [absoluteFilePath => eslintrcConfig.criteria.test(absoluteFilePath)];\n }\n\n // translate plugins\n if (eslintrcConfig.plugins && typeof eslintrcConfig.plugins === \"object\") {\n debug(`Translating plugins: ${eslintrcConfig.plugins}`);\n\n flatConfig.plugins = {};\n\n for (const pluginName of Object.keys(eslintrcConfig.plugins)) {\n\n debug(`Translating plugin: ${pluginName}`);\n debug(`Resolving plugin '${pluginName} relative to ${resolvePluginsRelativeTo}`);\n\n const { original: plugin, error } = eslintrcConfig.plugins[pluginName];\n\n if (error) {\n throw error;\n }\n\n flatConfig.plugins[pluginName] = plugin;\n\n // create a config for any processors\n if (plugin.processors) {\n for (const processorName of Object.keys(plugin.processors)) {\n if (processorName.startsWith(\".\")) {\n debug(`Assigning processor: ${pluginName}/${processorName}`);\n\n configs.unshift({\n files: [`**/*${processorName}`],\n processor: pluginProcessors.get(`${pluginName}/${processorName}`)\n });\n }\n\n }\n }\n }\n }\n\n // translate env - must come after plugins\n if (eslintrcConfig.env && typeof eslintrcConfig.env === \"object\") {\n for (const envName of Object.keys(eslintrcConfig.env)) {\n\n // only add environments that are true\n if (eslintrcConfig.env[envName]) {\n debug(`Translating environment: ${envName}`);\n\n if (environments.has(envName)) {\n\n // built-in environments should be defined first\n configs.unshift(...translateESLintRC({\n criteria: eslintrcConfig.criteria,\n ...environments.get(envName)\n }, {\n resolveConfigRelativeTo,\n resolvePluginsRelativeTo\n }));\n } else if (pluginEnvironments.has(envName)) {\n\n // if the environment comes from a plugin, it should come after the plugin config\n configs.push(...translateESLintRC({\n criteria: eslintrcConfig.criteria,\n ...pluginEnvironments.get(envName)\n }, {\n resolveConfigRelativeTo,\n resolvePluginsRelativeTo\n }));\n }\n }\n }\n }\n\n // only add if there are actually keys in the config\n if (Object.keys(flatConfig).length > 0) {\n configs.push(flatConfig);\n }\n\n return configs;\n}\n\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\n/**\n * A compatibility class for working with configs.\n */\nclass FlatCompat {\n\n constructor({\n baseDirectory = process.cwd(),\n resolvePluginsRelativeTo = baseDirectory,\n recommendedConfig,\n allConfig\n } = {}) {\n this.baseDirectory = baseDirectory;\n this.resolvePluginsRelativeTo = resolvePluginsRelativeTo;\n this[cafactory] = new ConfigArrayFactory({\n cwd: baseDirectory,\n resolvePluginsRelativeTo,\n getEslintAllConfig: () => {\n\n if (!allConfig) {\n throw new TypeError(\"Missing parameter 'allConfig' in FlatCompat constructor.\");\n }\n\n return allConfig;\n },\n getEslintRecommendedConfig: () => {\n\n if (!recommendedConfig) {\n throw new TypeError(\"Missing parameter 'recommendedConfig' in FlatCompat constructor.\");\n }\n\n return recommendedConfig;\n }\n });\n }\n\n /**\n * Translates an ESLintRC-style config into a flag-config-style config.\n * @param {Object} eslintrcConfig The ESLintRC-style config object.\n * @returns {Object} A flag-config-style config object.\n */\n config(eslintrcConfig) {\n const eslintrcArray = this[cafactory].create(eslintrcConfig, {\n basePath: this.baseDirectory\n });\n\n const flatArray = [];\n let hasIgnorePatterns = false;\n\n eslintrcArray.forEach(configData => {\n if (configData.type === \"config\") {\n hasIgnorePatterns = hasIgnorePatterns || configData.ignorePattern;\n flatArray.push(...translateESLintRC(configData, {\n resolveConfigRelativeTo: path.join(this.baseDirectory, \"__placeholder.js\"),\n resolvePluginsRelativeTo: path.join(this.resolvePluginsRelativeTo, \"__placeholder.js\"),\n pluginEnvironments: eslintrcArray.pluginEnvironments,\n pluginProcessors: eslintrcArray.pluginProcessors\n }));\n }\n });\n\n // combine ignorePatterns to emulate ESLintRC behavior better\n if (hasIgnorePatterns) {\n flatArray.unshift({\n ignores: [filePath => {\n\n // Compute the final config for this file.\n // This filters config array elements by `files`/`excludedFiles` then merges the elements.\n const finalConfig = eslintrcArray.extractConfig(filePath);\n\n // Test the `ignorePattern` properties of the final config.\n return Boolean(finalConfig.ignores) && finalConfig.ignores(filePath);\n }]\n });\n }\n\n return flatArray;\n }\n\n /**\n * Translates the `env` section of an ESLintRC-style config.\n * @param {Object} envConfig The `env` section of an ESLintRC config.\n * @returns {Object[]} An array of flag-config objects representing the environments.\n */\n env(envConfig) {\n return this.config({\n env: envConfig\n });\n }\n\n /**\n * Translates the `extends` section of an ESLintRC-style config.\n * @param {...string} configsToExtend The names of the configs to load.\n * @returns {Object[]} An array of flag-config objects representing the config.\n */\n extends(...configsToExtend) {\n return this.config({\n extends: configsToExtend\n });\n }\n\n /**\n * Translates the `plugins` section of an ESLintRC-style config.\n * @param {...string} plugins The names of the plugins to load.\n * @returns {Object[]} An array of flag-config objects representing the plugins.\n */\n plugins(...plugins) {\n return this.config({\n plugins\n });\n }\n}\n\nexport { FlatCompat };\n","/**\n * @fileoverview Package exports for @eslint/eslintrc\n * @author Nicholas C. Zakas\n */\n//------------------------------------------------------------------------------\n// Requirements\n//------------------------------------------------------------------------------\n\nimport {\n ConfigArrayFactory,\n createContext as createConfigArrayFactoryContext\n} from \"./config-array-factory.js\";\n\nimport { CascadingConfigArrayFactory } from \"./cascading-config-array-factory.js\";\nimport * as ModuleResolver from \"./shared/relative-module-resolver.js\";\nimport { ConfigArray, getUsedExtractedConfigs } from \"./config-array/index.js\";\nimport { ConfigDependency } from \"./config-array/config-dependency.js\";\nimport { ExtractedConfig } from \"./config-array/extracted-config.js\";\nimport { IgnorePattern } from \"./config-array/ignore-pattern.js\";\nimport { OverrideTester } from \"./config-array/override-tester.js\";\nimport * as ConfigOps from \"./shared/config-ops.js\";\nimport ConfigValidator from \"./shared/config-validator.js\";\nimport * as naming from \"./shared/naming.js\";\nimport { FlatCompat } from \"./flat-compat.js\";\nimport environments from \"../conf/environments.js\";\n\n//-----------------------------------------------------------------------------\n// Exports\n//-----------------------------------------------------------------------------\n\nconst Legacy = {\n ConfigArray,\n createConfigArrayFactoryContext,\n CascadingConfigArrayFactory,\n ConfigArrayFactory,\n ConfigDependency,\n ExtractedConfig,\n IgnorePattern,\n OverrideTester,\n getUsedExtractedConfigs,\n environments,\n\n // shared\n ConfigOps,\n ConfigValidator,\n ModuleResolver,\n naming\n};\n\nexport {\n\n Legacy,\n\n FlatCompat\n\n};\n"],"names":["debug","debugOrig","path","ignore","assert","internalSlotsMap","util","minimatch","Ajv","globals","BuiltInEnvironments","ConfigOps.normalizeConfigGlobal","Module","require","createRequire","fs","stripComments","importFresh","ModuleResolver.resolve","naming.normalizePackageName","naming.getShorthandName","os","createDebug","createConfigArrayFactoryContext"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAUA;AACA,MAAMA,OAAK,GAAGC,6BAAS,CAAC,yBAAyB,CAAC,CAAC;AACnD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,qBAAqB,CAAC,WAAW,EAAE;AAC5C,IAAI,IAAI,MAAM,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC;AAChC;AACA,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,CAAC,M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CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;AACjE,KAAK,CAAC,OAAO,KAAK,EAAE;AACpB;AACA;AACA,QAAQ;AACR,YAAY,OAAO,KAAK,KAAK,QAAQ;AACrC,YAAY,KAAK,KAAK,IAAI;AAC1B,YAAY,KAAK,CAAC,IAAI,KAAK,kBAAkB;AAC7C,YAAY,CAAC,KAAK,CAAC,YAAY;AAC/B,YAAY,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC;AAC9C,UAAU;AACV,YAAY,KAAK,CAAC,OAAO,IAAI,CAAC,oBAAoB,EAAE,cAAc,CAAC,CAAC,CAAC;AACrE,SAAS;AACT,QAAQ,MAAM,KAAK,CAAC;AACpB,KAAK;AACL;;;;;;;ACrCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAsBA;AACA,MAAMC,SAAO,GAAGC,oBAAa,CAAC,mDAAe,CAAC,CAAC;AAC/C;AACA,MAAMd,OAAK,GAAGC,6BAAS,CAAC,+BAA+B,CAAC,CAAC;AACzD;AACA;AACA;AACA;AACA;AACA,MAAM,eAAe,GAAG;AACxB,IAAI,cAAc;AAClB,IAAI,eAAe;AACnB,IAAI,gBAAgB;AACpB,IAAI,eAAe;AACnB,IAAI,gBAAgB;AACpB,IAAI,WAAW;AACf,IAAI,cAAc;AAClB,CAAC,CAAC;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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,MAAM;AACV;;;;;"} \ No newline at end of file diff --git a/node_modules/@humanwhocodes/module-importer/dist/module-importer.cjs b/node_modules/@humanwhocodes/module-importer/dist/module-importer.cjs new file mode 100644 index 0000000..779e0cf --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/dist/module-importer.cjs @@ -0,0 +1,22 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var module$1 = require('module'); +var url = require('url'); +var path = require('path'); + +/** + * @fileoverview Universal module importer + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const __filename$1 = url.fileURLToPath((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('module-importer.cjs', document.baseURI).href))); +const __dirname$1 = path.dirname(__filename$1); +const require$1 = module$1.createRequire(__dirname$1 + "/"); +const { ModuleImporter } = require$1("./module-importer.cjs"); + +exports.ModuleImporter = ModuleImporter; diff --git a/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.cts b/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.cts new file mode 100644 index 0000000..a1acbb6 --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.cts @@ -0,0 +1,27 @@ +export class ModuleImporter { + /** + * Creates a new instance. + * @param {string} [cwd] The current working directory to resolve from. + */ + constructor(cwd?: string); + /** + * The base directory from which paths should be resolved. + * @type {string} + */ + cwd: string; + /** + * Resolves a module based on its name or location. + * @param {string} specifier Either an npm package name or + * relative file path. + * @returns {string|undefined} The location of the import. + * @throws {Error} If specifier cannot be located. + */ + resolve(specifier: string): string | undefined; + /** + * Imports a module based on its name or location. + * @param {string} specifier Either an npm package name or + * relative file path. + * @returns {Promise} The module's object. + */ + import(specifier: string): Promise; +} diff --git a/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.ts b/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.ts new file mode 100644 index 0000000..498f0a2 --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/dist/module-importer.d.ts @@ -0,0 +1,2 @@ +export { ModuleImporter }; +import { ModuleImporter } from "./module-importer.cjs"; diff --git a/node_modules/@humanwhocodes/module-importer/dist/module-importer.js b/node_modules/@humanwhocodes/module-importer/dist/module-importer.js new file mode 100644 index 0000000..26e052d --- /dev/null +++ b/node_modules/@humanwhocodes/module-importer/dist/module-importer.js @@ -0,0 +1,18 @@ +import { createRequire } from 'module'; +import { fileURLToPath } from 'url'; +import { dirname } from 'path'; + +/** + * @fileoverview Universal module importer + */ + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const require = createRequire(__dirname + "/"); +const { ModuleImporter } = require("./module-importer.cjs"); + +export { ModuleImporter }; diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs new file mode 100644 index 0000000..5aeb5cc --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs @@ -0,0 +1,230 @@ +import { SetArray, put } from '@jridgewell/set-array'; +import { encode } from '@jridgewell/sourcemap-codec'; +import { TraceMap, decodedMappings } from '@jridgewell/trace-mapping'; + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; + +const NO_NAME = -1; +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +let addSegment; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +let addMapping; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +let maybeAddSegment; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +let maybeAddMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +let setSourceContent; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let toDecodedMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let toEncodedMap; +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +let fromMap; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +let allMappings; +// This split declaration is only so that terser can elminiate the static initialization block. +let addSegmentInternal; +/** + * Provides the state to generate a sourcemap. + */ +class GenMapping { + constructor({ file, sourceRoot } = {}) { + this._names = new SetArray(); + this._sources = new SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + } +} +(() => { + addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(false, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + addMapping = (map, mapping) => { + return addMappingInternal(false, map, mapping); + }; + maybeAddMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping); + }; + setSourceContent = (map, source, content) => { + const { _sources: sources, _sourcesContent: sourcesContent } = map; + sourcesContent[put(sources, source)] = content; + }; + toDecodedMap = (map) => { + const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + removeEmptyFinalLines(mappings); + return { + version: 3, + file: file || undefined, + names: names.array, + sourceRoot: sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + }; + }; + toEncodedMap = (map) => { + const decoded = toDecodedMap(map); + return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) }); + }; + allMappings = (map) => { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = map; + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[COLUMN] }; + let source = undefined; + let original = undefined; + let name = undefined; + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + if (seg.length === 5) + name = names.array[seg[NAMES_INDEX]]; + } + out.push({ generated, source, original, name }); + } + } + return out; + }; + fromMap = (input) => { + const map = new TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + putAll(gen._names, map.names); + putAll(gen._sources, map.sources); + gen._sourcesContent = map.sourcesContent || map.sources.map(() => null); + gen._mappings = decodedMappings(map); + return gen; + }; + // Internal helpers + addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + const line = getLine(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) + return; + return insert(line, index, [genColumn]); + } + const sourcesIndex = put(sources, source); + const namesIndex = name ? put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) + sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null; + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + return insert(line, index, name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] + : [genColumn, sourcesIndex, sourceLine, sourceColumn]); + }; +})(); +function getLine(mappings, index) { + for (let i = mappings.length; i <= index; i++) { + mappings[i] = []; + } + return mappings[index]; +} +function getColumnIndex(line, genColumn) { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) + break; + } + return index; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +function removeEmptyFinalLines(mappings) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) + break; + } + if (len < length) + mappings.length = len; +} +function putAll(strarr, array) { + for (let i = 0; i < array.length; i++) + put(strarr, array[i]); +} +function skipSourceless(line, index) { + // The start of a line is already sourceless, so adding a sourceless segment to the beginning + // doesn't generate any useful information. + if (index === 0) + return true; + const prev = line[index - 1]; + // If the previous segment is also sourceless, then adding another sourceless segment doesn't + // genrate any new information. Else, this segment will end the source/named segment and point to + // a sourceless position, which is useful. + return prev.length === 1; +} +function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + // A source/named segment at the start of a line gives position at that genColumn + if (index === 0) + return false; + const prev = line[index - 1]; + // If the previous segment is sourceless, then we're transitioning to a source. + if (prev.length === 1) + return false; + // If the previous segment maps to the exact same source position, then this segment doesn't + // provide any new position information. + return (sourcesIndex === prev[SOURCES_INDEX] && + sourceLine === prev[SOURCE_LINE] && + sourceColumn === prev[SOURCE_COLUMN] && + namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)); +} +function addMappingInternal(skipable, map, mapping) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null); + } + const s = source; + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, s, original.line - 1, original.column, name, content); +} + +export { GenMapping, addMapping, addSegment, allMappings, fromMap, maybeAddMapping, maybeAddSegment, setSourceContent, toDecodedMap, toEncodedMap }; +//# sourceMappingURL=gen-mapping.mjs.map diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map new file mode 100644 index 0000000..2fee0cd --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.mjs","sources":["../src/sourcemap-segment.ts","../src/gen-mapping.ts"],"sourcesContent":["type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n","import { SetArray, put } from '@jridgewell/set-array';\nimport { encode } from '@jridgewell/sourcemap-codec';\nimport { TraceMap, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type { SourceMapInput } from '@jridgewell/trace-mapping';\nimport type { SourceMapSegment } from './sourcemap-segment';\nimport type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types';\n\nexport type { DecodedSourceMap, EncodedSourceMap, Mapping };\n\nexport type Options = {\n file?: string | null;\n sourceRoot?: string | null;\n};\n\nconst NO_NAME = -1;\n\n/**\n * A low-level API to associate a generated position with an original source position. Line and\n * column here are 0-based, unlike `addMapping`.\n */\nexport let addSegment: {\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source?: null,\n sourceLine?: null,\n sourceColumn?: null,\n name?: null,\n content?: null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name?: null,\n content?: string | null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name: string,\n content?: string | null,\n ): void;\n};\n\n/**\n * A high-level API to associate a generated position with an original source position. Line is\n * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.\n */\nexport let addMapping: {\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source?: null;\n original?: null;\n name?: null;\n content?: null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name?: null;\n content?: string | null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name: string;\n content?: string | null;\n },\n ): void;\n};\n\n/**\n * Same as `addSegment`, but will only add the segment if it generates useful information in the\n * resulting map. This only works correctly if segments are added **in order**, meaning you should\n * not add a segment with a lower generated line/column than one that came before.\n */\nexport let maybeAddSegment: typeof addSegment;\n\n/**\n * Same as `addMapping`, but will only add the mapping if it generates useful information in the\n * resulting map. This only works correctly if mappings are added **in order**, meaning you should\n * not add a mapping with a lower generated line/column than one that came before.\n */\nexport let maybeAddMapping: typeof addMapping;\n\n/**\n * Adds/removes the content of the source file to the source map.\n */\nexport let setSourceContent: (map: GenMapping, source: string, content: string | null) => void;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let toDecodedMap: (map: GenMapping) => DecodedSourceMap;\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let toEncodedMap: (map: GenMapping) => EncodedSourceMap;\n\n/**\n * Constructs a new GenMapping, using the already present mappings of the input.\n */\nexport let fromMap: (input: SourceMapInput) => GenMapping;\n\n/**\n * Returns an array of high-level mapping objects for every recorded segment, which could then be\n * passed to the `source-map` library.\n */\nexport let allMappings: (map: GenMapping) => Mapping[];\n\n// This split declaration is only so that terser can elminiate the static initialization block.\nlet addSegmentInternal: (\n skipable: boolean,\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: S,\n sourceLine: S extends string ? number : null | undefined,\n sourceColumn: S extends string ? number : null | undefined,\n name: S extends string ? string | null | undefined : null | undefined,\n content: S extends string ? string | null | undefined : null | undefined,\n) => void;\n\n/**\n * Provides the state to generate a sourcemap.\n */\nexport class GenMapping {\n private _names = new SetArray();\n private _sources = new SetArray();\n private _sourcesContent: (string | null)[] = [];\n private _mappings: SourceMapSegment[][] = [];\n declare file: string | null | undefined;\n declare sourceRoot: string | null | undefined;\n\n constructor({ file, sourceRoot }: Options = {}) {\n this.file = file;\n this.sourceRoot = sourceRoot;\n }\n\n static {\n addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {\n return addSegmentInternal(\n false,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n };\n\n maybeAddSegment = (\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n ) => {\n return addSegmentInternal(\n true,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n };\n\n addMapping = (map, mapping) => {\n return addMappingInternal(false, map, mapping as Parameters[2]);\n };\n\n maybeAddMapping = (map, mapping) => {\n return addMappingInternal(true, map, mapping as Parameters[2]);\n };\n\n setSourceContent = (map, source, content) => {\n const { _sources: sources, _sourcesContent: sourcesContent } = map;\n sourcesContent[put(sources, source)] = content;\n };\n\n toDecodedMap = (map) => {\n const {\n file,\n sourceRoot,\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n removeEmptyFinalLines(mappings);\n\n return {\n version: 3,\n file: file || undefined,\n names: names.array,\n sourceRoot: sourceRoot || undefined,\n sources: sources.array,\n sourcesContent,\n mappings,\n };\n };\n\n toEncodedMap = (map) => {\n const decoded = toDecodedMap(map);\n return {\n ...decoded,\n mappings: encode(decoded.mappings as SourceMapSegment[][]),\n };\n };\n\n allMappings = (map) => {\n const out: Mapping[] = [];\n const { _mappings: mappings, _sources: sources, _names: names } = map;\n\n for (let i = 0; i < mappings.length; i++) {\n const line = mappings[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generated = { line: i + 1, column: seg[COLUMN] };\n let source: string | undefined = undefined;\n let original: Pos | undefined = undefined;\n let name: string | undefined = undefined;\n\n if (seg.length !== 1) {\n source = sources.array[seg[SOURCES_INDEX]];\n original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };\n\n if (seg.length === 5) name = names.array[seg[NAMES_INDEX]];\n }\n\n out.push({ generated, source, original, name } as Mapping);\n }\n }\n\n return out;\n };\n\n fromMap = (input) => {\n const map = new TraceMap(input);\n const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });\n\n putAll(gen._names, map.names);\n putAll(gen._sources, map.sources as string[]);\n gen._sourcesContent = map.sourcesContent || map.sources.map(() => null);\n gen._mappings = decodedMappings(map) as GenMapping['_mappings'];\n\n return gen;\n };\n\n // Internal helpers\n addSegmentInternal = (\n skipable,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n ) => {\n const {\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n const line = getLine(mappings, genLine);\n const index = getColumnIndex(line, genColumn);\n\n if (!source) {\n if (skipable && skipSourceless(line, index)) return;\n return insert(line, index, [genColumn]);\n }\n\n // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source\n // isn't nullish.\n assert(sourceLine);\n assert(sourceColumn);\n\n const sourcesIndex = put(sources, source);\n const namesIndex = name ? put(names, name) : NO_NAME;\n if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content ?? null;\n\n if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {\n return;\n }\n\n return insert(\n line,\n index,\n name\n ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]\n : [genColumn, sourcesIndex, sourceLine, sourceColumn],\n );\n };\n }\n}\n\nfunction assert(_val: unknown): asserts _val is T {\n // noop.\n}\n\nfunction getLine(mappings: SourceMapSegment[][], index: number): SourceMapSegment[] {\n for (let i = mappings.length; i <= index; i++) {\n mappings[i] = [];\n }\n return mappings[index];\n}\n\nfunction getColumnIndex(line: SourceMapSegment[], genColumn: number): number {\n let index = line.length;\n for (let i = index - 1; i >= 0; index = i--) {\n const current = line[i];\n if (genColumn >= current[COLUMN]) break;\n }\n return index;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\nfunction removeEmptyFinalLines(mappings: SourceMapSegment[][]) {\n const { length } = mappings;\n let len = length;\n for (let i = len - 1; i >= 0; len = i, i--) {\n if (mappings[i].length > 0) break;\n }\n if (len < length) mappings.length = len;\n}\n\nfunction putAll(strarr: SetArray, array: string[]) {\n for (let i = 0; i < array.length; i++) put(strarr, array[i]);\n}\n\nfunction skipSourceless(line: SourceMapSegment[], index: number): boolean {\n // The start of a line is already sourceless, so adding a sourceless segment to the beginning\n // doesn't generate any useful information.\n if (index === 0) return true;\n\n const prev = line[index - 1];\n // If the previous segment is also sourceless, then adding another sourceless segment doesn't\n // genrate any new information. Else, this segment will end the source/named segment and point to\n // a sourceless position, which is useful.\n return prev.length === 1;\n}\n\nfunction skipSource(\n line: SourceMapSegment[],\n index: number,\n sourcesIndex: number,\n sourceLine: number,\n sourceColumn: number,\n namesIndex: number,\n): boolean {\n // A source/named segment at the start of a line gives position at that genColumn\n if (index === 0) return false;\n\n const prev = line[index - 1];\n\n // If the previous segment is sourceless, then we're transitioning to a source.\n if (prev.length === 1) return false;\n\n // If the previous segment maps to the exact same source position, then this segment doesn't\n // provide any new position information.\n return (\n sourcesIndex === prev[SOURCES_INDEX] &&\n sourceLine === prev[SOURCE_LINE] &&\n sourceColumn === prev[SOURCE_COLUMN] &&\n namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)\n );\n}\n\nfunction addMappingInternal(\n skipable: boolean,\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: S;\n original: S extends string ? Pos : null | undefined;\n name: S extends string ? string | null | undefined : null | undefined;\n content: S extends string ? string | null | undefined : null | undefined;\n },\n) {\n const { generated, source, original, name, content } = mapping;\n if (!source) {\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n null,\n null,\n null,\n null,\n null,\n );\n }\n const s: string = source;\n assert(original);\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n s,\n original.line - 1,\n original.column,\n name,\n content,\n );\n}\n"],"names":[],"mappings":";;;;AAWO,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,WAAW,GAAG,CAAC;;ACQ5B,MAAM,OAAO,GAAG,CAAC,CAAC,CAAC;AAEnB;;;AAGG;AACQ,IAAA,WA+BT;AAEF;;;AAGG;AACQ,IAAA,WA+BT;AAEF;;;;AAIG;AACQ,IAAA,gBAAmC;AAE9C;;;;AAIG;AACQ,IAAA,gBAAmC;AAE9C;;AAEG;AACQ,IAAA,iBAAoF;AAE/F;;;AAGG;AACQ,IAAA,aAAoD;AAE/D;;;AAGG;AACQ,IAAA,aAAoD;AAE/D;;AAEG;AACQ,IAAA,QAA+C;AAE1D;;;AAGG;AACQ,IAAA,YAA4C;AAEvD;AACA,IAAI,kBAUK,CAAC;AAEV;;AAEG;MACU,UAAU,CAAA;AAQrB,IAAA,WAAA,CAAY,EAAE,IAAI,EAAE,UAAU,KAAc,EAAE,EAAA;AAPtC,QAAA,IAAA,CAAA,MAAM,GAAG,IAAI,QAAQ,EAAE,CAAC;AACxB,QAAA,IAAA,CAAA,QAAQ,GAAG,IAAI,QAAQ,EAAE,CAAC;QAC1B,IAAe,CAAA,eAAA,GAAsB,EAAE,CAAC;QACxC,IAAS,CAAA,SAAA,GAAyB,EAAE,CAAC;AAK3C,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;AACjB,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;KAC9B;AA2KF,CAAA;AAzKC,CA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,IAAA,QACE,YAAY,KAAK,IAAI,CAAC,aAAa,CAAC;AACpC,QAAA,UAAU,KAAK,IAAI,CAAC,WAAW,CAAC;AAChC,QAAA,YAAY,KAAK,IAAI,CAAC,aAAa,CAAC;QACpC,UAAU,MAAM,IAAI,CAAC,MAAM,KAAK,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,OAAO,CAAC,EAChE;AACJ,CAAC;AAED,SAAS,kBAAkB,CACzB,QAAiB,EACjB,GAAe,EACf,OAMC,EAAA;AAED,IAAA,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IAC/D,IAAI,CAAC,MAAM,EAAE;QACX,OAAO,kBAAkB,CACvB,QAAQ,EACR,GAAG,EACH,SAAS,CAAC,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,CACL,CAAC;AACH,KAAA;IACD,MAAM,CAAC,GAAW,MAAM,CAAC;AAEzB,IAAA,OAAO,kBAAkB,CACvB,QAAQ,EACR,GAAG,EACH,SAAS,CAAC,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,CAAC,EACD,QAAQ,CAAC,IAAI,GAAG,CAAC,EACjB,QAAQ,CAAC,MAAM,EACf,IAAI,EACJ,OAAO,CACR,CAAC;AACJ;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js new file mode 100644 index 0000000..d9fcf5c --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js @@ -0,0 +1,236 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/set-array'), require('@jridgewell/sourcemap-codec'), require('@jridgewell/trace-mapping')) : + typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/set-array', '@jridgewell/sourcemap-codec', '@jridgewell/trace-mapping'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.genMapping = {}, global.setArray, global.sourcemapCodec, global.traceMapping)); +})(this, (function (exports, setArray, sourcemapCodec, traceMapping) { 'use strict'; + + const COLUMN = 0; + const SOURCES_INDEX = 1; + const SOURCE_LINE = 2; + const SOURCE_COLUMN = 3; + const NAMES_INDEX = 4; + + const NO_NAME = -1; + /** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ + exports.addSegment = void 0; + /** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ + exports.addMapping = void 0; + /** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ + exports.maybeAddSegment = void 0; + /** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ + exports.maybeAddMapping = void 0; + /** + * Adds/removes the content of the source file to the source map. + */ + exports.setSourceContent = void 0; + /** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.toDecodedMap = void 0; + /** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.toEncodedMap = void 0; + /** + * Constructs a new GenMapping, using the already present mappings of the input. + */ + exports.fromMap = void 0; + /** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ + exports.allMappings = void 0; + // This split declaration is only so that terser can elminiate the static initialization block. + let addSegmentInternal; + /** + * Provides the state to generate a sourcemap. + */ + class GenMapping { + constructor({ file, sourceRoot } = {}) { + this._names = new setArray.SetArray(); + this._sources = new setArray.SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + } + } + (() => { + exports.addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(false, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + exports.maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + exports.addMapping = (map, mapping) => { + return addMappingInternal(false, map, mapping); + }; + exports.maybeAddMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping); + }; + exports.setSourceContent = (map, source, content) => { + const { _sources: sources, _sourcesContent: sourcesContent } = map; + sourcesContent[setArray.put(sources, source)] = content; + }; + exports.toDecodedMap = (map) => { + const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + removeEmptyFinalLines(mappings); + return { + version: 3, + file: file || undefined, + names: names.array, + sourceRoot: sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + }; + }; + exports.toEncodedMap = (map) => { + const decoded = exports.toDecodedMap(map); + return Object.assign(Object.assign({}, decoded), { mappings: sourcemapCodec.encode(decoded.mappings) }); + }; + exports.allMappings = (map) => { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = map; + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[COLUMN] }; + let source = undefined; + let original = undefined; + let name = undefined; + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + if (seg.length === 5) + name = names.array[seg[NAMES_INDEX]]; + } + out.push({ generated, source, original, name }); + } + } + return out; + }; + exports.fromMap = (input) => { + const map = new traceMapping.TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + putAll(gen._names, map.names); + putAll(gen._sources, map.sources); + gen._sourcesContent = map.sourcesContent || map.sources.map(() => null); + gen._mappings = traceMapping.decodedMappings(map); + return gen; + }; + // Internal helpers + addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + const line = getLine(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) + return; + return insert(line, index, [genColumn]); + } + const sourcesIndex = setArray.put(sources, source); + const namesIndex = name ? setArray.put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) + sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null; + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + return insert(line, index, name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] + : [genColumn, sourcesIndex, sourceLine, sourceColumn]); + }; + })(); + function getLine(mappings, index) { + for (let i = mappings.length; i <= index; i++) { + mappings[i] = []; + } + return mappings[index]; + } + function getColumnIndex(line, genColumn) { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) + break; + } + return index; + } + function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; + } + function removeEmptyFinalLines(mappings) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) + break; + } + if (len < length) + mappings.length = len; + } + function putAll(strarr, array) { + for (let i = 0; i < array.length; i++) + setArray.put(strarr, array[i]); + } + function skipSourceless(line, index) { + // The start of a line is already sourceless, so adding a sourceless segment to the beginning + // doesn't generate any useful information. + if (index === 0) + return true; + const prev = line[index - 1]; + // If the previous segment is also sourceless, then adding another sourceless segment doesn't + // genrate any new information. Else, this segment will end the source/named segment and point to + // a sourceless position, which is useful. + return prev.length === 1; + } + function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + // A source/named segment at the start of a line gives position at that genColumn + if (index === 0) + return false; + const prev = line[index - 1]; + // If the previous segment is sourceless, then we're transitioning to a source. + if (prev.length === 1) + return false; + // If the previous segment maps to the exact same source position, then this segment doesn't + // provide any new position information. + return (sourcesIndex === prev[SOURCES_INDEX] && + sourceLine === prev[SOURCE_LINE] && + sourceColumn === prev[SOURCE_COLUMN] && + namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)); + } + function addMappingInternal(skipable, map, mapping) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null, null); + } + const s = source; + return addSegmentInternal(skipable, map, generated.line - 1, generated.column, s, original.line - 1, original.column, name, content); + } + + exports.GenMapping = GenMapping; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=gen-mapping.umd.js.map diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map new file mode 100644 index 0000000..7cc8d14 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.umd.js","sources":["../src/sourcemap-segment.ts","../src/gen-mapping.ts"],"sourcesContent":["type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n","import { SetArray, put } from '@jridgewell/set-array';\nimport { encode } from '@jridgewell/sourcemap-codec';\nimport { TraceMap, decodedMappings } from '@jridgewell/trace-mapping';\n\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type { SourceMapInput } from '@jridgewell/trace-mapping';\nimport type { SourceMapSegment } from './sourcemap-segment';\nimport type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types';\n\nexport type { DecodedSourceMap, EncodedSourceMap, Mapping };\n\nexport type Options = {\n file?: string | null;\n sourceRoot?: string | null;\n};\n\nconst NO_NAME = -1;\n\n/**\n * A low-level API to associate a generated position with an original source position. Line and\n * column here are 0-based, unlike `addMapping`.\n */\nexport let addSegment: {\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source?: null,\n sourceLine?: null,\n sourceColumn?: null,\n name?: null,\n content?: null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name?: null,\n content?: string | null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name: string,\n content?: string | null,\n ): void;\n};\n\n/**\n * A high-level API to associate a generated position with an original source position. Line is\n * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.\n */\nexport let addMapping: {\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source?: null;\n original?: null;\n name?: null;\n content?: null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name?: null;\n content?: string | null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name: string;\n content?: string | null;\n },\n ): void;\n};\n\n/**\n * Same as `addSegment`, but will only add the segment if it generates useful information in the\n * resulting map. This only works correctly if segments are added **in order**, meaning you should\n * not add a segment with a lower generated line/column than one that came before.\n */\nexport let maybeAddSegment: typeof addSegment;\n\n/**\n * Same as `addMapping`, but will only add the mapping if it generates useful information in the\n * resulting map. This only works correctly if mappings are added **in order**, meaning you should\n * not add a mapping with a lower generated line/column than one that came before.\n */\nexport let maybeAddMapping: typeof addMapping;\n\n/**\n * Adds/removes the content of the source file to the source map.\n */\nexport let setSourceContent: (map: GenMapping, source: string, content: string | null) => void;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let toDecodedMap: (map: GenMapping) => DecodedSourceMap;\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let toEncodedMap: (map: GenMapping) => EncodedSourceMap;\n\n/**\n * Constructs a new GenMapping, using the already present mappings of the input.\n */\nexport let fromMap: (input: SourceMapInput) => GenMapping;\n\n/**\n * Returns an array of high-level mapping objects for every recorded segment, which could then be\n * passed to the `source-map` library.\n */\nexport let allMappings: (map: GenMapping) => Mapping[];\n\n// This split declaration is only so that terser can elminiate the static initialization block.\nlet addSegmentInternal: (\n skipable: boolean,\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: S,\n sourceLine: S extends string ? number : null | undefined,\n sourceColumn: S extends string ? number : null | undefined,\n name: S extends string ? string | null | undefined : null | undefined,\n content: S extends string ? string | null | undefined : null | undefined,\n) => void;\n\n/**\n * Provides the state to generate a sourcemap.\n */\nexport class GenMapping {\n private _names = new SetArray();\n private _sources = new SetArray();\n private _sourcesContent: (string | null)[] = [];\n private _mappings: SourceMapSegment[][] = [];\n declare file: string | null | undefined;\n declare sourceRoot: string | null | undefined;\n\n constructor({ file, sourceRoot }: Options = {}) {\n this.file = file;\n this.sourceRoot = sourceRoot;\n }\n\n static {\n addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {\n return addSegmentInternal(\n false,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n };\n\n maybeAddSegment = (\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n ) => {\n return addSegmentInternal(\n true,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n );\n };\n\n addMapping = (map, mapping) => {\n return addMappingInternal(false, map, mapping as Parameters[2]);\n };\n\n maybeAddMapping = (map, mapping) => {\n return addMappingInternal(true, map, mapping as Parameters[2]);\n };\n\n setSourceContent = (map, source, content) => {\n const { _sources: sources, _sourcesContent: sourcesContent } = map;\n sourcesContent[put(sources, source)] = content;\n };\n\n toDecodedMap = (map) => {\n const {\n file,\n sourceRoot,\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n removeEmptyFinalLines(mappings);\n\n return {\n version: 3,\n file: file || undefined,\n names: names.array,\n sourceRoot: sourceRoot || undefined,\n sources: sources.array,\n sourcesContent,\n mappings,\n };\n };\n\n toEncodedMap = (map) => {\n const decoded = toDecodedMap(map);\n return {\n ...decoded,\n mappings: encode(decoded.mappings as SourceMapSegment[][]),\n };\n };\n\n allMappings = (map) => {\n const out: Mapping[] = [];\n const { _mappings: mappings, _sources: sources, _names: names } = map;\n\n for (let i = 0; i < mappings.length; i++) {\n const line = mappings[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generated = { line: i + 1, column: seg[COLUMN] };\n let source: string | undefined = undefined;\n let original: Pos | undefined = undefined;\n let name: string | undefined = undefined;\n\n if (seg.length !== 1) {\n source = sources.array[seg[SOURCES_INDEX]];\n original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };\n\n if (seg.length === 5) name = names.array[seg[NAMES_INDEX]];\n }\n\n out.push({ generated, source, original, name } as Mapping);\n }\n }\n\n return out;\n };\n\n fromMap = (input) => {\n const map = new TraceMap(input);\n const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });\n\n putAll(gen._names, map.names);\n putAll(gen._sources, map.sources as string[]);\n gen._sourcesContent = map.sourcesContent || map.sources.map(() => null);\n gen._mappings = decodedMappings(map) as GenMapping['_mappings'];\n\n return gen;\n };\n\n // Internal helpers\n addSegmentInternal = (\n skipable,\n map,\n genLine,\n genColumn,\n source,\n sourceLine,\n sourceColumn,\n name,\n content,\n ) => {\n const {\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n const line = getLine(mappings, genLine);\n const index = getColumnIndex(line, genColumn);\n\n if (!source) {\n if (skipable && skipSourceless(line, index)) return;\n return insert(line, index, [genColumn]);\n }\n\n // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source\n // isn't nullish.\n assert(sourceLine);\n assert(sourceColumn);\n\n const sourcesIndex = put(sources, source);\n const namesIndex = name ? put(names, name) : NO_NAME;\n if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content ?? null;\n\n if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {\n return;\n }\n\n return insert(\n line,\n index,\n name\n ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]\n : [genColumn, sourcesIndex, sourceLine, sourceColumn],\n );\n };\n }\n}\n\nfunction assert(_val: unknown): asserts _val is T {\n // noop.\n}\n\nfunction getLine(mappings: SourceMapSegment[][], index: number): SourceMapSegment[] {\n for (let i = mappings.length; i <= index; i++) {\n mappings[i] = [];\n }\n return mappings[index];\n}\n\nfunction getColumnIndex(line: SourceMapSegment[], genColumn: number): number {\n let index = line.length;\n for (let i = index - 1; i >= 0; index = i--) {\n const current = line[i];\n if (genColumn >= current[COLUMN]) break;\n }\n return index;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\nfunction removeEmptyFinalLines(mappings: SourceMapSegment[][]) {\n const { length } = mappings;\n let len = length;\n for (let i = len - 1; i >= 0; len = i, i--) {\n if (mappings[i].length > 0) break;\n }\n if (len < length) mappings.length = len;\n}\n\nfunction putAll(strarr: SetArray, array: string[]) {\n for (let i = 0; i < array.length; i++) put(strarr, array[i]);\n}\n\nfunction skipSourceless(line: SourceMapSegment[], index: number): boolean {\n // The start of a line is already sourceless, so adding a sourceless segment to the beginning\n // doesn't generate any useful information.\n if (index === 0) return true;\n\n const prev = line[index - 1];\n // If the previous segment is also sourceless, then adding another sourceless segment doesn't\n // genrate any new information. Else, this segment will end the source/named segment and point to\n // a sourceless position, which is useful.\n return prev.length === 1;\n}\n\nfunction skipSource(\n line: SourceMapSegment[],\n index: number,\n sourcesIndex: number,\n sourceLine: number,\n sourceColumn: number,\n namesIndex: number,\n): boolean {\n // A source/named segment at the start of a line gives position at that genColumn\n if (index === 0) return false;\n\n const prev = line[index - 1];\n\n // If the previous segment is sourceless, then we're transitioning to a source.\n if (prev.length === 1) return false;\n\n // If the previous segment maps to the exact same source position, then this segment doesn't\n // provide any new position information.\n return (\n sourcesIndex === prev[SOURCES_INDEX] &&\n sourceLine === prev[SOURCE_LINE] &&\n sourceColumn === prev[SOURCE_COLUMN] &&\n namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)\n );\n}\n\nfunction addMappingInternal(\n skipable: boolean,\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: S;\n original: S extends string ? Pos : null | undefined;\n name: S extends string ? string | null | undefined : null | undefined;\n content: S extends string ? string | null | undefined : null | undefined;\n },\n) {\n const { generated, source, original, name, content } = mapping;\n if (!source) {\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n null,\n null,\n null,\n null,\n null,\n );\n }\n const s: string = source;\n assert(original);\n return addSegmentInternal(\n skipable,\n map,\n generated.line - 1,\n generated.column,\n s,\n original.line - 1,\n original.column,\n name,\n content,\n );\n}\n"],"names":["addSegment","addMapping","maybeAddSegment","maybeAddMapping","setSourceContent","toDecodedMap","toEncodedMap","fromMap","allMappings","SetArray","put","encode","TraceMap","decodedMappings"],"mappings":";;;;;;IAWO,MAAM,MAAM,GAAG,CAAC,CAAC;IACjB,MAAM,aAAa,GAAG,CAAC,CAAC;IACxB,MAAM,WAAW,GAAG,CAAC,CAAC;IACtB,MA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AAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;QAC/D,IAAI,CAAC,MAAM,EAAE;YACX,OAAO,kBAAkB,CACvB,QAAQ,EACR,GAAG,EACH,SAAS,CAAC,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,IAAI,CACL,CAAC;IACH,KAAA;QACD,MAAM,CAAC,GAAW,MAAM,CAAC;IAEzB,IAAA,OAAO,kBAAkB,CACvB,QAAQ,EACR,GAAG,EACH,SAAS,CAAC,IAAI,GAAG,CAAC,EAClB,SAAS,CAAC,MAAM,EAChB,CAAC,EACD,QAAQ,CAAC,IAAI,GAAG,CAAC,EACjB,QAAQ,CAAC,MAAM,EACf,IAAI,EACJ,OAAO,CACR,CAAC;IACJ;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts new file mode 100644 index 0000000..d510d74 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts @@ -0,0 +1,90 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types'; +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; +export declare type Options = { + file?: string | null; + sourceRoot?: string | null; +}; +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export declare let addSegment: { + (map: GenMapping, genLine: number, genColumn: number, source?: null, sourceLine?: null, sourceColumn?: null, name?: null, content?: null): void; + (map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name?: null, content?: string | null): void; + (map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name: string, content?: string | null): void; +}; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export declare let addMapping: { + (map: GenMapping, mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + content?: null; + }): void; + (map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + content?: string | null; + }): void; + (map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + content?: string | null; + }): void; +}; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +export declare let maybeAddSegment: typeof addSegment; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +export declare let maybeAddMapping: typeof addMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +export declare let setSourceContent: (map: GenMapping, source: string, content: string | null) => void; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let toDecodedMap: (map: GenMapping) => DecodedSourceMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let toEncodedMap: (map: GenMapping) => EncodedSourceMap; +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +export declare let fromMap: (input: SourceMapInput) => GenMapping; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export declare let allMappings: (map: GenMapping) => Mapping[]; +/** + * Provides the state to generate a sourcemap. + */ +export declare class GenMapping { + private _names; + private _sources; + private _sourcesContent; + private _mappings; + file: string | null | undefined; + sourceRoot: string | null | undefined; + constructor({ file, sourceRoot }?: Options); +} diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 0000000..e187ba9 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,12 @@ +declare type GeneratedColumn = number; +declare type SourcesIndex = number; +declare type SourceLine = number; +declare type SourceColumn = number; +declare type NamesIndex = number; +export declare type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export {}; diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts new file mode 100644 index 0000000..b309c81 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts @@ -0,0 +1,35 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; +} +export interface Pos { + line: number; + column: number; +} +export declare type Mapping = { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; +} | { + generated: Pos; + source: string; + original: Pos; + name: string; +} | { + generated: Pos; + source: string; + original: Pos; + name: undefined; +}; diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs new file mode 100644 index 0000000..94d8dce --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs @@ -0,0 +1,242 @@ +// Matches the scheme of a URL, eg "http://" +const schemeRegex = /^[\w+.-]+:\/\//; +/** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ +const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; +/** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ +const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; +var UrlType; +(function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; +})(UrlType || (UrlType = {})); +function isAbsoluteUrl(input) { + return schemeRegex.test(input); +} +function isSchemeRelativeUrl(input) { + return input.startsWith('//'); +} +function isAbsolutePath(input) { + return input.startsWith('/'); +} +function isFileUrl(input) { + return input.startsWith('file:'); +} +function isRelative(input) { + return /^[.?#]/.test(input); +} +function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); +} +function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); +} +function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: UrlType.Absolute, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = UrlType.SchemeRelative; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = UrlType.AbsolutePath; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? UrlType.Query + : input.startsWith('#') + ? UrlType.Hash + : UrlType.RelativePath + : UrlType.Empty; + return url; +} +function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} +function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } +} +/** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ +function normalizePath(url, type) { + const rel = type <= UrlType.RelativePath; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; +} +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== UrlType.Absolute) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case UrlType.Empty: + url.hash = baseUrl.hash; + // fall through + case UrlType.Hash: + url.query = baseUrl.query; + // fall through + case UrlType.Query: + case UrlType.RelativePath: + mergePaths(url, baseUrl); + // fall through + case UrlType.AbsolutePath: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case UrlType.SchemeRelative: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case UrlType.Hash: + case UrlType.Query: + return queryHash; + case UrlType.RelativePath: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case UrlType.AbsolutePath: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +export { resolve as default }; +//# sourceMappingURL=resolve-uri.mjs.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map new file mode 100644 index 0000000..009d043 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.mjs","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nenum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":"AAAA;AACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAErC;;;;;;;;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I,CAAC;QAClB,KAAK,OAAO,CAAC,KAAK;YAChB,OAAO,SAAS,CAAC;QAEnB,KAAK,OAAO,CAAC,YAAY,EAAE;;YAEzB,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAE/B,IAAI,CAAC,IAAI;gBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;YAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;gBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;aAChC;YAED,OAAO,IAAI,GAAG,SAAS,CAAC;SACzB;QAED,KAAK,OAAO,CAAC,YAAY;YACvB,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;QAE9B;YACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;KACpF;AACH;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js new file mode 100644 index 0000000..0700a2d --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js @@ -0,0 +1,250 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.resolveURI = factory()); +})(this, (function () { 'use strict'; + + // Matches the scheme of a URL, eg "http://" + const schemeRegex = /^[\w+.-]+:\/\//; + /** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ + const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; + /** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ + const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; + var UrlType; + (function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; + })(UrlType || (UrlType = {})); + function isAbsoluteUrl(input) { + return schemeRegex.test(input); + } + function isSchemeRelativeUrl(input) { + return input.startsWith('//'); + } + function isAbsolutePath(input) { + return input.startsWith('/'); + } + function isFileUrl(input) { + return input.startsWith('file:'); + } + function isRelative(input) { + return /^[.?#]/.test(input); + } + function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); + } + function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); + } + function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: UrlType.Absolute, + }; + } + function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = UrlType.SchemeRelative; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = UrlType.AbsolutePath; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? UrlType.Query + : input.startsWith('#') + ? UrlType.Hash + : UrlType.RelativePath + : UrlType.Empty; + return url; + } + function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } + } + /** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ + function normalizePath(url, type) { + const rel = type <= UrlType.RelativePath; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; + } + /** + * Attempts to resolve `input` URL/path relative to `base`. + */ + function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== UrlType.Absolute) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case UrlType.Empty: + url.hash = baseUrl.hash; + // fall through + case UrlType.Hash: + url.query = baseUrl.query; + // fall through + case UrlType.Query: + case UrlType.RelativePath: + mergePaths(url, baseUrl); + // fall through + case UrlType.AbsolutePath: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case UrlType.SchemeRelative: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case UrlType.Hash: + case UrlType.Query: + return queryHash; + case UrlType.RelativePath: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case UrlType.AbsolutePath: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } + } + + return resolve; + +})); +//# sourceMappingURL=resolve-uri.umd.js.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map new file mode 100644 index 0000000..a3e39eb --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.umd.js","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nenum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":";;;;;;IAAA;IACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;IAErC;;;;;;;;;;IAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;IAE5F;;;;;;;;;IAS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ChB,OAAO,SAAS,CAAC;YAEnB,KAAK,OAAO,CAAC,YAAY,EAAE;;gBAEzB,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBAE/B,IAAI,CAAC,IAAI;oBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;gBAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;oBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;iBAChC;gBAED,OAAO,IAAI,GAAG,SAAS,CAAC;aACzB;YAED,KAAK,OAAO,CAAC,YAAY;gBACvB,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;YAE9B;gBACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;SACpF;IACH;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts new file mode 100644 index 0000000..b7f0b3b --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts @@ -0,0 +1,4 @@ +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/set-array/dist/set-array.mjs b/node_modules/@jridgewell/set-array/dist/set-array.mjs new file mode 100644 index 0000000..b7f1a9c --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.mjs @@ -0,0 +1,48 @@ +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +let get; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +let put; +/** + * Pops the last added item out of the SetArray. + */ +let pop; +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +class SetArray { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } +} +(() => { + get = (strarr, key) => strarr._indexes[key]; + put = (strarr, key) => { + // The key may or may not be present. If it is present, it's a number. + const index = get(strarr, key); + if (index !== undefined) + return index; + const { array, _indexes: indexes } = strarr; + return (indexes[key] = array.push(key) - 1); + }; + pop = (strarr) => { + const { array, _indexes: indexes } = strarr; + if (array.length === 0) + return; + const last = array.pop(); + indexes[last] = undefined; + }; +})(); + +export { SetArray, get, pop, put }; +//# sourceMappingURL=set-array.mjs.map diff --git a/node_modules/@jridgewell/set-array/dist/set-array.mjs.map b/node_modules/@jridgewell/set-array/dist/set-array.mjs.map new file mode 100644 index 0000000..ead5643 --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"set-array.mjs","sources":["../src/set-array.ts"],"sourcesContent":["/**\n * Gets the index associated with `key` in the backing array, if it is already present.\n */\nexport let get: (strarr: SetArray, key: string) => number | undefined;\n\n/**\n * Puts `key` into the backing array, if it is not already present. Returns\n * the index of the `key` in the backing array.\n */\nexport let put: (strarr: SetArray, key: string) => number;\n\n/**\n * Pops the last added item out of the SetArray.\n */\nexport let pop: (strarr: SetArray) => void;\n\n/**\n * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the\n * index of the `key` in the backing array.\n *\n * This is designed to allow synchronizing a second array with the contents of the backing array,\n * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,\n * and there are never duplicates.\n */\nexport class SetArray {\n private declare _indexes: { [key: string]: number | undefined };\n declare array: readonly string[];\n\n constructor() {\n this._indexes = { __proto__: null } as any;\n this.array = [];\n }\n\n static {\n get = (strarr, key) => strarr._indexes[key];\n\n put = (strarr, key) => {\n // The key may or may not be present. If it is present, it's a number.\n const index = get(strarr, key);\n if (index !== undefined) return index;\n\n const { array, _indexes: indexes } = strarr;\n\n return (indexes[key] = (array as string[]).push(key) - 1);\n };\n\n pop = (strarr) => {\n const { array, _indexes: indexes } = strarr;\n if (array.length === 0) return;\n\n const last = (array as string[]).pop()!;\n indexes[last] = undefined;\n };\n }\n}\n"],"names":[],"mappings":"AAAA;;;IAGW,IAA2D;AAEtE;;;;IAIW,IAA+C;AAE1D;;;IAGW,IAAgC;AAE3C;;;;;;;;MAQa,QAAQ;IAInB;QACE,IAAI,CAAC,QAAQ,GAAG,EAAE,SAAS,EAAE,IAAI,EAAS,CAAC;QAC3C,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;KACjB;CAuBF;AArBC;IACE,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,KAAK,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAE5C,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG;;QAEhB,MAAM,KAAK,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAC/B,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,KAAK,CAAC;QAEtC,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;QAE5C,QAAQ,OAAO,CAAC,GAAG,CAAC,GAAI,KAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;KAC3D,CAAC;IAEF,GAAG,GAAG,CAAC,MAAM;QACX,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;QAC5C,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QAE/B,MAAM,IAAI,GAAI,KAAkB,CAAC,GAAG,EAAG,CAAC;QACxC,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC;KAC3B,CAAC;AACJ,CAAC,GAAA;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/set-array/dist/set-array.umd.js b/node_modules/@jridgewell/set-array/dist/set-array.umd.js new file mode 100644 index 0000000..a1c200a --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.umd.js @@ -0,0 +1,58 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.setArray = {})); +})(this, (function (exports) { 'use strict'; + + /** + * Gets the index associated with `key` in the backing array, if it is already present. + */ + exports.get = void 0; + /** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ + exports.put = void 0; + /** + * Pops the last added item out of the SetArray. + */ + exports.pop = void 0; + /** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ + class SetArray { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } + } + (() => { + exports.get = (strarr, key) => strarr._indexes[key]; + exports.put = (strarr, key) => { + // The key may or may not be present. If it is present, it's a number. + const index = exports.get(strarr, key); + if (index !== undefined) + return index; + const { array, _indexes: indexes } = strarr; + return (indexes[key] = array.push(key) - 1); + }; + exports.pop = (strarr) => { + const { array, _indexes: indexes } = strarr; + if (array.length === 0) + return; + const last = array.pop(); + indexes[last] = undefined; + }; + })(); + + exports.SetArray = SetArray; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=set-array.umd.js.map diff --git a/node_modules/@jridgewell/set-array/dist/set-array.umd.js.map b/node_modules/@jridgewell/set-array/dist/set-array.umd.js.map new file mode 100644 index 0000000..10005af --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"set-array.umd.js","sources":["../src/set-array.ts"],"sourcesContent":["/**\n * Gets the index associated with `key` in the backing array, if it is already present.\n */\nexport let get: (strarr: SetArray, key: string) => number | undefined;\n\n/**\n * Puts `key` into the backing array, if it is not already present. Returns\n * the index of the `key` in the backing array.\n */\nexport let put: (strarr: SetArray, key: string) => number;\n\n/**\n * Pops the last added item out of the SetArray.\n */\nexport let pop: (strarr: SetArray) => void;\n\n/**\n * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the\n * index of the `key` in the backing array.\n *\n * This is designed to allow synchronizing a second array with the contents of the backing array,\n * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,\n * and there are never duplicates.\n */\nexport class SetArray {\n private declare _indexes: { [key: string]: number | undefined };\n declare array: readonly string[];\n\n constructor() {\n this._indexes = { __proto__: null } as any;\n this.array = [];\n }\n\n static {\n get = (strarr, key) => strarr._indexes[key];\n\n put = (strarr, key) => {\n // The key may or may not be present. If it is present, it's a number.\n const index = get(strarr, key);\n if (index !== undefined) return index;\n\n const { array, _indexes: indexes } = strarr;\n\n return (indexes[key] = (array as string[]).push(key) - 1);\n };\n\n pop = (strarr) => {\n const { array, _indexes: indexes } = strarr;\n if (array.length === 0) return;\n\n const last = (array as string[]).pop()!;\n indexes[last] = undefined;\n };\n }\n}\n"],"names":["get","put","pop"],"mappings":";;;;;;IAAA;;;AAGWA,yBAA2D;IAEtE;;;;AAIWC,yBAA+C;IAE1D;;;AAGWC,yBAAgC;IAE3C;;;;;;;;UAQa,QAAQ;QAInB;YACE,IAAI,CAAC,QAAQ,GAAG,EAAE,SAAS,EAAE,IAAI,EAAS,CAAC;YAC3C,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;SACjB;KAuBF;IArBC;QACEF,WAAG,GAAG,CAAC,MAAM,EAAE,GAAG,KAAK,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QAE5CC,WAAG,GAAG,CAAC,MAAM,EAAE,GAAG;;YAEhB,MAAM,KAAK,GAAGD,WAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;YAC/B,IAAI,KAAK,KAAK,SAAS;gBAAE,OAAO,KAAK,CAAC;YAEtC,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;YAE5C,QAAQ,OAAO,CAAC,GAAG,CAAC,GAAI,KAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;SAC3D,CAAC;QAEFE,WAAG,GAAG,CAAC,MAAM;YACX,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;YAC5C,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO;YAE/B,MAAM,IAAI,GAAI,KAAkB,CAAC,GAAG,EAAG,CAAC;YACxC,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC;SAC3B,CAAC;IACJ,CAAC,GAAA;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/set-array/dist/types/set-array.d.ts b/node_modules/@jridgewell/set-array/dist/types/set-array.d.ts new file mode 100644 index 0000000..7ed59b9 --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/types/set-array.d.ts @@ -0,0 +1,26 @@ +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export declare let get: (strarr: SetArray, key: string) => number | undefined; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export declare let put: (strarr: SetArray, key: string) => number; +/** + * Pops the last added item out of the SetArray. + */ +export declare let pop: (strarr: SetArray) => void; +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export declare class SetArray { + private _indexes; + array: readonly string[]; + constructor(); +} diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs new file mode 100644 index 0000000..3dff372 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs @@ -0,0 +1,164 @@ +const comma = ','.charCodeAt(0); +const semicolon = ';'.charCodeAt(0); +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +// Provide a fallback for older environments. +const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; +function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; +} +function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} +function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; +} +function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); +} +function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; +} + +export { decode, encode }; +//# sourceMappingURL=sourcemap-codec.mjs.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map new file mode 100644 index 0000000..236fd12 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.mjs","sources":["../src/sourcemap-codec.ts"],"sourcesContent":["export type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst comma = ','.charCodeAt(0);\nconst semicolon = ';'.charCodeAt(0);\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array) {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array) {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport function decode(mappings: string): SourceMapMappings {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const decoded: SourceMapMappings = [];\n\n let index = 0;\n do {\n const semi = indexOf(mappings, index);\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n state[0] = 0;\n\n for (let i = index; i < semi; i++) {\n let seg: SourceMapSegment;\n\n i = decodeInteger(mappings, i, state, 0); // genColumn\n const col = state[0];\n if (col < lastCol) sorted = false;\n lastCol = col;\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 1); // sourcesIndex\n i = decodeInteger(mappings, i, state, 2); // sourceLine\n i = decodeInteger(mappings, i, state, 3); // sourceColumn\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 4); // namesIndex\n seg = [col, state[1], state[2], state[3], state[4]];\n } else {\n seg = [col, state[1], state[2], state[3]];\n }\n } else {\n seg = [col];\n }\n\n line.push(seg);\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n index = semi + 1;\n } while (index <= mappings.length);\n\n return decoded;\n}\n\nfunction indexOf(mappings: string, index: number): number {\n const idx = mappings.indexOf(';', index);\n return idx === -1 ? mappings.length : idx;\n}\n\nfunction decodeInteger(mappings: string, pos: number, state: SourceMapSegment, j: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = mappings.charCodeAt(pos++);\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n state[j] += value;\n return pos;\n}\n\nfunction hasMoreVlq(mappings: string, i: number, length: number): boolean {\n if (i >= length) return false;\n return mappings.charCodeAt(i) !== comma;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly): string;\nexport function encode(decoded: Readonly): string {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const bufLength = 1024 * 16;\n const subLength = bufLength - 36;\n const buf = new Uint8Array(bufLength);\n const sub = buf.subarray(0, subLength);\n let pos = 0;\n let out = '';\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) {\n if (pos === bufLength) {\n out += td.decode(buf);\n pos = 0;\n }\n buf[pos++] = semicolon;\n }\n if (line.length === 0) continue;\n\n state[0] = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n // We can push up to 5 ints, each int can take at most 7 chars, and we\n // may push a comma.\n if (pos > subLength) {\n out += td.decode(sub);\n buf.copyWithin(0, subLength, pos);\n pos -= subLength;\n }\n if (j > 0) buf[pos++] = comma;\n\n pos = encodeInteger(buf, pos, state, segment, 0); // genColumn\n\n if (segment.length === 1) continue;\n pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex\n pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine\n pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn\n\n if (segment.length === 4) continue;\n pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex\n }\n }\n\n return out + td.decode(buf.subarray(0, pos));\n}\n\nfunction encodeInteger(\n buf: Uint8Array,\n pos: number,\n state: SourceMapSegment,\n segment: SourceMapSegment,\n j: number,\n): number {\n const next = segment[j];\n let num = next - state[j];\n state[j] = next;\n\n num = num < 0 ? (-num << 1) | 1 : num << 1;\n do {\n let clamped = num & 0b011111;\n num >>>= 5;\n if (num > 0) clamped |= 0b100000;\n buf[pos++] = intToChar[clamped];\n } while (num > 0);\n\n return pos;\n}\n"],"names":[],"mappings":"AAOA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;AACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;AACrC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACrC,MAAM,CAA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,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IAC1B,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAEhB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;IAC3C,GAAG;QACD,IAAI,OAAO,GAAG,GAAG,GAAG,QAAQ,CAAC;QAC7B,GAAG,MAAM,CAAC,CAAC;QACX,IAAI,GAAG,GAAG,CAAC;YAAE,OAAO,IAAI,QAAQ,CAAC;QACjC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;KACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;IAElB,OAAO,GAAG,CAAC;AACb;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 0000000..bec92a9 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,175 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.sourcemapCodec = {})); +})(this, (function (exports) { 'use strict'; + + const comma = ','.charCodeAt(0); + const semicolon = ';'.charCodeAt(0); + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + const intToChar = new Uint8Array(64); // 64 possible chars. + const charToInt = new Uint8Array(128); // z is 122 in ASCII + for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; + } + // Provide a fallback for older environments. + const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; + } + function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; + } + function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; + } + function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; + } + function sort(line) { + line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[0] - b[0]; + } + function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); + } + function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; + } + + exports.decode = decode; + exports.encode = encode; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 0000000..b6b2003 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.umd.js","sources":["../src/sourcemap-codec.ts"],"sourcesContent":["export type SourceMapSegment =\n | [number]\n | [number, number, number, number]\n | [number, number, number, number, number];\nexport type SourceMapLine = SourceMapSegment[];\nexport type SourceMapMappings = SourceMapLine[];\n\nconst comma = ','.charCodeAt(0);\nconst semicolon = ';'.charCodeAt(0);\nconst chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst intToChar = new Uint8Array(64); // 64 possible chars.\nconst charToInt = new Uint8Array(128); // z is 122 in ASCII\n\nfor (let i = 0; i < chars.length; i++) {\n const c = chars.charCodeAt(i);\n intToChar[i] = c;\n charToInt[c] = i;\n}\n\n// Provide a fallback for older environments.\nconst td =\n typeof TextDecoder !== 'undefined'\n ? /* #__PURE__ */ new TextDecoder()\n : typeof Buffer !== 'undefined'\n ? {\n decode(buf: Uint8Array) {\n const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);\n return out.toString();\n },\n }\n : {\n decode(buf: Uint8Array) {\n let out = '';\n for (let i = 0; i < buf.length; i++) {\n out += String.fromCharCode(buf[i]);\n }\n return out;\n },\n };\n\nexport function decode(mappings: string): SourceMapMappings {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const decoded: SourceMapMappings = [];\n\n let index = 0;\n do {\n const semi = indexOf(mappings, index);\n const line: SourceMapLine = [];\n let sorted = true;\n let lastCol = 0;\n state[0] = 0;\n\n for (let i = index; i < semi; i++) {\n let seg: SourceMapSegment;\n\n i = decodeInteger(mappings, i, state, 0); // genColumn\n const col = state[0];\n if (col < lastCol) sorted = false;\n lastCol = col;\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 1); // sourcesIndex\n i = decodeInteger(mappings, i, state, 2); // sourceLine\n i = decodeInteger(mappings, i, state, 3); // sourceColumn\n\n if (hasMoreVlq(mappings, i, semi)) {\n i = decodeInteger(mappings, i, state, 4); // namesIndex\n seg = [col, state[1], state[2], state[3], state[4]];\n } else {\n seg = [col, state[1], state[2], state[3]];\n }\n } else {\n seg = [col];\n }\n\n line.push(seg);\n }\n\n if (!sorted) sort(line);\n decoded.push(line);\n index = semi + 1;\n } while (index <= mappings.length);\n\n return decoded;\n}\n\nfunction indexOf(mappings: string, index: number): number {\n const idx = mappings.indexOf(';', index);\n return idx === -1 ? mappings.length : idx;\n}\n\nfunction decodeInteger(mappings: string, pos: number, state: SourceMapSegment, j: number): number {\n let value = 0;\n let shift = 0;\n let integer = 0;\n\n do {\n const c = mappings.charCodeAt(pos++);\n integer = charToInt[c];\n value |= (integer & 31) << shift;\n shift += 5;\n } while (integer & 32);\n\n const shouldNegate = value & 1;\n value >>>= 1;\n\n if (shouldNegate) {\n value = -0x80000000 | -value;\n }\n\n state[j] += value;\n return pos;\n}\n\nfunction hasMoreVlq(mappings: string, i: number, length: number): boolean {\n if (i >= length) return false;\n return mappings.charCodeAt(i) !== comma;\n}\n\nfunction sort(line: SourceMapSegment[]) {\n line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[0] - b[0];\n}\n\nexport function encode(decoded: SourceMapMappings): string;\nexport function encode(decoded: Readonly): string;\nexport function encode(decoded: Readonly): string {\n const state: [number, number, number, number, number] = new Int32Array(5) as any;\n const bufLength = 1024 * 16;\n const subLength = bufLength - 36;\n const buf = new Uint8Array(bufLength);\n const sub = buf.subarray(0, subLength);\n let pos = 0;\n let out = '';\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n if (i > 0) {\n if (pos === bufLength) {\n out += td.decode(buf);\n pos = 0;\n }\n buf[pos++] = semicolon;\n }\n if (line.length === 0) continue;\n\n state[0] = 0;\n\n for (let j = 0; j < line.length; j++) {\n const segment = line[j];\n // We can push up to 5 ints, each int can take at most 7 chars, and we\n // may push a comma.\n if (pos > subLength) {\n out += td.decode(sub);\n buf.copyWithin(0, subLength, pos);\n pos -= subLength;\n }\n if (j > 0) buf[pos++] = comma;\n\n pos = encodeInteger(buf, pos, state, segment, 0); // genColumn\n\n if (segment.length === 1) continue;\n pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex\n pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine\n pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn\n\n if (segment.length === 4) continue;\n pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex\n }\n }\n\n return out + td.decode(buf.subarray(0, pos));\n}\n\nfunction encodeInteger(\n buf: Uint8Array,\n pos: number,\n state: SourceMapSegment,\n segment: SourceMapSegment,\n j: number,\n): number {\n const next = segment[j];\n let num = next - state[j];\n state[j] = next;\n\n num = num < 0 ? (-num << 1) | 1 : num << 1;\n do {\n let clamped = num & 0b011111;\n num >>>= 5;\n if (num > 0) clamped |= 0b100000;\n buf[pos++] = intToChar[clamped];\n } while (num > 0);\n\n return pos;\n}\n"],"names":[],"mappings":";;;;;;IAOA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;IACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IACrC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;IAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACrC,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC9B,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACjB,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAClB;IAED;IACA,MAAM,EAAE,GACN,OAAO,WAAW,KAAK,WAAW;0BACd,IAAI,WAAW,EAAE;UACjC,OAAO,MAAM,KAAK,WAAW;cAC7B;gBACE,MAAM,CAAC,GAAe;oBACpB,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;oBACpE,OA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EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;SACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;QAElB,OAAO,GAAG,CAAC;IACb;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts b/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts new file mode 100644 index 0000000..410d320 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts @@ -0,0 +1,6 @@ +export declare type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export declare type SourceMapLine = SourceMapSegment[]; +export declare type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs new file mode 100644 index 0000000..d3c1a7a --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs @@ -0,0 +1,552 @@ +import { encode, decode } from '@jridgewell/sourcemap-codec'; +import resolveUri from '@jridgewell/resolve-uri'; + +function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; +const REV_GENERATED_LINE = 1; +const REV_GENERATED_COLUMN = 2; + +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; +} + +let found = false; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; +} +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); +} + +// Rebuilds the original source files, with mappings that are ordered by source line/column instead +// of generated line/column. +function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like +// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. +// Numeric properties on objects are magically sorted in ascending order by the engine regardless of +// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending +// order when iterating with for-in. +function buildNullArray() { + return { __proto__: null }; +} + +const AnyMap = function (map, mapUrl) { + const parsed = typeof map === 'string' ? JSON.parse(map) : map; + if (!('sections' in parsed)) + return new TraceMap(parsed, mapUrl); + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + }; + return presortedDecodedMap(joined); +}; +function recurse(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } + else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection(map, mapUrl, mappings, sources, sourcesContent, names, lineOffset + offset.line, columnOffset + offset.column, sl, sc); + } +} +function addSection(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) { + if ('sections' in input) + return recurse(...arguments); + const map = new TraceMap(input, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) + append(sourcesContent, contents); + else + for (let i = 0; i < resolvedSources.length; i++) + sourcesContent.push(null); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. But it may not have any columns that overstep, so we + // still need to check that we don't overstep lines, too. + if (lineI > stopLine) + return; + // The out line may already exist in mappings (if we're continuing the line started by a + // previous section). Or, we may have jumped ahead several lines to start this section. + const out = getLine(mappings, lineI); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (lineI === stopLine && column >= stopColumn) + return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push(seg.length === 4 + ? [column, sourcesIndex, sourceLine, sourceColumn] + : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } +} +function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); +} +function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) + arr[i] = []; + return arr[index]; +} + +const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; +const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +let encodedMappings; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +let decodedMappings; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +let traceSegment; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +let originalPositionFor; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +let generatedPositionFor; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +let allGeneratedPositionsFor; +/** + * Iterates each mapping in generated position order. + */ +let eachMapping; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +let sourceContentFor; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +let presortedDecodedMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let decodedMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let encodedMap; +class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} +(() => { + encodedMappings = (map) => { + var _a; + return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = encode(map._decoded))); + }; + decodedMappings = (map) => { + return (map._decoded || (map._decoded = decode(map._encoded))); + }; + traceSegment = (map, line, column) => { + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + return index === -1 ? null : segments[index]; + }; + originalPositionFor = (map, { line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (index === -1) + return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) + return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null); + }; + allGeneratedPositionsFor = (map, { source, line, column, bias }) => { + // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit. + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); + }; + generatedPositionFor = (map, { source, line, column, bias }) => { + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); + }; + eachMapping = (map, cb) => { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + }; + sourceContentFor = (map, source) => { + const { sources, resolvedSources, sourcesContent } = map; + if (sourcesContent == null) + return null; + let index = sources.indexOf(source); + if (index === -1) + index = resolvedSources.indexOf(source); + return index === -1 ? null : sourcesContent[index]; + }; + presortedDecodedMap = (map, mapUrl) => { + const tracer = new TraceMap(clone(map, []), mapUrl); + tracer._decoded = map.mappings; + return tracer; + }; + decodedMap = (map) => { + return clone(map, decodedMappings(map)); + }; + encodedMap = (map) => { + return clone(map, encodedMappings(map)); + }; + function generatedPosition(map, source, line, column, bias, all) { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return all ? [] : GMapping(null, null); + const generated = (map._bySources || (map._bySources = buildBySources(decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState))))); + const segments = generated[sourceIndex][line]; + if (segments == null) + return all ? [] : GMapping(null, null); + const memo = map._bySourceMemos[sourceIndex]; + if (all) + return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) + return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); + } +})(); +function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + }; +} +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function GMapping(line, column) { + return { line, column }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; +} +function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in + // insertion order) segment that matched. Even if we did respect the bias when tracing, we would + // still need to call `lowerBound()` to find the first segment, which is slower than just looking + // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the + // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to + // match LEAST_UPPER_BOUND. + if (!found && bias === LEAST_UPPER_BOUND) + min++; + if (min === -1 || min === segments.length) + return []; + // We may have found the segment that started at an earlier column. If this is the case, then we + // need to slice all generated segments that match _that_ column, because all such segments span + // to our desired column. + const matchedColumn = found ? column : segments[min][COLUMN]; + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + if (!found) + min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; +} + +export { AnyMap, GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap, allGeneratedPositionsFor, decodedMap, decodedMappings, eachMapping, encodedMap, encodedMappings, generatedPositionFor, originalPositionFor, presortedDecodedMap, sourceContentFor, traceSegment }; +//# sourceMappingURL=trace-mapping.mjs.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map new file mode 100644 index 0000000..8399465 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.mjs","sources":["../src/resolve.ts","../src/strip-filename.ts","../src/sourcemap-segment.ts","../src/sort.ts","../src/binary-search.ts","../src/by-source.ts","../src/any-map.ts","../src/trace-mapping.ts"],"sourcesContent":["import resolveUri from '@jridgewell/resolve-uri';\n\nexport default function resolve(input: string, base: string | undefined): string {\n // The base is always treated as a directory, if it's not empty.\n // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327\n // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401\n if (base && !base.endsWith('/')) base += '/';\n\n return resolveUri(input, base);\n}\n","/**\n * Removes everything after the last \"/\", but leaves the slash.\n */\nexport default function stripFilename(path: string | undefined | null): string {\n if (!path) return '';\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n","type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\ntype GeneratedLine = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n\nexport const REV_GENERATED_LINE = 1;\nexport const REV_GENERATED_COLUMN = 2;\n","import { COLUMN } from './sourcemap-segment';\n\nimport type { SourceMapSegment } from './sourcemap-segment';\n\nexport default function maybeSort(\n mappings: SourceMapSegment[][],\n owned: boolean,\n): SourceMapSegment[][] {\n const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);\n if (unsortedIndex === mappings.length) return mappings;\n\n // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If\n // not, we do not want to modify the consumer's input array.\n if (!owned) mappings = mappings.slice();\n\n for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {\n mappings[i] = sortSegments(mappings[i], owned);\n }\n return mappings;\n}\n\nfunction nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number {\n for (let i = start; i < mappings.length; i++) {\n if (!isSorted(mappings[i])) return i;\n }\n return mappings.length;\n}\n\nfunction isSorted(line: SourceMapSegment[]): boolean {\n for (let j = 1; j < line.length; j++) {\n if (line[j][COLUMN] < line[j - 1][COLUMN]) {\n return false;\n }\n }\n return true;\n}\n\nfunction sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] {\n if (!owned) line = line.slice();\n return line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[COLUMN] - b[COLUMN];\n}\n","import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport { COLUMN } from './sourcemap-segment';\n\nexport type MemoState = {\n lastKey: number;\n lastNeedle: number;\n lastIndex: number;\n};\n\nexport let found = false;\n\n/**\n * A binary search implementation that returns the index if a match is found.\n * If no match is found, then the left-index (the index associated with the item that comes just\n * before the desired index) is returned. To maintain proper sort order, a splice would happen at\n * the next index:\n *\n * ```js\n * const array = [1, 3];\n * const needle = 2;\n * const index = binarySearch(array, needle, (item, needle) => item - needle);\n *\n * assert.equal(index, 0);\n * array.splice(index + 1, 0, needle);\n * assert.deepEqual(array, [1, 2, 3]);\n * ```\n */\nexport function binarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n low: number,\n high: number,\n): number {\n while (low <= high) {\n const mid = low + ((high - low) >> 1);\n const cmp = haystack[mid][COLUMN] - needle;\n\n if (cmp === 0) {\n found = true;\n return mid;\n }\n\n if (cmp < 0) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n found = false;\n return low - 1;\n}\n\nexport function upperBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index + 1; i < haystack.length; index = i++) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function lowerBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index - 1; i >= 0; index = i--) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function memoizedState(): MemoState {\n return {\n lastKey: -1,\n lastNeedle: -1,\n lastIndex: -1,\n };\n}\n\n/**\n * This overly complicated beast is just to record the last tested line/column and the resulting\n * index, allowing us to skip a few tests if mappings are monotonically increasing.\n */\nexport function memoizedBinarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n state: MemoState,\n key: number,\n): number {\n const { lastKey, lastNeedle, lastIndex } = state;\n\n let low = 0;\n let high = haystack.length - 1;\n if (key === lastKey) {\n if (needle === lastNeedle) {\n found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;\n return lastIndex;\n }\n\n if (needle >= lastNeedle) {\n // lastIndex may be -1 if the previous needle was not found.\n low = lastIndex === -1 ? 0 : lastIndex;\n } else {\n high = lastIndex;\n }\n }\n state.lastKey = key;\n state.lastNeedle = needle;\n\n return (state.lastIndex = binarySearch(haystack, needle, low, high));\n}\n","import { COLUMN, SOURCES_INDEX, SOURCE_LINE, SOURCE_COLUMN } from './sourcemap-segment';\nimport { memoizedBinarySearch, upperBound } from './binary-search';\n\nimport type { ReverseSegment, SourceMapSegment } from './sourcemap-segment';\nimport type { MemoState } from './binary-search';\n\nexport type Source = {\n __proto__: null;\n [line: number]: Exclude[];\n};\n\n// Rebuilds the original source files, with mappings that are ordered by source line/column instead\n// of generated line/column.\nexport default function buildBySources(\n decoded: readonly SourceMapSegment[][],\n memos: MemoState[],\n): Source[] {\n const sources: Source[] = memos.map(buildNullArray);\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n if (seg.length === 1) continue;\n\n const sourceIndex = seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n const originalSource = sources[sourceIndex];\n const originalLine = (originalSource[sourceLine] ||= []);\n const memo = memos[sourceIndex];\n\n // The binary search either found a match, or it found the left-index just before where the\n // segment should go. Either way, we want to insert after that. And there may be multiple\n // generated segments associated with an original location, so there may need to move several\n // indexes before we find where we need to insert.\n const index = upperBound(\n originalLine,\n sourceColumn,\n memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine),\n );\n\n insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]);\n }\n }\n\n return sources;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\n// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like\n// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.\n// Numeric properties on objects are magically sorted in ascending order by the engine regardless of\n// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending\n// order when iterating with for-in.\nfunction buildNullArray(): T {\n return { __proto__: null } as T;\n}\n","import { TraceMap, presortedDecodedMap, decodedMappings } from './trace-mapping';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type {\n Section,\n SectionedSourceMap,\n DecodedSourceMap,\n SectionedSourceMapInput,\n Ro,\n} from './types';\nimport type { SourceMapSegment } from './sourcemap-segment';\n\ntype AnyMap = {\n new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n};\n\nexport const AnyMap: AnyMap = function (map, mapUrl) {\n const parsed =\n typeof map === 'string' ? (JSON.parse(map) as Exclude) : map;\n\n if (!('sections' in parsed)) return new TraceMap(parsed, mapUrl);\n\n const mappings: SourceMapSegment[][] = [];\n const sources: string[] = [];\n const sourcesContent: (string | null)[] = [];\n const names: string[] = [];\n\n recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity);\n\n const joined: DecodedSourceMap = {\n version: 3,\n file: parsed.file,\n names,\n sources,\n sourcesContent,\n mappings,\n };\n\n return presortedDecodedMap(joined);\n} as AnyMap;\n\nfunction recurse(\n input: Ro,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const { sections } = input;\n for (let i = 0; i < sections.length; i++) {\n const { map, offset } = sections[i];\n\n let sl = stopLine;\n let sc = stopColumn;\n if (i + 1 < sections.length) {\n const nextOffset = sections[i + 1].offset;\n sl = Math.min(stopLine, lineOffset + nextOffset.line);\n\n if (sl === stopLine) {\n sc = Math.min(stopColumn, columnOffset + nextOffset.column);\n } else if (sl < stopLine) {\n sc = columnOffset + nextOffset.column;\n }\n }\n\n addSection(\n map,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n lineOffset + offset.line,\n columnOffset + offset.column,\n sl,\n sc,\n );\n }\n}\n\nfunction addSection(\n input: Ro,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n if ('sections' in input) return recurse(...(arguments as unknown as Parameters));\n\n const map = new TraceMap(input, mapUrl);\n const sourcesOffset = sources.length;\n const namesOffset = names.length;\n const decoded = decodedMappings(map);\n const { resolvedSources, sourcesContent: contents } = map;\n\n append(sources, resolvedSources);\n append(names, map.names);\n if (contents) append(sourcesContent, contents);\n else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null);\n\n for (let i = 0; i < decoded.length; i++) {\n const lineI = lineOffset + i;\n\n // We can only add so many lines before we step into the range that the next section's map\n // controls. When we get to the last line, then we'll start checking the segments to see if\n // they've crossed into the column range. But it may not have any columns that overstep, so we\n // still need to check that we don't overstep lines, too.\n if (lineI > stopLine) return;\n\n // The out line may already exist in mappings (if we're continuing the line started by a\n // previous section). Or, we may have jumped ahead several lines to start this section.\n const out = getLine(mappings, lineI);\n // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the\n // map can be multiple lines), it doesn't.\n const cOffset = i === 0 ? columnOffset : 0;\n\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n const column = cOffset + seg[COLUMN];\n\n // If this segment steps into the column range that the next section's map controls, we need\n // to stop early.\n if (lineI === stopLine && column >= stopColumn) return;\n\n if (seg.length === 1) {\n out.push([column]);\n continue;\n }\n\n const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n out.push(\n seg.length === 4\n ? [column, sourcesIndex, sourceLine, sourceColumn]\n : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]],\n );\n }\n }\n}\n\nfunction append(arr: T[], other: T[]) {\n for (let i = 0; i < other.length; i++) arr.push(other[i]);\n}\n\nfunction getLine(arr: T[][], index: number): T[] {\n for (let i = arr.length; i <= index; i++) arr[i] = [];\n return arr[index];\n}\n","import { encode, decode } from '@jridgewell/sourcemap-codec';\n\nimport resolve from './resolve';\nimport stripFilename from './strip-filename';\nimport maybeSort from './sort';\nimport buildBySources from './by-source';\nimport {\n memoizedState,\n memoizedBinarySearch,\n upperBound,\n lowerBound,\n found as bsFound,\n} from './binary-search';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n REV_GENERATED_LINE,\n REV_GENERATED_COLUMN,\n} from './sourcemap-segment';\n\nimport type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport type {\n SourceMapV3,\n DecodedSourceMap,\n EncodedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n SourceMapInput,\n Needle,\n SourceNeedle,\n SourceMap,\n EachMapping,\n Bias,\n} from './types';\nimport type { Source } from './by-source';\nimport type { MemoState } from './binary-search';\n\nexport type { SourceMapSegment } from './sourcemap-segment';\nexport type * from './types';\n\nconst LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';\nconst COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';\n\nexport const LEAST_UPPER_BOUND = -1;\nexport const GREATEST_LOWER_BOUND = 1;\n\n/**\n * Returns the encoded (VLQ string) form of the SourceMap's mappings field.\n */\nexport let encodedMappings: (map: TraceMap) => EncodedSourceMap['mappings'];\n\n/**\n * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.\n */\nexport let decodedMappings: (map: TraceMap) => Readonly;\n\n/**\n * A low-level API to find the segment associated with a generated line/column (think, from a\n * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.\n */\nexport let traceSegment: (\n map: TraceMap,\n line: number,\n column: number,\n) => Readonly | null;\n\n/**\n * A higher-level API to find the source/line/column associated with a generated line/column\n * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in\n * `source-map` library.\n */\nexport let originalPositionFor: (\n map: TraceMap,\n needle: Needle,\n) => OriginalMapping | InvalidOriginalMapping;\n\n/**\n * Finds the generated line/column position of the provided source/line/column source position.\n */\nexport let generatedPositionFor: (\n map: TraceMap,\n needle: SourceNeedle,\n) => GeneratedMapping | InvalidGeneratedMapping;\n\n/**\n * Finds all generated line/column positions of the provided source/line/column source position.\n */\nexport let allGeneratedPositionsFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping[];\n\n/**\n * Iterates each mapping in generated position order.\n */\nexport let eachMapping: (map: TraceMap, cb: (mapping: EachMapping) => void) => void;\n\n/**\n * Retrieves the source content for a particular source, if its found. Returns null if not.\n */\nexport let sourceContentFor: (map: TraceMap, source: string) => string | null;\n\n/**\n * A helper that skips sorting of the input map's mappings array, which can be expensive for larger\n * maps.\n */\nexport let presortedDecodedMap: (map: DecodedSourceMap, mapUrl?: string) => TraceMap;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let decodedMap: (\n map: TraceMap,\n) => Omit & { mappings: readonly SourceMapSegment[][] };\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let encodedMap: (map: TraceMap) => EncodedSourceMap;\n\nexport { AnyMap } from './any-map';\n\nexport class TraceMap implements SourceMap {\n declare version: SourceMapV3['version'];\n declare file: SourceMapV3['file'];\n declare names: SourceMapV3['names'];\n declare sourceRoot: SourceMapV3['sourceRoot'];\n declare sources: SourceMapV3['sources'];\n declare sourcesContent: SourceMapV3['sourcesContent'];\n\n declare resolvedSources: string[];\n private declare _encoded: string | undefined;\n\n private declare _decoded: SourceMapSegment[][] | undefined;\n private declare _decodedMemo: MemoState;\n\n private declare _bySources: Source[] | undefined;\n private declare _bySourceMemos: MemoState[] | undefined;\n\n constructor(map: SourceMapInput, mapUrl?: string | null) {\n const isString = typeof map === 'string';\n\n if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap;\n\n const parsed = (isString ? JSON.parse(map) : map) as DecodedSourceMap | EncodedSourceMap;\n\n const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;\n this.version = version;\n this.file = file;\n this.names = names || [];\n this.sourceRoot = sourceRoot;\n this.sources = sources;\n this.sourcesContent = sourcesContent;\n\n const from = resolve(sourceRoot || '', stripFilename(mapUrl));\n this.resolvedSources = sources.map((s) => resolve(s || '', from));\n\n const { mappings } = parsed;\n if (typeof mappings === 'string') {\n this._encoded = mappings;\n this._decoded = undefined;\n } else {\n this._encoded = undefined;\n this._decoded = maybeSort(mappings, isString);\n }\n\n this._decodedMemo = memoizedState();\n this._bySources = undefined;\n this._bySourceMemos = undefined;\n }\n\n static {\n encodedMappings = (map) => {\n return (map._encoded ??= encode(map._decoded!));\n };\n\n decodedMappings = (map) => {\n return (map._decoded ||= decode(map._encoded!));\n };\n\n traceSegment = (map, line, column) => {\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return null;\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n map._decodedMemo,\n line,\n column,\n GREATEST_LOWER_BOUND,\n );\n\n return index === -1 ? null : segments[index];\n };\n\n originalPositionFor = (map, { line, column, bias }) => {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return OMapping(null, null, null, null);\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n map._decodedMemo,\n line,\n column,\n bias || GREATEST_LOWER_BOUND,\n );\n\n if (index === -1) return OMapping(null, null, null, null);\n\n const segment = segments[index];\n if (segment.length === 1) return OMapping(null, null, null, null);\n\n const { names, resolvedSources } = map;\n return OMapping(\n resolvedSources[segment[SOURCES_INDEX]],\n segment[SOURCE_LINE] + 1,\n segment[SOURCE_COLUMN],\n segment.length === 5 ? names[segment[NAMES_INDEX]] : null,\n );\n };\n\n allGeneratedPositionsFor = (map, { source, line, column, bias }) => {\n // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit.\n return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);\n };\n\n generatedPositionFor = (map, { source, line, column, bias }) => {\n return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);\n };\n\n eachMapping = (map, cb) => {\n const decoded = decodedMappings(map);\n const { names, resolvedSources } = map;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generatedLine = i + 1;\n const generatedColumn = seg[0];\n let source = null;\n let originalLine = null;\n let originalColumn = null;\n let name = null;\n if (seg.length !== 1) {\n source = resolvedSources[seg[1]];\n originalLine = seg[2] + 1;\n originalColumn = seg[3];\n }\n if (seg.length === 5) name = names[seg[4]];\n\n cb({\n generatedLine,\n generatedColumn,\n source,\n originalLine,\n originalColumn,\n name,\n } as EachMapping);\n }\n }\n };\n\n sourceContentFor = (map, source) => {\n const { sources, resolvedSources, sourcesContent } = map;\n if (sourcesContent == null) return null;\n\n let index = sources.indexOf(source);\n if (index === -1) index = resolvedSources.indexOf(source);\n\n return index === -1 ? null : sourcesContent[index];\n };\n\n presortedDecodedMap = (map, mapUrl) => {\n const tracer = new TraceMap(clone(map, []), mapUrl);\n tracer._decoded = map.mappings;\n return tracer;\n };\n\n decodedMap = (map) => {\n return clone(map, decodedMappings(map));\n };\n\n encodedMap = (map) => {\n return clone(map, encodedMappings(map));\n };\n\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: false,\n ): GeneratedMapping | InvalidGeneratedMapping;\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: true,\n ): GeneratedMapping[];\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: boolean,\n ): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const { sources, resolvedSources } = map;\n let sourceIndex = sources.indexOf(source);\n if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source);\n if (sourceIndex === -1) return all ? [] : GMapping(null, null);\n\n const generated = (map._bySources ||= buildBySources(\n decodedMappings(map),\n (map._bySourceMemos = sources.map(memoizedState)),\n ));\n\n const segments = generated[sourceIndex][line];\n if (segments == null) return all ? [] : GMapping(null, null);\n\n const memo = map._bySourceMemos![sourceIndex];\n\n if (all) return sliceGeneratedPositions(segments, memo, line, column, bias);\n\n const index = traceSegmentInternal(segments, memo, line, column, bias);\n if (index === -1) return GMapping(null, null);\n\n const segment = segments[index];\n return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);\n }\n }\n}\n\nfunction clone(\n map: TraceMap | DecodedSourceMap | EncodedSourceMap,\n mappings: T,\n): T extends string ? EncodedSourceMap : DecodedSourceMap {\n return {\n version: map.version,\n file: map.file,\n names: map.names,\n sourceRoot: map.sourceRoot,\n sources: map.sources,\n sourcesContent: map.sourcesContent,\n mappings,\n } as any;\n}\n\nfunction OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping;\nfunction OMapping(\n source: string,\n line: number,\n column: number,\n name: string | null,\n): OriginalMapping;\nfunction OMapping(\n source: string | null,\n line: number | null,\n column: number | null,\n name: string | null,\n): OriginalMapping | InvalidOriginalMapping {\n return { source, line, column, name } as any;\n}\n\nfunction GMapping(line: null, column: null): InvalidGeneratedMapping;\nfunction GMapping(line: number, column: number): GeneratedMapping;\nfunction GMapping(\n line: number | null,\n column: number | null,\n): GeneratedMapping | InvalidGeneratedMapping {\n return { line, column } as any;\n}\n\nfunction traceSegmentInternal(\n segments: SourceMapSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: SourceMapSegment[] | ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number {\n let index = memoizedBinarySearch(segments, column, memo, line);\n if (bsFound) {\n index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);\n } else if (bias === LEAST_UPPER_BOUND) index++;\n\n if (index === -1 || index === segments.length) return -1;\n return index;\n}\n\nfunction sliceGeneratedPositions(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): GeneratedMapping[] {\n let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);\n\n // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in\n // insertion order) segment that matched. Even if we did respect the bias when tracing, we would\n // still need to call `lowerBound()` to find the first segment, which is slower than just looking\n // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the\n // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to\n // match LEAST_UPPER_BOUND.\n if (!bsFound && bias === LEAST_UPPER_BOUND) min++;\n\n if (min === -1 || min === segments.length) return [];\n\n // We may have found the segment that started at an earlier column. If this is the case, then we\n // need to slice all generated segments that match _that_ column, because all such segments span\n // to our desired column.\n const matchedColumn = bsFound ? column : segments[min][COLUMN];\n\n // The binary search is not guaranteed to find the lower bound when a match wasn't found.\n if (!bsFound) min = lowerBound(segments, matchedColumn, min);\n const max = upperBound(segments, matchedColumn, min);\n\n const result = [];\n for (; min <= max; min++) {\n const segment = segments[min];\n result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));\n }\n return result;\n}\n"],"names":["bsFound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AO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,uBAAuB,CAC9B,QAA0B,EAC1B,IAAe,EACf,IAAY,EACZ,MAAc,EACd,IAAU,EAAA;AAEV,IAAA,IAAI,GAAG,GAAG,oBAAoB,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,oBAAoB,CAAC,CAAC;;;;;;;AAQnF,IAAA,IAAI,CAACA,KAAO,IAAI,IAAI,KAAK,iBAAiB;AAAE,QAAA,GAAG,EAAE,CAAC;IAElD,IAAI,GAAG,KAAK,CAAC,CAAC,IAAI,GAAG,KAAK,QAAQ,CAAC,MAAM;AAAE,QAAA,OAAO,EAAE,CAAC;;;;AAKrD,IAAA,MAAM,aAAa,GAAGA,KAAO,GAAG,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;;AAG/D,IAAA,IAAI,CAACA,KAAO;QAAE,GAAG,GAAG,UAAU,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;IAC7D,MAAM,GAAG,GAAG,UAAU,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;IAErD,MAAM,MAAM,GAAG,EAAE,CAAC;AAClB,IAAA,OAAO,GAAG,IAAI,GAAG,EAAE,GAAG,EAAE,EAAE;AACxB,QAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;AAC9B,QAAA,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;KACvF;AACD,IAAA,OAAO,MAAM,CAAC;AAChB;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js new file mode 100644 index 0000000..c373bc3 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js @@ -0,0 +1,560 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/sourcemap-codec'), require('@jridgewell/resolve-uri')) : + typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/sourcemap-codec', '@jridgewell/resolve-uri'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.traceMapping = {}, global.sourcemapCodec, global.resolveURI)); +})(this, (function (exports, sourcemapCodec, resolveUri) { 'use strict'; + + function resolve(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolveUri(input, base); + } + + /** + * Removes everything after the last "/", but leaves the slash. + */ + function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + + const COLUMN = 0; + const SOURCES_INDEX = 1; + const SOURCE_LINE = 2; + const SOURCE_COLUMN = 3; + const NAMES_INDEX = 4; + const REV_GENERATED_LINE = 1; + const REV_GENERATED_COLUMN = 2; + + function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; + } + function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; + } + function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; + } + function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; + } + + let found = false; + /** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ + function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; + } + function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; + } + /** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ + function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); + } + + // Rebuilds the original source files, with mappings that are ordered by source line/column instead + // of generated line/column. + function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; + } + function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; + } + // Null arrays allow us to use ordered index keys without actually allocating contiguous memory like + // a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. + // Numeric properties on objects are magically sorted in ascending order by the engine regardless of + // the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending + // order when iterating with for-in. + function buildNullArray() { + return { __proto__: null }; + } + + const AnyMap = function (map, mapUrl) { + const parsed = typeof map === 'string' ? JSON.parse(map) : map; + if (!('sections' in parsed)) + return new TraceMap(parsed, mapUrl); + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + }; + return exports.presortedDecodedMap(joined); + }; + function recurse(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } + else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection(map, mapUrl, mappings, sources, sourcesContent, names, lineOffset + offset.line, columnOffset + offset.column, sl, sc); + } + } + function addSection(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) { + if ('sections' in input) + return recurse(...arguments); + const map = new TraceMap(input, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = exports.decodedMappings(map); + const { resolvedSources, sourcesContent: contents } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) + append(sourcesContent, contents); + else + for (let i = 0; i < resolvedSources.length; i++) + sourcesContent.push(null); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. But it may not have any columns that overstep, so we + // still need to check that we don't overstep lines, too. + if (lineI > stopLine) + return; + // The out line may already exist in mappings (if we're continuing the line started by a + // previous section). Or, we may have jumped ahead several lines to start this section. + const out = getLine(mappings, lineI); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (lineI === stopLine && column >= stopColumn) + return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push(seg.length === 4 + ? [column, sourcesIndex, sourceLine, sourceColumn] + : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } + } + function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); + } + function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) + arr[i] = []; + return arr[index]; + } + + const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; + const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; + const LEAST_UPPER_BOUND = -1; + const GREATEST_LOWER_BOUND = 1; + /** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ + exports.encodedMappings = void 0; + /** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ + exports.decodedMappings = void 0; + /** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ + exports.traceSegment = void 0; + /** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ + exports.originalPositionFor = void 0; + /** + * Finds the generated line/column position of the provided source/line/column source position. + */ + exports.generatedPositionFor = void 0; + /** + * Finds all generated line/column positions of the provided source/line/column source position. + */ + exports.allGeneratedPositionsFor = void 0; + /** + * Iterates each mapping in generated position order. + */ + exports.eachMapping = void 0; + /** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ + exports.sourceContentFor = void 0; + /** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ + exports.presortedDecodedMap = void 0; + /** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.decodedMap = void 0; + /** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.encodedMap = void 0; + class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } + } + (() => { + exports.encodedMappings = (map) => { + var _a; + return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = sourcemapCodec.encode(map._decoded))); + }; + exports.decodedMappings = (map) => { + return (map._decoded || (map._decoded = sourcemapCodec.decode(map._encoded))); + }; + exports.traceSegment = (map, line, column) => { + const decoded = exports.decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + return index === -1 ? null : segments[index]; + }; + exports.originalPositionFor = (map, { line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = exports.decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (index === -1) + return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) + return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null); + }; + exports.allGeneratedPositionsFor = (map, { source, line, column, bias }) => { + // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit. + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); + }; + exports.generatedPositionFor = (map, { source, line, column, bias }) => { + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); + }; + exports.eachMapping = (map, cb) => { + const decoded = exports.decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + }; + exports.sourceContentFor = (map, source) => { + const { sources, resolvedSources, sourcesContent } = map; + if (sourcesContent == null) + return null; + let index = sources.indexOf(source); + if (index === -1) + index = resolvedSources.indexOf(source); + return index === -1 ? null : sourcesContent[index]; + }; + exports.presortedDecodedMap = (map, mapUrl) => { + const tracer = new TraceMap(clone(map, []), mapUrl); + tracer._decoded = map.mappings; + return tracer; + }; + exports.decodedMap = (map) => { + return clone(map, exports.decodedMappings(map)); + }; + exports.encodedMap = (map) => { + return clone(map, exports.encodedMappings(map)); + }; + function generatedPosition(map, source, line, column, bias, all) { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return all ? [] : GMapping(null, null); + const generated = (map._bySources || (map._bySources = buildBySources(exports.decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState))))); + const segments = generated[sourceIndex][line]; + if (segments == null) + return all ? [] : GMapping(null, null); + const memo = map._bySourceMemos[sourceIndex]; + if (all) + return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) + return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); + } + })(); + function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + }; + } + function OMapping(source, line, column, name) { + return { source, line, column, name }; + } + function GMapping(line, column) { + return { line, column }; + } + function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; + } + function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in + // insertion order) segment that matched. Even if we did respect the bias when tracing, we would + // still need to call `lowerBound()` to find the first segment, which is slower than just looking + // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the + // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to + // match LEAST_UPPER_BOUND. + if (!found && bias === LEAST_UPPER_BOUND) + min++; + if (min === -1 || min === segments.length) + return []; + // We may have found the segment that started at an earlier column. If this is the case, then we + // need to slice all generated segments that match _that_ column, because all such segments span + // to our desired column. + const matchedColumn = found ? column : segments[min][COLUMN]; + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + if (!found) + min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; + } + + exports.AnyMap = AnyMap; + exports.GREATEST_LOWER_BOUND = GREATEST_LOWER_BOUND; + exports.LEAST_UPPER_BOUND = LEAST_UPPER_BOUND; + exports.TraceMap = TraceMap; + +})); +//# sourceMappingURL=trace-mapping.umd.js.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map new file mode 100644 index 0000000..2c25b90 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.umd.js","sources":["../src/resolve.ts","../src/strip-filename.ts","../src/sourcemap-segment.ts","../src/sort.ts","../src/binary-search.ts","../src/by-source.ts","../src/any-map.ts","../src/trace-mapping.ts"],"sourcesContent":["import resolveUri from '@jridgewell/resolve-uri';\n\nexport default function resolve(input: string, base: string | undefined): string {\n // The base is always treated as a directory, if it's not empty.\n // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327\n // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401\n if (base && !base.endsWith('/')) base += '/';\n\n return resolveUri(input, base);\n}\n","/**\n * Removes everything after the last \"/\", but leaves the slash.\n */\nexport default function stripFilename(path: string | undefined | null): string {\n if (!path) return '';\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n","type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\ntype GeneratedLine = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n\nexport const REV_GENERATED_LINE = 1;\nexport const REV_GENERATED_COLUMN = 2;\n","import { COLUMN } from './sourcemap-segment';\n\nimport type { SourceMapSegment } from './sourcemap-segment';\n\nexport default function maybeSort(\n mappings: SourceMapSegment[][],\n owned: boolean,\n): SourceMapSegment[][] {\n const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);\n if (unsortedIndex === mappings.length) return mappings;\n\n // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If\n // not, we do not want to modify the consumer's input array.\n if (!owned) mappings = mappings.slice();\n\n for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {\n mappings[i] = sortSegments(mappings[i], owned);\n }\n return mappings;\n}\n\nfunction nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number {\n for (let i = start; i < mappings.length; i++) {\n if (!isSorted(mappings[i])) return i;\n }\n return mappings.length;\n}\n\nfunction isSorted(line: SourceMapSegment[]): boolean {\n for (let j = 1; j < line.length; j++) {\n if (line[j][COLUMN] < line[j - 1][COLUMN]) {\n return false;\n }\n }\n return true;\n}\n\nfunction sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] {\n if (!owned) line = line.slice();\n return line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[COLUMN] - b[COLUMN];\n}\n","import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport { COLUMN } from './sourcemap-segment';\n\nexport type MemoState = {\n lastKey: number;\n lastNeedle: number;\n lastIndex: number;\n};\n\nexport let found = false;\n\n/**\n * A binary search implementation that returns the index if a match is found.\n * If no match is found, then the left-index (the index associated with the item that comes just\n * before the desired index) is returned. To maintain proper sort order, a splice would happen at\n * the next index:\n *\n * ```js\n * const array = [1, 3];\n * const needle = 2;\n * const index = binarySearch(array, needle, (item, needle) => item - needle);\n *\n * assert.equal(index, 0);\n * array.splice(index + 1, 0, needle);\n * assert.deepEqual(array, [1, 2, 3]);\n * ```\n */\nexport function binarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n low: number,\n high: number,\n): number {\n while (low <= high) {\n const mid = low + ((high - low) >> 1);\n const cmp = haystack[mid][COLUMN] - needle;\n\n if (cmp === 0) {\n found = true;\n return mid;\n }\n\n if (cmp < 0) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n found = false;\n return low - 1;\n}\n\nexport function upperBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index + 1; i < haystack.length; index = i++) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function lowerBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index - 1; i >= 0; index = i--) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function memoizedState(): MemoState {\n return {\n lastKey: -1,\n lastNeedle: -1,\n lastIndex: -1,\n };\n}\n\n/**\n * This overly complicated beast is just to record the last tested line/column and the resulting\n * index, allowing us to skip a few tests if mappings are monotonically increasing.\n */\nexport function memoizedBinarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n state: MemoState,\n key: number,\n): number {\n const { lastKey, lastNeedle, lastIndex } = state;\n\n let low = 0;\n let high = haystack.length - 1;\n if (key === lastKey) {\n if (needle === lastNeedle) {\n found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;\n return lastIndex;\n }\n\n if (needle >= lastNeedle) {\n // lastIndex may be -1 if the previous needle was not found.\n low = lastIndex === -1 ? 0 : lastIndex;\n } else {\n high = lastIndex;\n }\n }\n state.lastKey = key;\n state.lastNeedle = needle;\n\n return (state.lastIndex = binarySearch(haystack, needle, low, high));\n}\n","import { COLUMN, SOURCES_INDEX, SOURCE_LINE, SOURCE_COLUMN } from './sourcemap-segment';\nimport { memoizedBinarySearch, upperBound } from './binary-search';\n\nimport type { ReverseSegment, SourceMapSegment } from './sourcemap-segment';\nimport type { MemoState } from './binary-search';\n\nexport type Source = {\n __proto__: null;\n [line: number]: Exclude[];\n};\n\n// Rebuilds the original source files, with mappings that are ordered by source line/column instead\n// of generated line/column.\nexport default function buildBySources(\n decoded: readonly SourceMapSegment[][],\n memos: MemoState[],\n): Source[] {\n const sources: Source[] = memos.map(buildNullArray);\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n if (seg.length === 1) continue;\n\n const sourceIndex = seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n const originalSource = sources[sourceIndex];\n const originalLine = (originalSource[sourceLine] ||= []);\n const memo = memos[sourceIndex];\n\n // The binary search either found a match, or it found the left-index just before where the\n // segment should go. Either way, we want to insert after that. And there may be multiple\n // generated segments associated with an original location, so there may need to move several\n // indexes before we find where we need to insert.\n const index = upperBound(\n originalLine,\n sourceColumn,\n memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine),\n );\n\n insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]);\n }\n }\n\n return sources;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\n// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like\n// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.\n// Numeric properties on objects are magically sorted in ascending order by the engine regardless of\n// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending\n// order when iterating with for-in.\nfunction buildNullArray(): T {\n return { __proto__: null } as T;\n}\n","import { TraceMap, presortedDecodedMap, decodedMappings } from './trace-mapping';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type {\n Section,\n SectionedSourceMap,\n DecodedSourceMap,\n SectionedSourceMapInput,\n Ro,\n} from './types';\nimport type { SourceMapSegment } from './sourcemap-segment';\n\ntype AnyMap = {\n new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n};\n\nexport const AnyMap: AnyMap = function (map, mapUrl) {\n const parsed =\n typeof map === 'string' ? (JSON.parse(map) as Exclude) : map;\n\n if (!('sections' in parsed)) return new TraceMap(parsed, mapUrl);\n\n const mappings: SourceMapSegment[][] = [];\n const sources: string[] = [];\n const sourcesContent: (string | null)[] = [];\n const names: string[] = [];\n\n recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity);\n\n const joined: DecodedSourceMap = {\n version: 3,\n file: parsed.file,\n names,\n sources,\n sourcesContent,\n mappings,\n };\n\n return presortedDecodedMap(joined);\n} as AnyMap;\n\nfunction recurse(\n input: Ro,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const { sections } = input;\n for (let i = 0; i < sections.length; i++) {\n const { map, offset } = sections[i];\n\n let sl = stopLine;\n let sc = stopColumn;\n if (i + 1 < sections.length) {\n const nextOffset = sections[i + 1].offset;\n sl = Math.min(stopLine, lineOffset + nextOffset.line);\n\n if (sl === stopLine) {\n sc = Math.min(stopColumn, columnOffset + nextOffset.column);\n } else if (sl < stopLine) {\n sc = columnOffset + nextOffset.column;\n }\n }\n\n addSection(\n map,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n lineOffset + offset.line,\n columnOffset + offset.column,\n sl,\n sc,\n );\n }\n}\n\nfunction addSection(\n input: Ro,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n if ('sections' in input) return recurse(...(arguments as unknown as Parameters));\n\n const map = new TraceMap(input, mapUrl);\n const sourcesOffset = sources.length;\n const namesOffset = names.length;\n const decoded = decodedMappings(map);\n const { resolvedSources, sourcesContent: contents } = map;\n\n append(sources, resolvedSources);\n append(names, map.names);\n if (contents) append(sourcesContent, contents);\n else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null);\n\n for (let i = 0; i < decoded.length; i++) {\n const lineI = lineOffset + i;\n\n // We can only add so many lines before we step into the range that the next section's map\n // controls. When we get to the last line, then we'll start checking the segments to see if\n // they've crossed into the column range. But it may not have any columns that overstep, so we\n // still need to check that we don't overstep lines, too.\n if (lineI > stopLine) return;\n\n // The out line may already exist in mappings (if we're continuing the line started by a\n // previous section). Or, we may have jumped ahead several lines to start this section.\n const out = getLine(mappings, lineI);\n // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the\n // map can be multiple lines), it doesn't.\n const cOffset = i === 0 ? columnOffset : 0;\n\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n const column = cOffset + seg[COLUMN];\n\n // If this segment steps into the column range that the next section's map controls, we need\n // to stop early.\n if (lineI === stopLine && column >= stopColumn) return;\n\n if (seg.length === 1) {\n out.push([column]);\n continue;\n }\n\n const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n out.push(\n seg.length === 4\n ? [column, sourcesIndex, sourceLine, sourceColumn]\n : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]],\n );\n }\n }\n}\n\nfunction append(arr: T[], other: T[]) {\n for (let i = 0; i < other.length; i++) arr.push(other[i]);\n}\n\nfunction getLine(arr: T[][], index: number): T[] {\n for (let i = arr.length; i <= index; i++) arr[i] = [];\n return arr[index];\n}\n","import { encode, decode } from '@jridgewell/sourcemap-codec';\n\nimport resolve from './resolve';\nimport stripFilename from './strip-filename';\nimport maybeSort from './sort';\nimport buildBySources from './by-source';\nimport {\n memoizedState,\n memoizedBinarySearch,\n upperBound,\n lowerBound,\n found as bsFound,\n} from './binary-search';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n REV_GENERATED_LINE,\n REV_GENERATED_COLUMN,\n} from './sourcemap-segment';\n\nimport type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport type {\n SourceMapV3,\n DecodedSourceMap,\n EncodedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n SourceMapInput,\n Needle,\n SourceNeedle,\n SourceMap,\n EachMapping,\n Bias,\n} from './types';\nimport type { Source } from './by-source';\nimport type { MemoState } from './binary-search';\n\nexport type { SourceMapSegment } from './sourcemap-segment';\nexport type * from './types';\n\nconst LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';\nconst COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';\n\nexport const LEAST_UPPER_BOUND = -1;\nexport const GREATEST_LOWER_BOUND = 1;\n\n/**\n * Returns the encoded (VLQ string) form of the SourceMap's mappings field.\n */\nexport let encodedMappings: (map: TraceMap) => EncodedSourceMap['mappings'];\n\n/**\n * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.\n */\nexport let decodedMappings: (map: TraceMap) => Readonly;\n\n/**\n * A low-level API to find the segment associated with a generated line/column (think, from a\n * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.\n */\nexport let traceSegment: (\n map: TraceMap,\n line: number,\n column: number,\n) => Readonly | null;\n\n/**\n * A higher-level API to find the source/line/column associated with a generated line/column\n * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in\n * `source-map` library.\n */\nexport let originalPositionFor: (\n map: TraceMap,\n needle: Needle,\n) => OriginalMapping | InvalidOriginalMapping;\n\n/**\n * Finds the generated line/column position of the provided source/line/column source position.\n */\nexport let generatedPositionFor: (\n map: TraceMap,\n needle: SourceNeedle,\n) => GeneratedMapping | InvalidGeneratedMapping;\n\n/**\n * Finds all generated line/column positions of the provided source/line/column source position.\n */\nexport let allGeneratedPositionsFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping[];\n\n/**\n * Iterates each mapping in generated position order.\n */\nexport let eachMapping: (map: TraceMap, cb: (mapping: EachMapping) => void) => void;\n\n/**\n * Retrieves the source content for a particular source, if its found. Returns null if not.\n */\nexport let sourceContentFor: (map: TraceMap, source: string) => string | null;\n\n/**\n * A helper that skips sorting of the input map's mappings array, which can be expensive for larger\n * maps.\n */\nexport let presortedDecodedMap: (map: DecodedSourceMap, mapUrl?: string) => TraceMap;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let decodedMap: (\n map: TraceMap,\n) => Omit & { mappings: readonly SourceMapSegment[][] };\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let encodedMap: (map: TraceMap) => EncodedSourceMap;\n\nexport { AnyMap } from './any-map';\n\nexport class TraceMap implements SourceMap {\n declare version: SourceMapV3['version'];\n declare file: SourceMapV3['file'];\n declare names: SourceMapV3['names'];\n declare sourceRoot: SourceMapV3['sourceRoot'];\n declare sources: SourceMapV3['sources'];\n declare sourcesContent: SourceMapV3['sourcesContent'];\n\n declare resolvedSources: string[];\n private declare _encoded: string | undefined;\n\n private declare _decoded: SourceMapSegment[][] | undefined;\n private declare _decodedMemo: MemoState;\n\n private declare _bySources: Source[] | undefined;\n private declare _bySourceMemos: MemoState[] | undefined;\n\n constructor(map: SourceMapInput, mapUrl?: string | null) {\n const isString = typeof map === 'string';\n\n if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap;\n\n const parsed = (isString ? JSON.parse(map) : map) as DecodedSourceMap | EncodedSourceMap;\n\n const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;\n this.version = version;\n this.file = file;\n this.names = names || [];\n this.sourceRoot = sourceRoot;\n this.sources = sources;\n this.sourcesContent = sourcesContent;\n\n const from = resolve(sourceRoot || '', stripFilename(mapUrl));\n this.resolvedSources = sources.map((s) => resolve(s || '', from));\n\n const { mappings } = parsed;\n if (typeof mappings === 'string') {\n this._encoded = mappings;\n this._decoded = undefined;\n } else {\n this._encoded = undefined;\n this._decoded = maybeSort(mappings, isString);\n }\n\n this._decodedMemo = memoizedState();\n this._bySources = undefined;\n this._bySourceMemos = undefined;\n }\n\n static {\n encodedMappings = (map) => {\n return (map._encoded ??= encode(map._decoded!));\n };\n\n decodedMappings = (map) => {\n return (map._decoded ||= decode(map._encoded!));\n };\n\n traceSegment = (map, line, column) => {\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return null;\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n map._decodedMemo,\n line,\n column,\n GREATEST_LOWER_BOUND,\n );\n\n return index === -1 ? null : segments[index];\n };\n\n originalPositionFor = (map, { line, column, bias }) => {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return OMapping(null, null, null, null);\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n map._decodedMemo,\n line,\n column,\n bias || GREATEST_LOWER_BOUND,\n );\n\n if (index === -1) return OMapping(null, null, null, null);\n\n const segment = segments[index];\n if (segment.length === 1) return OMapping(null, null, null, null);\n\n const { names, resolvedSources } = map;\n return OMapping(\n resolvedSources[segment[SOURCES_INDEX]],\n segment[SOURCE_LINE] + 1,\n segment[SOURCE_COLUMN],\n segment.length === 5 ? names[segment[NAMES_INDEX]] : null,\n );\n };\n\n allGeneratedPositionsFor = (map, { source, line, column, bias }) => {\n // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit.\n return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);\n };\n\n generatedPositionFor = (map, { source, line, column, bias }) => {\n return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);\n };\n\n eachMapping = (map, cb) => {\n const decoded = decodedMappings(map);\n const { names, resolvedSources } = map;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generatedLine = i + 1;\n const generatedColumn = seg[0];\n let source = null;\n let originalLine = null;\n let originalColumn = null;\n let name = null;\n if (seg.length !== 1) {\n source = resolvedSources[seg[1]];\n originalLine = seg[2] + 1;\n originalColumn = seg[3];\n }\n if (seg.length === 5) name = names[seg[4]];\n\n cb({\n generatedLine,\n generatedColumn,\n source,\n originalLine,\n originalColumn,\n name,\n } as EachMapping);\n }\n }\n };\n\n sourceContentFor = (map, source) => {\n const { sources, resolvedSources, sourcesContent } = map;\n if (sourcesContent == null) return null;\n\n let index = sources.indexOf(source);\n if (index === -1) index = resolvedSources.indexOf(source);\n\n return index === -1 ? null : sourcesContent[index];\n };\n\n presortedDecodedMap = (map, mapUrl) => {\n const tracer = new TraceMap(clone(map, []), mapUrl);\n tracer._decoded = map.mappings;\n return tracer;\n };\n\n decodedMap = (map) => {\n return clone(map, decodedMappings(map));\n };\n\n encodedMap = (map) => {\n return clone(map, encodedMappings(map));\n };\n\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: false,\n ): GeneratedMapping | InvalidGeneratedMapping;\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: true,\n ): GeneratedMapping[];\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: boolean,\n ): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const { sources, resolvedSources } = map;\n let sourceIndex = sources.indexOf(source);\n if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source);\n if (sourceIndex === -1) return all ? [] : GMapping(null, null);\n\n const generated = (map._bySources ||= buildBySources(\n decodedMappings(map),\n (map._bySourceMemos = sources.map(memoizedState)),\n ));\n\n const segments = generated[sourceIndex][line];\n if (segments == null) return all ? [] : GMapping(null, null);\n\n const memo = map._bySourceMemos![sourceIndex];\n\n if (all) return sliceGeneratedPositions(segments, memo, line, column, bias);\n\n const index = traceSegmentInternal(segments, memo, line, column, bias);\n if (index === -1) return GMapping(null, null);\n\n const segment = segments[index];\n return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);\n }\n }\n}\n\nfunction clone(\n map: TraceMap | DecodedSourceMap | EncodedSourceMap,\n mappings: T,\n): T extends string ? EncodedSourceMap : DecodedSourceMap {\n return {\n version: map.version,\n file: map.file,\n names: map.names,\n sourceRoot: map.sourceRoot,\n sources: map.sources,\n sourcesContent: map.sourcesContent,\n mappings,\n } as any;\n}\n\nfunction OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping;\nfunction OMapping(\n source: string,\n line: number,\n column: number,\n name: string | null,\n): OriginalMapping;\nfunction OMapping(\n source: string | null,\n line: number | null,\n column: number | null,\n name: string | null,\n): OriginalMapping | InvalidOriginalMapping {\n return { source, line, column, name } as any;\n}\n\nfunction GMapping(line: null, column: null): InvalidGeneratedMapping;\nfunction GMapping(line: number, column: number): GeneratedMapping;\nfunction GMapping(\n line: number | null,\n column: number | null,\n): GeneratedMapping | InvalidGeneratedMapping {\n return { line, column } as any;\n}\n\nfunction traceSegmentInternal(\n segments: SourceMapSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: SourceMapSegment[] | ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number {\n let index = memoizedBinarySearch(segments, column, memo, line);\n if (bsFound) {\n index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);\n } else if (bias === LEAST_UPPER_BOUND) index++;\n\n if (index === -1 || index === segments.length) return -1;\n return index;\n}\n\nfunction sliceGeneratedPositions(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): GeneratedMapping[] {\n let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);\n\n // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in\n // insertion order) segment that matched. Even if we did respect the bias when tracing, we would\n // still need to call `lowerBound()` to find the first segment, which is slower than just looking\n // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the\n // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to\n // match LEAST_UPPER_BOUND.\n if (!bsFound && bias === LEAST_UPPER_BOUND) min++;\n\n if (min === -1 || min === segments.length) return [];\n\n // We may have found the segment that started at an earlier column. If this is the case, then we\n // need to slice all generated segments that match _that_ column, because all such segments span\n // to our desired column.\n const matchedColumn = bsFound ? column : segments[min][COLUMN];\n\n // The binary search is not guaranteed to find the lower bound when a match wasn't found.\n if (!bsFound) min = lowerBound(segments, matchedColumn, min);\n const max = upperBound(segments, matchedColumn, min);\n\n const result = [];\n for (; min <= max; min++) {\n const segment = segments[min];\n result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));\n }\n return result;\n}\n"],"names":["presortedDecodedMap","decodedMappings","encodedMappings","traceSegment","originalPositionFor","generatedPositionFor","allGeneratedPositionsFor","eachMapping","sourceContentFor","decodedMap","encodedMap","encode","decode","bsFound"],"mappings":";;;;;;IAEc,SAAU,OAAO,CAAC,KAAa,EAAE,IAAwB,EAAA;;;;QAIrE,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,IAAI,IAAI,GAAG,CAAC;IAE7C,IAAA,OAAO,UAAU,CAAC,KAAK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AAM,EAAE,oBAAoB,CAAC,CAAC;;;;;;;IAQnF,IAAA,IAAI,CAACA,KAAO,IAAI,IAAI,KAAK,iBAAiB;IAAE,QAAA,GAAG,EAAE,CAAC;QAElD,IAAI,GAAG,KAAK,CAAC,CAAC,IAAI,GAAG,KAAK,QAAQ,CAAC,MAAM;IAAE,QAAA,OAAO,EAAE,CAAC;;;;IAKrD,IAAA,MAAM,aAAa,GAAGA,KAAO,GAAG,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;;IAG/D,IAAA,IAAI,CAACA,KAAO;YAAE,GAAG,GAAG,UAAU,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;QAC7D,MAAM,GAAG,GAAG,UAAU,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;QAErD,MAAM,MAAM,GAAG,EAAE,CAAC;IAClB,IAAA,OAAO,GAAG,IAAI,GAAG,EAAE,GAAG,EAAE,EAAE;IACxB,QAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC9B,QAAA,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;SACvF;IACD,IAAA,OAAO,MAAM,CAAC;IAChB;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts new file mode 100644 index 0000000..ec775fb --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts @@ -0,0 +1,8 @@ +import { TraceMap } from './trace-mapping'; +import type { SectionedSourceMapInput } from './types'; +type AnyMap = { + new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; + (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; +}; +export declare const AnyMap: AnyMap; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts new file mode 100644 index 0000000..ecb2873 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts @@ -0,0 +1,32 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +export type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts new file mode 100644 index 0000000..a91751c --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts @@ -0,0 +1,7 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment'; +import type { MemoState } from './binary-search'; +export type Source = { + __proto__: null; + [line: number]: Exclude[]; +}; +export default function buildBySources(decoded: readonly SourceMapSegment[][], memos: MemoState[]): Source[]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts new file mode 100644 index 0000000..cf7d4f8 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts @@ -0,0 +1 @@ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts new file mode 100644 index 0000000..2bfb5dc --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts @@ -0,0 +1,2 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export default function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 0000000..6d4d318 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,16 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +type GeneratedLine = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts new file mode 100644 index 0000000..bead5c1 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts @@ -0,0 +1,4 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts new file mode 100644 index 0000000..69e93ee --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts @@ -0,0 +1,74 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping } from './types'; +export type { SourceMapSegment } from './sourcemap-segment'; +export type * from './types'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare let encodedMappings: (map: TraceMap) => EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare let decodedMappings: (map: TraceMap) => Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare let traceSegment: (map: TraceMap, line: number, column: number) => Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare let originalPositionFor: (map: TraceMap, needle: Needle) => OriginalMapping | InvalidOriginalMapping; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export declare let generatedPositionFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping | InvalidGeneratedMapping; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export declare let allGeneratedPositionsFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping[]; +/** + * Iterates each mapping in generated position order. + */ +export declare let eachMapping: (map: TraceMap, cb: (mapping: EachMapping) => void) => void; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export declare let sourceContentFor: (map: TraceMap, source: string) => string | null; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare let presortedDecodedMap: (map: DecodedSourceMap, mapUrl?: string) => TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let decodedMap: (map: TraceMap) => Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let encodedMap: (map: TraceMap) => EncodedSourceMap; +export { AnyMap } from './any-map'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: SourceMapInput, mapUrl?: string | null); +} diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts new file mode 100644 index 0000000..d881499 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts @@ -0,0 +1,92 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export type GeneratedMapping = { + line: number; + column: number; +}; +export type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; +export type SourceMapInput = string | Ro | Ro | TraceMap; +export type SectionedSourceMapInput = SourceMapInput | Ro; +export type Needle = { + line: number; + column: number; + bias?: Bias; +}; +export type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: Bias; +}; +export type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; +} +export type Ro = T extends Array ? V[] | Readonly | RoArray | Readonly> : T extends object ? T | Readonly | RoObject | Readonly> : T; +type RoArray = Ro[]; +type RoObject = { + [K in keyof T]: T[K] | Ro; +}; +export {}; diff --git a/node_modules/@remix-run/router/dist/history.d.ts b/node_modules/@remix-run/router/dist/history.d.ts new file mode 100644 index 0000000..bda6722 --- /dev/null +++ b/node_modules/@remix-run/router/dist/history.d.ts @@ -0,0 +1,250 @@ +/** + * 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: State; + /** + * A unique string associated with this location. May be used to safely store + * and retrieve data in some other storage API, like `localStorage`. + * + * Note: This value is always "default" on the initial location. + */ + key: string; +} +/** + * A change to the current location. + */ +export interface Update { + /** + * The action that triggered the change. + */ + action: Action; + /** + * The new location. + */ + location: Location; + /** + * The delta between this location and the former location in the history stack + */ + delta: number | null; +} +/** + * A function that receives notifications about location changes. + */ +export interface Listener { + (update: Update): void; +} +/** + * Describes a location that is the destination of some navigation, either via + * `history.push` or `history.replace`. This may be either a URL or the pieces + * of a URL path. + */ +export type To = string | Partial; +/** + * 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; + /** + * Returns a URL for the given `to` value + * + * @param to - The destination URL + */ + createURL(to: To): URL; + /** + * Encode a location the same way window.history would do (no-op for memory + * history) so we ensure our PUSH/REPLACE navigations for data routers + * behave the same as POP + * + * @param to Unencoded path + */ + encodeLocation(to: To): Path; + /** + * Pushes a new location onto the history stack, increasing its length by one. + * If there were any entries in the stack after the current one, they are + * lost. + * + * @param to - The new URL + * @param state - Data to associate with the new location + */ + push(to: To, state?: any): void; + /** + * Replaces the current location in the history stack with a new one. The + * location that was replaced will no longer be available. + * + * @param to - The new URL + * @param state - Data to associate with the new location + */ + replace(to: To, state?: any): void; + /** + * Navigates `n` entries backward/forward in the history stack relative to the + * current index. For example, a "back" navigation would use go(-1). + * + * @param delta - The delta in the stack index + */ + go(delta: number): void; + /** + * Sets up a listener that will be called whenever the current location + * changes. + * + * @param listener - A function that will be called when the location changes + * @returns unlisten - A function that may be used to stop listening + */ + listen(listener: Listener): () => void; +} +/** + * 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 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 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 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; +/** + * @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; +export declare function warning(cond: any, message: string): void; +/** + * 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 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 new file mode 100644 index 0000000..78479d0 --- /dev/null +++ b/node_modules/@remix-run/router/dist/index.d.ts @@ -0,0 +1,9 @@ +export type { ActionFunction, ActionFunctionArgs, AgnosticDataIndexRouteObject, AgnosticDataNonIndexRouteObject, AgnosticDataRouteMatch, AgnosticDataRouteObject, AgnosticIndexRouteObject, AgnosticNonIndexRouteObject, AgnosticRouteMatch, AgnosticRouteObject, ErrorResponse, FormEncType, FormMethod, HTMLFormMethod, JsonFunction, LazyRouteFunction, LoaderFunction, LoaderFunctionArgs, ParamParseKey, Params, PathMatch, PathParam, PathPattern, RedirectFunction, ShouldRevalidateFunction, ShouldRevalidateFunctionArgs, TrackedPromise, UIMatch, V7_FormMethod, } from "./utils"; +export { AbortedDeferredError, defer, generatePath, getToPathname, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, redirect, redirectDocument, resolvePath, resolveTo, stripBasename, } from "./utils"; +export type { BrowserHistory, BrowserHistoryOptions, HashHistory, HashHistoryOptions, History, InitialEntry, Location, MemoryHistory, MemoryHistoryOptions, Path, To, } from "./history"; +export { Action, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, parsePath, } from "./history"; +export * from "./router"; +/** @internal */ +export type { RouteManifest as UNSAFE_RouteManifest } from "./utils"; +export { DeferredData as UNSAFE_DeferredData, ErrorResponseImpl as UNSAFE_ErrorResponseImpl, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, convertRouteMatchToUiMatch as UNSAFE_convertRouteMatchToUiMatch, getResolveToMatches as UNSAFE_getResolveToMatches, } from "./utils"; +export { invariant as UNSAFE_invariant, warning as UNSAFE_warning, } from "./history"; diff --git a/node_modules/@remix-run/router/dist/router.cjs.js b/node_modules/@remix-run/router/dist/router.cjs.js new file mode 100644 index 0000000..2e895bd --- /dev/null +++ b/node_modules/@remix-run/router/dist/router.cjs.js @@ -0,0 +1,4840 @@ +/** + * @remix-run/router v1.14.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. + */ +let Action = /*#__PURE__*/function (Action) { + Action["Pop"] = "POP"; + Action["Push"] = "PUSH"; + Action["Replace"] = "REPLACE"; + return Action; +}({}); + +/** + * The pathname, search, and hash values of a URL. + */ + +// TODO: (v7) Change the Location generic default from `any` to `unknown` and +// remove Remix `useLocation` wrapper. +/** + * An entry in a history stack. A location contains information about the + * URL path, as well as possibly some arbitrary state and a key. + */ +/** + * A change to the current location. + */ +/** + * A function that receives notifications about location changes. + */ +/** + * Describes a location that is the destination of some navigation, either via + * `history.push` or `history.replace`. This may be either a URL or the pieces + * of a URL path. + */ +/** + * A history is an interface to the navigation stack. The history serves as the + * source of truth for the current location, as well as provides a set of + * methods that may be used to change it. + * + * It is similar to the DOM's `window.history` object, but with a smaller, more + * focused API. + */ +const PopStateEventType = "popstate"; +//#endregion + +//////////////////////////////////////////////////////////////////////////////// +//#region Memory History +//////////////////////////////////////////////////////////////////////////////// + +/** + * A user-supplied object that describes a location. Used when providing + * entries to `createMemoryHistory` via its `initialEntries` option. + */ +/** + * A memory history stores locations in memory. This is useful in stateful + * environments where there is no web browser, such as node tests or React + * Native. + */ +/** + * Memory history stores the current location in memory. It is designed for use + * in stateful non-browser environments like tests and React Native. + */ +function createMemoryHistory(options) { + if (options === void 0) { + options = {}; + } + let { + initialEntries = ["/"], + initialIndex, + v5Compat = false + } = options; + let entries; // Declare so we can access from createMemoryLocation + entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined)); + let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex); + let action = Action.Pop; + let listener = null; + function clampIndex(n) { + return Math.min(Math.max(n, 0), entries.length - 1); + } + function getCurrentLocation() { + return entries[index]; + } + function createMemoryLocation(to, state, key) { + if (state === void 0) { + state = null; + } + let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key); + warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to)); + return location; + } + function createHref(to) { + return typeof to === "string" ? to : createPath(to); + } + let history = { + get index() { + return index; + }, + get action() { + return action; + }, + get location() { + return getCurrentLocation(); + }, + createHref, + createURL(to) { + return new URL(createHref(to), "http://localhost"); + }, + encodeLocation(to) { + let path = typeof to === "string" ? parsePath(to) : to; + return { + pathname: path.pathname || "", + search: path.search || "", + hash: path.hash || "" + }; + }, + push(to, state) { + action = Action.Push; + let nextLocation = createMemoryLocation(to, state); + index += 1; + entries.splice(index, entries.length, nextLocation); + if (v5Compat && listener) { + listener({ + action, + location: nextLocation, + delta: 1 + }); + } + }, + replace(to, state) { + action = Action.Replace; + let nextLocation = createMemoryLocation(to, state); + entries[index] = nextLocation; + if (v5Compat && listener) { + listener({ + action, + location: nextLocation, + delta: 0 + }); + } + }, + go(delta) { + action = Action.Pop; + let nextIndex = clampIndex(index + delta); + let nextLocation = entries[nextIndex]; + index = nextIndex; + if (listener) { + listener({ + action, + location: nextLocation, + delta + }); + } + }, + listen(fn) { + listener = fn; + return () => { + listener = null; + }; + } + }; + return history; +} +//#endregion + +//////////////////////////////////////////////////////////////////////////////// +//#region Browser History +//////////////////////////////////////////////////////////////////////////////// + +/** + * A browser history stores the current location in regular URLs in a web + * browser environment. This is the standard for most web apps and provides the + * cleanest URLs the browser's address bar. + * + * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory + */ +/** + * Browser history stores the location in regular URLs. This is the standard for + * most web apps, but it requires some configuration on the server to ensure you + * serve the same app at multiple URLs. + * + * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory + */ +function createBrowserHistory(options) { + if (options === void 0) { + options = {}; + } + function createBrowserLocation(window, globalHistory) { + let { + pathname, + search, + hash + } = window.location; + return createLocation("", { + pathname, + search, + hash + }, + // state defaults to `null` because `window.history.state` does + globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); + } + function createBrowserHref(window, to) { + return typeof to === "string" ? to : createPath(to); + } + return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options); +} +//#endregion + +//////////////////////////////////////////////////////////////////////////////// +//#region Hash History +//////////////////////////////////////////////////////////////////////////////// + +/** + * A hash history stores the current location in the fragment identifier portion + * of the URL in a web browser environment. + * + * This is ideal for apps that do not control the server for some reason + * (because the fragment identifier is never sent to the server), including some + * shared hosting environments that do not provide fine-grained controls over + * which pages are served at which URLs. + * + * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory + */ +/** + * Hash history stores the location in window.location.hash. This makes it ideal + * for situations where you don't want to send the location to the server for + * some reason, either because you do cannot configure it or the URL space is + * reserved for something else. + * + * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory + */ +function createHashHistory(options) { + if (options === void 0) { + options = {}; + } + function createHashLocation(window, globalHistory) { + let { + pathname = "/", + search = "", + hash = "" + } = parsePath(window.location.hash.substr(1)); + + // Hash URL should always have a leading / just like window.location.pathname + // does, so if an app ends up at a route like /#something then we add a + // leading slash so all of our path-matching behaves the same as if it would + // in a browser router. This is particularly important when there exists a + // root splat route () since that matches internally against + // "/*" and we'd expect /#something to 404 in a hash router app. + if (!pathname.startsWith("/") && !pathname.startsWith(".")) { + pathname = "/" + pathname; + } + return createLocation("", { + pathname, + search, + hash + }, + // state defaults to `null` because `window.history.state` does + globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); + } + function createHashHref(window, to) { + let base = window.document.querySelector("base"); + let href = ""; + if (base && base.getAttribute("href")) { + let url = window.location.href; + let hashIndex = url.indexOf("#"); + href = hashIndex === -1 ? url : url.slice(0, hashIndex); + } + return href + "#" + (typeof to === "string" ? to : createPath(to)); + } + function validateHashLocation(location, to) { + warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")"); + } + return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options); +} +//#endregion + +//////////////////////////////////////////////////////////////////////////////// +//#region UTILS +//////////////////////////////////////////////////////////////////////////////// + +/** + * @private + */ +function invariant(value, message) { + if (value === false || value === null || typeof value === "undefined") { + throw new Error(message); + } +} +function warning(cond, message) { + if (!cond) { + // eslint-disable-next-line no-console + if (typeof console !== "undefined") console.warn(message); + try { + // Welcome to debugging history! + // + // This error is thrown as a convenience, so you can more easily + // find the source for a warning that appears in the console by + // enabling "pause on exceptions" in your JavaScript debugger. + throw new Error(message); + // eslint-disable-next-line no-empty + } catch (e) {} + } +} +function createKey() { + return Math.random().toString(36).substr(2, 8); +} + +/** + * For browser-based histories, we combine the state and key into an object + */ +function getHistoryState(location, index) { + return { + usr: location.state, + key: location.key, + idx: index + }; +} + +/** + * Creates a Location object with a unique key from the given Path + */ +function createLocation(current, to, state, key) { + if (state === void 0) { + state = null; + } + let location = _extends({ + pathname: typeof current === "string" ? current : current.pathname, + search: "", + hash: "" + }, typeof to === "string" ? parsePath(to) : to, { + state, + // TODO: This could be cleaned up. push/replace should probably just take + // full Locations now and avoid the need to run through this flow at all + // But that's a pretty big refactor to the current test suite so going to + // keep as is for the time being and just let any incoming keys take precedence + key: to && to.key || key || createKey() + }); + return location; +} + +/** + * Creates a string URL path from the given pathname, search, and hash components. + */ +function createPath(_ref) { + let { + pathname = "/", + search = "", + hash = "" + } = _ref; + if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search; + if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash; + return pathname; +} + +/** + * Parses a string URL path into its separate pathname, search, and hash components. + */ +function parsePath(path) { + let parsedPath = {}; + if (path) { + let hashIndex = path.indexOf("#"); + if (hashIndex >= 0) { + parsedPath.hash = path.substr(hashIndex); + path = path.substr(0, hashIndex); + } + let searchIndex = path.indexOf("?"); + if (searchIndex >= 0) { + parsedPath.search = path.substr(searchIndex); + path = path.substr(0, searchIndex); + } + if (path) { + parsedPath.pathname = path; + } + } + return parsedPath; +} +function getUrlBasedHistory(getLocation, createHref, validateLocation, options) { + if (options === void 0) { + options = {}; + } + let { + window = document.defaultView, + v5Compat = false + } = options; + let globalHistory = window.history; + let action = Action.Pop; + let listener = null; + let index = getIndex(); + // Index should only be null when we initialize. If not, it's because the + // user called history.pushState or history.replaceState directly, in which + // case we should log a warning as it will result in bugs. + if (index == null) { + index = 0; + globalHistory.replaceState(_extends({}, globalHistory.state, { + idx: index + }), ""); + } + function getIndex() { + let state = globalHistory.state || { + idx: null + }; + return state.idx; + } + function handlePop() { + action = Action.Pop; + let nextIndex = getIndex(); + let delta = nextIndex == null ? null : nextIndex - index; + index = nextIndex; + if (listener) { + listener({ + action, + location: history.location, + delta + }); + } + } + function push(to, state) { + action = Action.Push; + let location = createLocation(history.location, to, state); + if (validateLocation) validateLocation(location, to); + index = getIndex() + 1; + let historyState = getHistoryState(location, index); + let url = history.createHref(location); + + // try...catch because iOS limits us to 100 pushState calls :/ + try { + globalHistory.pushState(historyState, "", url); + } catch (error) { + // If the exception is because `state` can't be serialized, let that throw + // outwards just like a replace call would so the dev knows the cause + // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps + // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal + if (error instanceof DOMException && error.name === "DataCloneError") { + throw error; + } + // They are going to lose state here, but there is no real + // way to warn them about it since the page will refresh... + window.location.assign(url); + } + if (v5Compat && listener) { + listener({ + action, + location: history.location, + delta: 1 + }); + } + } + function replace(to, state) { + action = Action.Replace; + let location = createLocation(history.location, to, state); + if (validateLocation) validateLocation(location, to); + index = getIndex(); + let historyState = getHistoryState(location, index); + let url = history.createHref(location); + globalHistory.replaceState(historyState, "", url); + if (v5Compat && listener) { + listener({ + action, + location: history.location, + delta: 0 + }); + } + } + function createURL(to) { + // window.location.origin is "null" (the literal string value) in Firefox + // under certain conditions, notably when serving from a local HTML file + // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297 + let base = window.location.origin !== "null" ? window.location.origin : window.location.href; + let href = typeof to === "string" ? to : createPath(to); + invariant(base, "No window.location.(origin|href) available to create URL for href: " + href); + return new URL(href, base); + } + let history = { + get action() { + return action; + }, + get location() { + return getLocation(window, globalHistory); + }, + listen(fn) { + if (listener) { + throw new Error("A history only accepts one active listener"); + } + window.addEventListener(PopStateEventType, handlePop); + listener = fn; + return () => { + window.removeEventListener(PopStateEventType, handlePop); + listener = null; + }; + }, + createHref(to) { + return createHref(window, to); + }, + createURL, + encodeLocation(to) { + // Encode a Location the same way window.location would + let url = createURL(to); + return { + pathname: url.pathname, + search: url.search, + hash: url.hash + }; + }, + push, + replace, + go(n) { + return globalHistory.go(n); + } + }; + return history; +} + +//#endregion + +/** + * Map of routeId -> data returned from a loader/action/error + */ + +let ResultType = /*#__PURE__*/function (ResultType) { + ResultType["data"] = "data"; + ResultType["deferred"] = "deferred"; + ResultType["redirect"] = "redirect"; + ResultType["error"] = "error"; + return ResultType; +}({}); + +/** + * Successful result from a loader or action + */ + +/** + * Successful defer() result from a loader or action + */ + +/** + * Redirect result from a loader or action + */ + +/** + * Unsuccessful result from a loader or action + */ + +/** + * Result from a loader or action - potentially successful or unsuccessful + */ + +/** + * Users can specify either lowercase or uppercase form methods on `
`, + * useSubmit(), ``, etc. + */ + +/** + * Active navigation/fetcher form methods are exposed in lowercase on the + * RouterState + */ + +/** + * In v7, active navigation/fetcher form methods are exposed in uppercase on the + * RouterState. This is to align with the normalization done via fetch(). + */ + +// Thanks https://github.com/sindresorhus/type-fest! + +/** + * @private + * Internal interface to pass around for action submissions, not intended for + * external consumption + */ + +/** + * @private + * Arguments passed to route loader/action functions. Same for now but we keep + * this as a private implementation detail in case they diverge in the future. + */ + +// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers: +// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs +// Also, make them a type alias instead of an interface +/** + * Arguments passed to loader functions + */ +/** + * Arguments passed to action functions + */ +/** + * Loaders and actions can return anything except `undefined` (`null` is a + * valid return value if there is no data to return). Responses are preferred + * and will ease any future migration to Remix + */ +/** + * Route loader function signature + */ +/** + * Route action function signature + */ +/** + * Arguments passed to shouldRevalidate function + */ +/** + * Route shouldRevalidate function signature. This runs after any submission + * (navigation or fetcher), so we flatten the navigation/fetcher submission + * onto the arguments. It shouldn't matter whether it came from a navigation + * or a fetcher, what really matters is the URLs and the formData since loaders + * have to re-run based on the data models that were potentially mutated. + */ +/** + * Function provided by the framework-aware layers to set `hasErrorBoundary` + * from the framework-aware `errorElement` prop + * + * @deprecated Use `mapRouteProperties` instead + */ +/** + * Function provided by the framework-aware layers to set any framework-specific + * properties from framework-agnostic properties + */ +/** + * Keys we cannot change from within a lazy() function. We spread all other keys + * onto the route. Either they're meaningful to the router, or they'll get + * ignored. + */ +const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]); + +/** + * lazy() function to load a route definition, which can add non-matching + * related properties to a route + */ + +/** + * Base RouteObject with common props shared by all types of routes + */ + +/** + * Index routes must not have children + */ + +/** + * Non-index routes may have children, but cannot have index + */ + +/** + * A route object represents a logical route, with (optionally) its child + * routes organized in a tree-like structure. + */ + +/** + * A data route object, which is just a RouteObject with a required unique ID + */ + +// Recursive helper for finding path parameters in the absence of wildcards + +/** + * Examples: + * "/a/b/*" -> "*" + * ":a" -> "a" + * "/a/:b" -> "b" + * "/a/blahblahblah:b" -> "b" + * "/:a/:b" -> "a" | "b" + * "/:a/b/:c/*" -> "a" | "c" | "*" + */ + +// Attempt to parse the given string segment. If it fails, then just return the +// plain string type as a default fallback. Otherwise, return the union of the +// parsed string literals that were referenced as dynamic segments in the route. +/** + * The parameters that were parsed from the URL path. + */ +/** + * A RouteMatch contains info about how a route matched a URL. + */ +function isIndexRoute(route) { + return route.index === true; +} + +// Walk the route tree generating unique IDs where necessary, so we are working +// solely with AgnosticDataRouteObject's within the Router +function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) { + if (parentPath === void 0) { + parentPath = []; + } + if (manifest === void 0) { + manifest = {}; + } + return routes.map((route, index) => { + let treePath = [...parentPath, index]; + let id = typeof route.id === "string" ? route.id : treePath.join("-"); + invariant(route.index !== true || !route.children, "Cannot specify children on an index route"); + invariant(!manifest[id], "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages"); + if (isIndexRoute(route)) { + let indexRoute = _extends({}, route, mapRouteProperties(route), { + id + }); + manifest[id] = indexRoute; + return indexRoute; + } else { + let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), { + id, + children: undefined + }); + manifest[id] = pathOrLayoutRoute; + if (route.children) { + pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest); + } + return pathOrLayoutRoute; + } + }); +} + +/** + * Matches the given routes to a location and returns the match data. + * + * @see https://reactrouter.com/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], + // Incoming pathnames are generally encoded from either window.location + // or from router.navigate, but we want to match against the unencoded + // paths in the route definitions. Memory router locations won't be + // encoded here but there also shouldn't be anything to decode so this + // should be a safe operation. This avoids needing matchRoutes to be + // history-aware. + safelyDecodeURI(pathname)); + } + return matches; +} +function convertRouteMatchToUiMatch(match, loaderData) { + let { + route, + pathname, + params + } = match; + return { + id: route.id, + pathname, + params, + data: loaderData[route.id], + handle: route.handle + }; +} +function flattenRoutes(routes, branches, parentsMeta, parentPath) { + if (branches === void 0) { + branches = []; + } + if (parentsMeta === void 0) { + parentsMeta = []; + } + if (parentPath === void 0) { + parentPath = ""; + } + let flattenRoute = (route, index, relativePath) => { + let meta = { + relativePath: relativePath === undefined ? route.path || "" : relativePath, + caseSensitive: route.caseSensitive === true, + childrenIndex: index, + route + }; + if (meta.relativePath.startsWith("/")) { + invariant(meta.relativePath.startsWith(parentPath), "Absolute route path \"" + meta.relativePath + "\" nested under path " + ("\"" + parentPath + "\" is not valid. An absolute child route path ") + "must start with the combined path of all its parent routes."); + meta.relativePath = meta.relativePath.slice(parentPath.length); + } + let path = joinPaths([parentPath, meta.relativePath]); + let routesMeta = parentsMeta.concat(meta); + + // Add the children before adding this route to the array, so we traverse the + // route tree depth-first and child routes appear before their parents in + // the "flattened" version. + if (route.children && route.children.length > 0) { + invariant( + // Our types know better, but runtime JS may not! + // @ts-expect-error + route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\".")); + flattenRoutes(route.children, branches, routesMeta, path); + } + + // Routes without a path shouldn't ever match by themselves unless they are + // index routes, so don't add them to the list of possible branches. + if (route.path == null && !route.index) { + return; + } + branches.push({ + path, + score: computeScore(path, route.index), + routesMeta + }); + }; + routes.forEach((route, index) => { + var _route$path; + // coarse-grain check for optional params + if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) { + flattenRoute(route, index); + } else { + for (let exploded of explodeOptionalSegments(route.path)) { + flattenRoute(route, index, exploded); + } + } + }); + return branches; +} + +/** + * Computes all combinations of optional path segments for a given path, + * excluding combinations that are ambiguous and of lower priority. + * + * For example, `/one/:two?/three/:four?/:five?` explodes to: + * - `/one/three` + * - `/one/:two/three` + * - `/one/three/:four` + * - `/one/three/:five` + * - `/one/:two/three/:four` + * - `/one/:two/three/:five` + * - `/one/three/:four/:five` + * - `/one/:two/three/:four/:five` + */ +function explodeOptionalSegments(path) { + let segments = path.split("/"); + if (segments.length === 0) return []; + let [first, ...rest] = segments; + + // Optional path segments are denoted by a trailing `?` + let isOptional = first.endsWith("?"); + // Compute the corresponding required segment: `foo?` -> `foo` + let required = first.replace(/\?$/, ""); + if (rest.length === 0) { + // Intepret empty string as omitting an optional segment + // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three` + return isOptional ? [required, ""] : [required]; + } + let restExploded = explodeOptionalSegments(rest.join("/")); + let result = []; + + // All child paths with the prefix. Do this for all children before the + // optional version for all children, so we get consistent ordering where the + // parent optional aspect is preferred as required. Otherwise, we can get + // child sections interspersed where deeper optional segments are higher than + // parent optional segments, where for example, /:two would explode _earlier_ + // then /:one. By always including the parent as required _for all children_ + // first, we avoid this issue + result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/"))); + + // Then, if this is an optional value, add all child versions without + if (isOptional) { + result.push(...restExploded); + } + + // for absolute paths, ensure `/` instead of empty segment + return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded); +} +function rankRouteBranches(branches) { + branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first + : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex))); +} +const paramRe = /^:[\w-]+$/; +const dynamicSegmentValue = 3; +const indexRouteValue = 2; +const emptySegmentValue = 1; +const staticSegmentValue = 10; +const splatPenalty = -2; +const isSplat = s => s === "*"; +function computeScore(path, index) { + let segments = path.split("/"); + let initialScore = segments.length; + if (segments.some(isSplat)) { + initialScore += splatPenalty; + } + if (index) { + initialScore += indexRouteValue; + } + return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore); +} +function compareIndexes(a, b) { + let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]); + return siblings ? + // If two routes are siblings, we should try to match the earlier sibling + // first. This allows people to have fine-grained control over the matching + // behavior by simply putting routes with identical paths in the order they + // want them tried. + a[a.length - 1] - b[b.length - 1] : + // Otherwise, it doesn't really make sense to rank non-siblings by index, + // so they sort equally. + 0; +} +function matchRouteBranch(branch, pathname) { + 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/utils/generate-path + */ +function generatePath(originalPath, params) { + if (params === void 0) { + params = {}; + } + let path = originalPath; + if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) { + warning(false, "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); + path = path.replace(/\*$/, "/*"); + } + + // ensure `/` is added at the beginning if the path is absolute + const prefix = path.startsWith("/") ? "/" : ""; + const stringify = p => p == null ? "" : typeof p === "string" ? p : String(p); + const segments = path.split(/\/+/).map((segment, index, array) => { + const isLastSegment = index === array.length - 1; + + // only apply the splat if it's the last segment + if (isLastSegment && segment === "*") { + const star = "*"; + // Apply the splat + return stringify(params[star]); + } + const keyMatch = segment.match(/^:([\w-]+)(\??)$/); + if (keyMatch) { + const [, key, optional] = keyMatch; + let param = params[key]; + invariant(optional === "?" || param != null, "Missing \":" + key + "\" param"); + return stringify(param); + } + + // Remove any optional markers from optional static segments + return segment.replace(/\?$/g, ""); + }) + // Remove empty segments + .filter(segment => !!segment); + return prefix + segments.join("/"); +} + +/** + * A PathPattern is used to match on some portion of a URL pathname. + */ + +/** + * A PathMatch contains info about how a PathPattern matched on a URL pathname. + */ + +/** + * Performs pattern matching on a URL pathname and returns information about + * the match. + * + * @see https://reactrouter.com/utils/match-path + */ +function matchPath(pattern, pathname) { + if (typeof pattern === "string") { + pattern = { + path: pattern, + caseSensitive: false, + end: true + }; + } + let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end); + let match = pathname.match(matcher); + if (!match) return null; + let matchedPathname = match[0]; + let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1"); + let captureGroups = match.slice(1); + let params = compiledParams.reduce((memo, _ref, index) => { + let { + paramName, + isOptional + } = _ref; + // We need to compute the pathnameBase here using the raw splat value + // instead of using params["*"] later because it will be decoded then + if (paramName === "*") { + let splatValue = captureGroups[index] || ""; + pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1"); + } + const value = captureGroups[index]; + if (isOptional && !value) { + memo[paramName] = undefined; + } else { + memo[paramName] = safelyDecodeURIComponent(value || "", paramName); + } + return memo; + }, {}); + return { + params, + pathname: matchedPathname, + pathnameBase, + pattern + }; +} +function compilePath(path, caseSensitive, end) { + if (caseSensitive === void 0) { + caseSensitive = false; + } + if (end === void 0) { + end = true; + } + warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); + let params = []; + let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below + .replace(/^\/*/, "/") // Make sure it has a leading / + .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars + .replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => { + params.push({ + paramName, + isOptional: isOptional != null + }); + return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)"; + }); + if (path.endsWith("*")) { + params.push({ + paramName: "*" + }); + regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest + : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"] + } else if (end) { + // When matching to the end, ignore trailing slashes + regexpSource += "\\/*$"; + } else if (path !== "" && path !== "/") { + // If our path is non-empty and contains anything beyond an initial slash, + // then we have _some_ form of path in our regex, so we should expect to + // match only if we find the end of this path segment. Look for an optional + // non-captured trailing slash (to match a portion of the URL) or the end + // of the path (if we've matched to the end). We used to do this with a + // word boundary but that gives false positives on routes like + // /user-preferences since `-` counts as a word boundary. + regexpSource += "(?:(?=\\/|$))"; + } else ; + let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i"); + return [matcher, params]; +} +function safelyDecodeURI(value) { + try { + return decodeURI(value); + } catch (error) { + warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ").")); + return value; + } +} +function safelyDecodeURIComponent(value, paramName) { + try { + return decodeURIComponent(value); + } catch (error) { + warning(false, "The value for the URL param \"" + paramName + "\" will not be decoded because" + (" the string \"" + value + "\" is a malformed URL segment. This is probably") + (" due to a bad percent encoding (" + error + ").")); + return value; + } +} + +/** + * @private + */ +function stripBasename(pathname, basename) { + if (basename === "/") return pathname; + if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) { + return null; + } + + // We want to leave trailing slash behavior in the user's control, so if they + // specify a basename with a trailing slash, we should support it + let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length; + let nextChar = pathname.charAt(startIndex); + if (nextChar && nextChar !== "/") { + // pathname does not start with basename/ + return null; + } + return pathname.slice(startIndex) || "/"; +} + +/** + * Returns a resolved path object relative to the given pathname. + * + * @see https://reactrouter.com/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 + * + * When processing relative navigation we want to ignore ancestor routes that + * do not contribute to the path, such that index/pathless layout routes don't + * interfere. + * + * For example, when moving a route element into an index route and/or a + * pathless layout route, relative link behavior contained within should stay + * the same. Both of the following examples should link back to the root: + * + * + * + * + * + * + * + * }> // <-- Does not contribute + * // <-- Does not contribute + * + * + */ +function getPathContributingMatches(matches) { + return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0); +} + +// Return the array of pathnames for the current route matches - used to +// generate the routePathnames input for resolveTo() +function getResolveToMatches(matches, v7_relativeSplatPath) { + let pathMatches = getPathContributingMatches(matches); + + // When v7_relativeSplatPath is enabled, use the full pathname for the leaf + // match so we include splat values for "." links. See: + // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329 + if (v7_relativeSplatPath) { + return pathMatches.map((match, idx) => idx === matches.length - 1 ? match.pathname : match.pathnameBase); + } + return pathMatches.map(match => match.pathnameBase); +} + +/** + * @private + */ +function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) { + if (isPathRelative === void 0) { + isPathRelative = false; + } + let to; + if (typeof toArg === "string") { + to = parsePath(toArg); + } else { + to = _extends({}, toArg); + invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to)); + invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to)); + invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to)); + } + let isEmptyPath = toArg === "" || to.pathname === ""; + let toPathname = isEmptyPath ? "/" : to.pathname; + let from; + + // Routing is relative to the current pathname if explicitly requested. + // + // If a pathname is explicitly provided in `to`, it should be relative to the + // route context. This is explained in `Note on `` values` in our + // migration guide from v5 as a means of disambiguation between `to` values + // that begin with `/` and those that do not. However, this is problematic for + // `to` values that do not provide a pathname. `to` can simply be a search or + // hash string, in which case we should assume that the navigation is relative + // to the current location's pathname and *not* the route pathname. + if (toPathname == null) { + from = locationPathname; + } else { + let routePathnameIndex = routePathnames.length - 1; + + // With relative="route" (the default), each leading .. segment means + // "go up one route" instead of "go up one URL segment". This is a key + // difference from how works and a major reason we call this a + // "to" value instead of a "href". + if (!isPathRelative && toPathname.startsWith("..")) { + let toSegments = toPathname.split("/"); + while (toSegments[0] === "..") { + toSegments.shift(); + routePathnameIndex -= 1; + } + to.pathname = toSegments.join("/"); + } + from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/"; + } + let path = resolvePath(to, from); + + // Ensure the pathname has a trailing slash if the original "to" had one + let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); + // Or if this was a link to the current path which has a trailing slash + let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/"); + if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) { + path.pathname += "/"; + } + return path; +} + +/** + * @private + */ +function getToPathname(to) { + // Empty strings should be treated the same as / paths + return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname; +} + +/** + * @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, responseInit) { + this.pendingKeysSet = new Set(); + this.subscribers = new Set(); + this.deferredKeys = []; + invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects"); + + // Set up an AbortController + Promise we can race against to exit early + // cancellation + let reject; + this.abortPromise = new Promise((_, r) => reject = r); + this.controller = new AbortController(); + let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted")); + this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort); + this.controller.signal.addEventListener("abort", onAbort); + this.data = Object.entries(data).reduce((acc, _ref2) => { + let [key, value] = _ref2; + return Object.assign(acc, { + [key]: this.trackPromise(key, value) + }); + }, {}); + if (this.done) { + // All incoming values were resolved + this.unlistenAbortSignal(); + } + this.init = responseInit; + } + trackPromise(key, value) { + if (!(value instanceof Promise)) { + return value; + } + this.deferredKeys.push(key); + this.pendingKeysSet.add(key); + + // We store a little wrapper promise that will be extended with + // _data/_error props upon resolve/reject + let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error)); + + // Register rejection listeners to avoid uncaught promise rejections on + // errors or aborted deferred values + promise.catch(() => {}); + Object.defineProperty(promise, "_tracked", { + get: () => true + }); + return promise; + } + onSettle(promise, key, error, data) { + if (this.controller.signal.aborted && error instanceof AbortedDeferredError) { + this.unlistenAbortSignal(); + Object.defineProperty(promise, "_error", { + get: () => error + }); + return Promise.reject(error); + } + this.pendingKeysSet.delete(key); + if (this.done) { + // Nothing left to abort! + this.unlistenAbortSignal(); + } + + // If the promise was resolved/rejected with undefined, we'll throw an error as you + // should always resolve with a value or null + if (error === undefined && data === undefined) { + let undefinedError = new Error("Deferred data for key \"" + key + "\" resolved/rejected with `undefined`, " + "you must resolve/reject with a value or `null`."); + Object.defineProperty(promise, "_error", { + get: () => undefinedError + }); + this.emit(false, key); + return Promise.reject(undefinedError); + } + if (data === undefined) { + Object.defineProperty(promise, "_error", { + get: () => error + }); + this.emit(false, key); + return Promise.reject(error); + } + Object.defineProperty(promise, "_data", { + get: () => data + }); + this.emit(false, key); + return data; + } + emit(aborted, settledKey) { + this.subscribers.forEach(subscriber => subscriber(aborted, settledKey)); + } + subscribe(fn) { + this.subscribers.add(fn); + return () => this.subscribers.delete(fn); + } + cancel() { + this.controller.abort(); + this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k)); + this.emit(true); + } + async resolveData(signal) { + let aborted = false; + if (!this.done) { + let onAbort = () => this.cancel(); + signal.addEventListener("abort", onAbort); + aborted = await new Promise(resolve => { + this.subscribe(aborted => { + signal.removeEventListener("abort", onAbort); + if (aborted || this.done) { + resolve(aborted); + } + }); + }); + } + return aborted; + } + get done() { + return this.pendingKeysSet.size === 0; + } + get unwrappedData() { + invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds"); + return Object.entries(this.data).reduce((acc, _ref3) => { + let [key, value] = _ref3; + return Object.assign(acc, { + [key]: unwrapTrackedPromise(value) + }); + }, {}); + } + get pendingKeys() { + return Array.from(this.pendingKeysSet); + } +} +function isTrackedPromise(value) { + return value instanceof Promise && value._tracked === true; +} +function unwrapTrackedPromise(value) { + if (!isTrackedPromise(value)) { + return value; + } + if (value._error) { + throw value._error; + } + return value._data; +} +const defer = function defer(data, init) { + if (init === void 0) { + init = {}; + } + let responseInit = typeof init === "number" ? { + status: init + } : init; + return new DeferredData(data, responseInit); +}; +/** + * A redirect response. Sets the status code and the `Location` header. + * Defaults to "302 Found". + */ +const redirect = function redirect(url, init) { + if (init === void 0) { + init = 302; + } + let responseInit = init; + if (typeof responseInit === "number") { + responseInit = { + status: responseInit + }; + } else if (typeof responseInit.status === "undefined") { + responseInit.status = 302; + } + let headers = new Headers(responseInit.headers); + headers.set("Location", url); + return new Response(null, _extends({}, responseInit, { + headers + })); +}; + +/** + * A redirect response that will force a document reload to the new location. + * Sets the status code and the `Location` header. + * Defaults to "302 Found". + */ +const redirectDocument = (url, init) => { + let response = redirect(url, init); + response.headers.set("X-Remix-Reload-Document", "true"); + return response; +}; +/** + * @private + * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies + * + * We don't export the class for public use since it's an implementation + * detail, but we export the interface above so folks can build their own + * abstractions around instances via isRouteErrorResponse() + */ +class ErrorResponseImpl { + constructor(status, statusText, data, internal) { + if (internal === void 0) { + internal = false; + } + this.status = status; + this.statusText = statusText || ""; + this.internal = internal; + if (data instanceof Error) { + this.data = data.toString(); + this.error = data; + } else { + this.data = data; + } + } +} + +/** + * Check if the given error is an ErrorResponse generated from a 4xx/5xx + * Response thrown from an action/loader + */ +function isRouteErrorResponse(error) { + return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error; +} + +//////////////////////////////////////////////////////////////////////////////// +//#region Types and Constants +//////////////////////////////////////////////////////////////////////////////// + +/** + * A Router instance manages all navigation and data loading/mutations + */ +/** + * State maintained internally by the router. During a navigation, all states + * reflect the the "old" location unless otherwise noted. + */ +/** + * Data that can be passed into hydrate a Router from SSR + */ +/** + * Future flags to toggle new feature behavior + */ +/** + * Initialization options for createRouter + */ +/** + * State returned from a server-side query() call + */ +/** + * A StaticHandler instance manages a singular SSR navigation/fetch event + */ +/** + * Subscriber function signature for changes to router state + */ +/** + * Function signature for determining the key to be used in scroll restoration + * for a given location + */ +/** + * Function signature for determining the current scroll position + */ +// Allowed for any navigation or fetch +// Only allowed for navigations +// Only allowed for submission navigations +/** + * Options for a navigate() call for a normal (non-submission) navigation + */ +/** + * Options for a navigate() call for a submission navigation + */ +/** + * Options to pass to navigate() for a navigation + */ +/** + * Options for a fetch() load + */ +/** + * Options for a fetch() submission + */ +/** + * Options to pass to fetch() + */ +/** + * Potential states for state.navigation + */ +/** + * Potential states for fetchers + */ +/** + * Cached info for active fetcher.load() instances so they can participate + * in revalidation + */ +/** + * Identified fetcher.load() calls that need to be revalidated + */ +/** + * Wrapper object to allow us to throw any response out from callLoaderOrAction + * for queryRouter while preserving whether or not it was thrown or returned + * from the loader/action + */ +const validMutationMethodsArr = ["post", "put", "patch", "delete"]; +const validMutationMethods = new Set(validMutationMethodsArr); +const validRequestMethodsArr = ["get", ...validMutationMethodsArr]; +const validRequestMethods = new Set(validRequestMethodsArr); +const redirectStatusCodes = new Set([301, 302, 303, 307, 308]); +const redirectPreserveMethodStatusCodes = new Set([307, 308]); +const IDLE_NAVIGATION = { + state: "idle", + location: undefined, + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined +}; +const IDLE_FETCHER = { + state: "idle", + data: undefined, + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined +}; +const IDLE_BLOCKER = { + state: "unblocked", + proceed: undefined, + reset: undefined, + location: undefined +}; +const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; +const defaultMapRouteProperties = route => ({ + hasErrorBoundary: Boolean(route.hasErrorBoundary) +}); +const TRANSITIONS_STORAGE_KEY = "remix-router-transitions"; + +//#endregion + +//////////////////////////////////////////////////////////////////////////////// +//#region createRouter +//////////////////////////////////////////////////////////////////////////////// + +/** + * Create a router and listen to history POP navigations + */ +function createRouter(init) { + const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined; + const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined"; + const isServer = !isBrowser; + invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter"); + let mapRouteProperties; + if (init.mapRouteProperties) { + mapRouteProperties = init.mapRouteProperties; + } else if (init.detectErrorBoundary) { + // If they are still using the deprecated version, wrap it with the new API + let detectErrorBoundary = init.detectErrorBoundary; + mapRouteProperties = route => ({ + hasErrorBoundary: detectErrorBoundary(route) + }); + } else { + mapRouteProperties = defaultMapRouteProperties; + } + + // Routes keyed by ID + let manifest = {}; + // Routes in tree format for matching + let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest); + let inFlightDataRoutes; + let basename = init.basename || "/"; + // Config driven behavior flags + let future = _extends({ + v7_fetcherPersist: false, + v7_normalizeFormMethod: false, + v7_partialHydration: false, + v7_prependBasename: false, + v7_relativeSplatPath: false + }, init.future); + // Cleanup function for history + let unlistenHistory = null; + // Externally-provided functions to call on all state changes + let subscribers = new Set(); + // Externally-provided object to hold scroll restoration locations during routing + let savedScrollPositions = null; + // Externally-provided function to get scroll restoration keys + let getScrollRestorationKey = null; + // Externally-provided function to get current scroll position + let getScrollPosition = null; + // One-time flag to control the initial hydration scroll restoration. Because + // we don't get the saved positions from until _after_ + // the initial render, we need to manually trigger a separate updateState to + // send along the restoreScrollPosition + // Set to true if we have `hydrationData` since we assume we were SSR'd and that + // SSR did the initial scroll restoration. + let initialScrollRestored = init.hydrationData != null; + let initialMatches = matchRoutes(dataRoutes, init.history.location, basename); + let 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 error = getInternalRouterError(404, { + pathname: init.history.location.pathname + }); + let { + matches, + route + } = getShortCircuitMatches(dataRoutes); + initialMatches = matches; + initialErrors = { + [route.id]: error + }; + } + let initialized; + let hasLazyRoutes = initialMatches.some(m => m.route.lazy); + let hasLoaders = initialMatches.some(m => m.route.loader); + if (hasLazyRoutes) { + // All initialMatches need to be loaded before we're ready. If we have lazy + // functions around still then we'll need to run them in initialize() + initialized = false; + } else if (!hasLoaders) { + // If we've got no loaders to run, then we're good to go + initialized = true; + } else if (future.v7_partialHydration) { + // If partial hydration is enabled, we're initialized so long as we were + // provided with hydrationData for every route with a loader, and no loaders + // were marked for explicit hydration + let loaderData = init.hydrationData ? init.hydrationData.loaderData : null; + let errors = init.hydrationData ? init.hydrationData.errors : null; + initialized = initialMatches.every(m => m.route.loader && m.route.loader.hydrate !== true && (loaderData && loaderData[m.route.id] !== undefined || errors && errors[m.route.id] !== undefined)); + } else { + // Without partial hydration - we're initialized if we were provided any + // hydrationData - which is expected to be complete + initialized = init.hydrationData != null; + } + let router; + let state = { + historyAction: init.history.action, + location: init.history.location, + matches: initialMatches, + initialized, + navigation: IDLE_NAVIGATION, + // Don't restore on initial updateState() if we were SSR'd + restoreScrollPosition: init.hydrationData != null ? false : null, + preventScrollReset: false, + revalidation: "idle", + loaderData: init.hydrationData && init.hydrationData.loaderData || {}, + actionData: init.hydrationData && init.hydrationData.actionData || null, + errors: init.hydrationData && init.hydrationData.errors || initialErrors, + fetchers: new Map(), + blockers: new Map() + }; + + // -- Stateful internal variables to manage navigations -- + // Current navigation in progress (to be committed in completeNavigation) + let pendingAction = Action.Pop; + + // Should the current navigation prevent the scroll reset if scroll cannot + // be restored? + let pendingPreventScrollReset = false; + + // AbortController for the active navigation + let pendingNavigationController; + + // Should the current navigation enable document.startViewTransition? + let pendingViewTransitionEnabled = false; + + // Store applied view transitions so we can apply them on POP + let appliedViewTransitions = new Map(); + + // Cleanup function for persisting applied transitions to sessionStorage + let removePageHideEventListener = null; + + // We use this to avoid touching history in completeNavigation if a + // revalidation is entirely uninterrupted + let isUninterruptedRevalidation = false; + + // Use this internal flag to force revalidation of all loaders: + // - submissions (completed or interrupted) + // - useRevalidator() + // - X-Remix-Revalidate (from redirect) + let isRevalidationRequired = false; + + // Use this internal array to capture routes that require revalidation due + // to a cancelled deferred on action submission + let cancelledDeferredRoutes = []; + + // Use this internal array to capture fetcher loads that were cancelled by an + // action navigation and require revalidation + let cancelledFetcherLoads = []; + + // AbortControllers for any in-flight fetchers + let fetchControllers = new Map(); + + // Track loads based on the order in which they started + let incrementingLoadId = 0; + + // Track the outstanding pending navigation data load to be compared against + // the globally incrementing load when a fetcher load lands after a completed + // navigation + let pendingNavigationLoadId = -1; + + // Fetchers that triggered data reloads as a result of their actions + let fetchReloadIds = new Map(); + + // Fetchers that triggered redirect navigations + let fetchRedirectIds = new Set(); + + // Most recent href/match for fetcher.load calls for fetchers + let fetchLoadMatches = new Map(); + + // Ref-count mounted fetchers so we know when it's ok to clean them up + let activeFetchers = new Map(); + + // Fetchers that have requested a delete when using v7_fetcherPersist, + // they'll be officially removed after they return to idle + let deletedFetchers = new Set(); + + // Store DeferredData instances for active route matches. When a + // route loader returns defer() we stick one in here. Then, when a nested + // promise resolves we update loaderData. If a new navigation starts we + // cancel active deferreds for eliminated routes. + let activeDeferreds = new Map(); + + // Store blocker functions in a separate Map outside of router state since + // we don't need to update UI state if they change + let blockerFunctions = new Map(); + + // Flag to ignore the next history update, so we can revert the URL change on + // a POP navigation that was blocked by the user without touching router state + let ignoreNextHistoryUpdate = false; + + // Initialize the router, all side effects should be kicked off from here. + // Implemented as a Fluent API for ease of: + // let router = createRouter(init).initialize(); + function initialize() { + // If history informs us of a POP navigation, start the navigation but do not update + // state. We'll update our own state once the navigation completes + unlistenHistory = init.history.listen(_ref => { + let { + action: historyAction, + location, + delta + } = _ref; + // Ignore this event if it was just us resetting the URL from a + // blocked POP navigation + if (ignoreNextHistoryUpdate) { + ignoreNextHistoryUpdate = false; + return; + } + warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location " + "that was not created by @remix-run/router. This will fail silently in " + "production. This can happen if you are navigating outside the router " + "via `window.history.pushState`/`window.location.hash` instead of using " + "router navigation APIs. This can also happen if you are using " + "createHashRouter and the user manually changes the URL."); + let blockerKey = shouldBlockNavigation({ + currentLocation: state.location, + nextLocation: location, + historyAction + }); + if (blockerKey && delta != null) { + // Restore the URL to match the current UI, but don't update router state + ignoreNextHistoryUpdate = true; + init.history.go(delta * -1); + + // Put the blocker into a blocked state + updateBlocker(blockerKey, { + state: "blocked", + location, + proceed() { + updateBlocker(blockerKey, { + state: "proceeding", + proceed: undefined, + reset: undefined, + location + }); + // Re-do the same POP navigation we just blocked + init.history.go(delta); + }, + reset() { + let blockers = new Map(state.blockers); + blockers.set(blockerKey, IDLE_BLOCKER); + updateState({ + blockers + }); + } + }); + return; + } + return startNavigation(historyAction, location); + }); + if (isBrowser) { + // FIXME: This feels gross. How can we cleanup the lines between + // scrollRestoration/appliedTransitions persistance? + restoreAppliedTransitions(routerWindow, appliedViewTransitions); + let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions); + routerWindow.addEventListener("pagehide", _saveAppliedTransitions); + removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions); + } + + // Kick off initial data load if needed. Use Pop to avoid modifying history + // Note we don't do any handling of lazy here. For SPA's it'll get handled + // in the normal navigation flow. For SSR it's expected that lazy modules are + // resolved prior to router creation since we can't go into a fallbackElement + // UI for SSR'd apps + if (!state.initialized) { + startNavigation(Action.Pop, state.location, { + initialHydration: true + }); + } + return router; + } + + // Clean up a router and it's side effects + function dispose() { + if (unlistenHistory) { + unlistenHistory(); + } + if (removePageHideEventListener) { + removePageHideEventListener(); + } + subscribers.clear(); + pendingNavigationController && pendingNavigationController.abort(); + state.fetchers.forEach((_, key) => deleteFetcher(key)); + state.blockers.forEach((_, key) => deleteBlocker(key)); + } + + // Subscribe to state updates for the router + function subscribe(fn) { + subscribers.add(fn); + return () => subscribers.delete(fn); + } + + // Update our state and notify the calling context of the change + function updateState(newState, opts) { + if (opts === void 0) { + opts = {}; + } + state = _extends({}, state, newState); + + // Prep fetcher cleanup so we can tell the UI which fetcher data entries + // can be removed + let completedFetchers = []; + let deletedFetchersKeys = []; + if (future.v7_fetcherPersist) { + state.fetchers.forEach((fetcher, key) => { + if (fetcher.state === "idle") { + if (deletedFetchers.has(key)) { + // Unmounted from the UI and can be totally removed + deletedFetchersKeys.push(key); + } else { + // Returned to idle but still mounted in the UI, so semi-remains for + // revalidations and such + completedFetchers.push(key); + } + } + }); + } + + // Iterate over a local copy so that if flushSync is used and we end up + // removing and adding a new subscriber due to the useCallback dependencies, + // we don't get ourselves into a loop calling the new subscriber immediately + [...subscribers].forEach(subscriber => subscriber(state, { + deletedFetchers: deletedFetchersKeys, + unstable_viewTransitionOpts: opts.viewTransitionOpts, + unstable_flushSync: opts.flushSync === true + })); + + // Remove idle fetchers from state since we only care about in-flight fetchers. + if (future.v7_fetcherPersist) { + completedFetchers.forEach(key => state.fetchers.delete(key)); + deletedFetchersKeys.forEach(key => deleteFetcher(key)); + } + } + + // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION + // and setting state.[historyAction/location/matches] to the new route. + // - Location is a required param + // - Navigation will always be set to IDLE_NAVIGATION + // - Can pass any other state in newState + function completeNavigation(location, newState, _temp) { + var _location$state, _location$state2; + let { + flushSync + } = _temp === void 0 ? {} : _temp; + // Deduce if we're in a loading/actionReload state: + // - We have committed actionData in the store + // - The current navigation was a mutation submission + // - We're past the submitting state and into the loading state + // - The location being loaded is not the result of a redirect + let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true; + let actionData; + if (newState.actionData) { + if (Object.keys(newState.actionData).length > 0) { + actionData = newState.actionData; + } else { + // Empty actionData -> clear prior actionData due to an action error + actionData = null; + } + } else if (isActionReload) { + // Keep the current data if we're wrapping up the action reload + actionData = state.actionData; + } else { + // Clear actionData on any other completed navigations + actionData = null; + } + + // Always preserve any existing loaderData from re-used routes + let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData; + + // On a successful navigation we can assume we got through all blockers + // so we can start fresh + let blockers = state.blockers; + if (blockers.size > 0) { + blockers = new Map(blockers); + blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER)); + } + + // Always respect the user flag. Otherwise don't reset on mutation + // submission navigations unless they redirect + let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true; + if (inFlightDataRoutes) { + dataRoutes = inFlightDataRoutes; + inFlightDataRoutes = undefined; + } + if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) { + init.history.push(location, location.state); + } else if (pendingAction === Action.Replace) { + init.history.replace(location, location.state); + } + let viewTransitionOpts; + + // On POP, enable transitions if they were enabled on the original navigation + if (pendingAction === Action.Pop) { + // Forward takes precedence so they behave like the original navigation + let priorPaths = appliedViewTransitions.get(state.location.pathname); + if (priorPaths && priorPaths.has(location.pathname)) { + viewTransitionOpts = { + currentLocation: state.location, + nextLocation: location + }; + } else if (appliedViewTransitions.has(location.pathname)) { + // If we don't have a previous forward nav, assume we're popping back to + // the new location and enable if that location previously enabled + viewTransitionOpts = { + currentLocation: location, + nextLocation: state.location + }; + } + } else if (pendingViewTransitionEnabled) { + // Store the applied transition on PUSH/REPLACE + let toPaths = appliedViewTransitions.get(state.location.pathname); + if (toPaths) { + toPaths.add(location.pathname); + } else { + toPaths = new Set([location.pathname]); + appliedViewTransitions.set(state.location.pathname, toPaths); + } + viewTransitionOpts = { + currentLocation: state.location, + nextLocation: location + }; + } + updateState(_extends({}, newState, { + // matches, errors, fetchers go through as-is + actionData, + loaderData, + historyAction: pendingAction, + location, + initialized: true, + navigation: IDLE_NAVIGATION, + revalidation: "idle", + restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches), + preventScrollReset, + blockers + }), { + viewTransitionOpts, + flushSync: flushSync === true + }); + + // Reset stateful navigation vars + pendingAction = Action.Pop; + pendingPreventScrollReset = false; + pendingViewTransitionEnabled = false; + isUninterruptedRevalidation = false; + isRevalidationRequired = false; + cancelledDeferredRoutes = []; + 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 normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative); + let { + path, + submission, + error + } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts); + let currentLocation = state.location; + let nextLocation = createLocation(state.location, path, opts && opts.state); + + // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded + // URL from window.location, so we need to encode it here so the behavior + // remains the same as POP and non-data-router usages. new URL() does all + // the same encoding we'd get from a history.pushState/window.location read + // without having to touch history + nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation)); + let userReplace = opts && opts.replace != null ? opts.replace : undefined; + let historyAction = Action.Push; + if (userReplace === true) { + historyAction = Action.Replace; + } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) { + // By default on submissions to the current location we REPLACE so that + // users don't have to double-click the back button to get to the prior + // location. If the user redirects to a different location from the + // action/loader this will be ignored and the redirect will be a PUSH + historyAction = Action.Replace; + } + let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined; + let flushSync = (opts && opts.unstable_flushSync) === true; + let blockerKey = shouldBlockNavigation({ + currentLocation, + nextLocation, + historyAction + }); + if (blockerKey) { + // Put the blocker into a blocked state + updateBlocker(blockerKey, { + state: "blocked", + location: nextLocation, + proceed() { + updateBlocker(blockerKey, { + state: "proceeding", + proceed: undefined, + reset: undefined, + location: nextLocation + }); + // Send the same navigation through + navigate(to, opts); + }, + reset() { + let blockers = new Map(state.blockers); + blockers.set(blockerKey, IDLE_BLOCKER); + updateState({ + blockers + }); + } + }); + return; + } + return await startNavigation(historyAction, nextLocation, { + submission, + // Send through the formData serialization error if we have one so we can + // render at the right error boundary after we match routes + pendingError: error, + preventScrollReset, + replace: opts && opts.replace, + enableViewTransition: opts && opts.unstable_viewTransition, + flushSync + }); + } + + // Revalidate all current loaders. If a navigation is in progress or if this + // is interrupted by a navigation, allow this to "succeed" by calling all + // loaders during the next loader round + function revalidate() { + interruptActiveLoads(); + updateState({ + revalidation: "loading" + }); + + // If we're currently submitting an action, we don't need to start a new + // navigation, we'll just let the follow up loader execution call all loaders + if (state.navigation.state === "submitting") { + return; + } + + // If we're currently in an idle state, start a new navigation for the current + // action/location and mark it as uninterrupted, which will skip the history + // update in completeNavigation + if (state.navigation.state === "idle") { + startNavigation(state.historyAction, state.location, { + startUninterruptedRevalidation: true + }); + return; + } + + // Otherwise, if we're currently in a loading state, just start a new + // navigation to the navigation.location but do not trigger an uninterrupted + // revalidation so that history correctly updates once the navigation completes + startNavigation(pendingAction || state.historyAction, state.navigation.location, { + overrideNavigation: state.navigation + }); + } + + // Start a navigation to the given action/location. Can optionally provide a + // overrideNavigation which will override the normalLoad in the case of a redirect + // navigation + async function startNavigation(historyAction, location, opts) { + // Abort any in-progress navigations and start a new one. Unset any ongoing + // uninterrupted revalidations unless told otherwise, since we want this + // new navigation to update history normally + pendingNavigationController && pendingNavigationController.abort(); + pendingNavigationController = null; + pendingAction = historyAction; + isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; + + // Save the current scroll position every time we start a new navigation, + // and track whether we should reset scroll on completion + saveScrollPosition(state.location, state.matches); + pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; + pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true; + let routesToUse = inFlightDataRoutes || dataRoutes; + let loadingNavigation = opts && opts.overrideNavigation; + let matches = matchRoutes(routesToUse, location, basename); + let flushSync = (opts && opts.flushSync) === true; + + // Short circuit with a 404 on the root error boundary if we match nothing + if (!matches) { + let error = getInternalRouterError(404, { + pathname: location.pathname + }); + let { + matches: notFoundMatches, + route + } = getShortCircuitMatches(routesToUse); + // Cancel all pending deferred on 404s since we don't keep any routes + cancelActiveDeferreds(); + completeNavigation(location, { + matches: notFoundMatches, + loaderData: {}, + errors: { + [route.id]: error + } + }, { + flushSync + }); + return; + } + + // Short circuit if it's only a hash change and not a revalidation or + // mutation submission. + // + // Ignore on initial page loads because since the initial load will always + // be "same hash". For example, on /page#hash and submit a + // which will default to a navigation to /page + if (state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) { + completeNavigation(location, { + matches + }, { + flushSync + }); + return; + } + + // Create a controller/Request for this navigation + pendingNavigationController = new AbortController(); + let request = createClientSideRequest(init.history, 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 && isMutationMethod(opts.submission.formMethod)) { + // Call action if we received an action submission + let actionOutput = await handleAction(request, location, opts.submission, matches, { + replace: opts.replace, + flushSync + }); + if (actionOutput.shortCircuited) { + return; + } + pendingActionData = actionOutput.pendingActionData; + pendingError = actionOutput.pendingActionError; + loadingNavigation = getLoadingNavigation(location, opts.submission); + flushSync = false; + + // Create a GET request for the loaders + request = new Request(request.url, { + signal: request.signal + }); + } + + // Call loaders + let { + shortCircuited, + loaderData, + errors + } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionData, pendingError); + if (shortCircuited) { + return; + } + + // Clean up now that the action/loaders have completed. Don't clean up if + // we short circuited because pendingNavigationController will have already + // been assigned to a new controller for the next navigation + pendingNavigationController = null; + completeNavigation(location, _extends({ + matches + }, pendingActionData ? { + actionData: pendingActionData + } : {}, { + 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) { + if (opts === void 0) { + opts = {}; + } + interruptActiveLoads(); + + // Put us in a submitting state + let navigation = getSubmittingNavigation(location, submission); + updateState({ + navigation + }, { + flushSync: opts.flushSync === true + }); + + // Call our action and get the result + let result; + let actionMatch = getTargetMatch(matches, location); + if (!actionMatch.route.action && !actionMatch.route.lazy) { + result = { + type: ResultType.error, + error: getInternalRouterError(405, { + method: request.method, + pathname: location.pathname, + routeId: actionMatch.route.id + }) + }; + } else { + result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); + if (request.signal.aborted) { + return { + shortCircuited: true + }; + } + } + if (isRedirectResult(result)) { + let replace; + if (opts && opts.replace != null) { + replace = opts.replace; + } else { + // If the user didn't explicity indicate replace behavior, replace if + // we redirected to the exact same location we're currently at to avoid + // double back-buttons + replace = result.location === state.location.pathname + state.location.search; + } + await startRedirectNavigation(state, result, { + submission, + 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 { + // Send back an empty object we can use to clear out any prior actionData + pendingActionData: {}, + pendingActionError: { + [boundaryMatch.route.id]: result.error + } + }; + } + if (isDeferredResult(result)) { + throw getInternalRouterError(400, { + type: "defer-action" + }); + } + return { + pendingActionData: { + [actionMatch.route.id]: result.data + } + }; + } + + // Call all applicable loaders for the given matches, handling redirects, + // errors, etc. + async function handleLoaders(request, location, matches, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionData, pendingError) { + // Figure out the right navigation we want to use for data loading + let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission); + + // If this was a redirect from an action we don't have a "submission" but + // we have it on the loading navigation so use that if available + let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation); + let routesToUse = inFlightDataRoutes || dataRoutes; + let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError); + + // Cancel pending deferreds for no-longer-matched routes or routes we're + // about to reload. Note that if this is an action reload we would have + // already cancelled all pending deferreds so this would be a no-op + cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); + pendingNavigationLoadId = ++incrementingLoadId; + + // Short circuit if we have no loaders to run + if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) { + let updatedFetchers = markFetchRedirectsDone(); + completeNavigation(location, _extends({ + matches, + loaderData: {}, + // Commit pending error if we're short circuiting + errors: pendingError || null + }, pendingActionData ? { + actionData: pendingActionData + } : {}, updatedFetchers ? { + fetchers: new Map(state.fetchers) + } : {}), { + flushSync + }); + 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 we have partialHydration enabled, then don't update the state for the + // initial data load since iot's not a "navigation" + if (!isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration)) { + revalidatingFetchers.forEach(rf => { + let fetcher = state.fetchers.get(rf.key); + let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined); + state.fetchers.set(rf.key, revalidatingFetcher); + }); + let actionData = pendingActionData || state.actionData; + updateState(_extends({ + navigation: loadingNavigation + }, actionData ? Object.keys(actionData).length === 0 ? { + actionData: null + } : { + actionData + } : {}, revalidatingFetchers.length > 0 ? { + fetchers: new Map(state.fetchers) + } : {}), { + flushSync + }); + } + revalidatingFetchers.forEach(rf => { + if (fetchControllers.has(rf.key)) { + abortFetcher(rf.key); + } + if (rf.controller) { + // Fetchers use an independent AbortController so that aborting a fetcher + // (via deleteFetcher) does not abort the triggering navigation that + // triggered the revalidation + fetchControllers.set(rf.key, rf.controller); + } + }); + + // Proxy navigation abort through to revalidation fetchers + let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key)); + if (pendingNavigationController) { + pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations); + } + let { + results, + loaderResults, + fetcherResults + } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request); + if (request.signal.aborted) { + return { + shortCircuited: true + }; + } + + // Clean up _after_ loaders have completed. Don't clean up if we short + // circuited because fetchControllers would have been aborted and + // reassigned to new controllers for the next navigation + if (pendingNavigationController) { + pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations); + } + revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key)); + + // If any loaders returned a redirect Response, start a new REPLACE navigation + let redirect = findRedirect(results); + if (redirect) { + if (redirect.idx >= matchesToLoad.length) { + // If this redirect came from a fetcher make sure we mark it in + // fetchRedirectIds so it doesn't get revalidated on the next set of + // loader executions + let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; + fetchRedirectIds.add(fetcherKey); + } + await startRedirectNavigation(state, redirect.result, { + 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); + } + }); + }); + let updatedFetchers = markFetchRedirectsDone(); + let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); + let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0; + return _extends({ + loaderData, + errors + }, shouldUpdateFetchers ? { + fetchers: new Map(state.fetchers) + } : {}); + } + + // Trigger a fetcher load/submit for the given fetcher key + function fetch(key, routeId, href, opts) { + if (isServer) { + throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback."); + } + if (fetchControllers.has(key)) abortFetcher(key); + let flushSync = (opts && opts.unstable_flushSync) === true; + let routesToUse = inFlightDataRoutes || dataRoutes; + let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative); + let matches = matchRoutes(routesToUse, normalizedPath, basename); + if (!matches) { + setFetcherError(key, routeId, getInternalRouterError(404, { + pathname: normalizedPath + }), { + flushSync + }); + return; + } + let { + path, + submission, + error + } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts); + if (error) { + setFetcherError(key, routeId, error, { + flushSync + }); + return; + } + let match = getTargetMatch(matches, path); + pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; + if (submission && isMutationMethod(submission.formMethod)) { + handleFetcherAction(key, routeId, path, match, matches, flushSync, submission); + return; + } + + // Store off the match so we can call it's shouldRevalidate on subsequent + // revalidations + fetchLoadMatches.set(key, { + routeId, + path + }); + handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission); + } + + // Call the action for the matched fetcher.submit(), and then handle redirects, + // errors, and revalidation + async function handleFetcherAction(key, routeId, path, match, requestMatches, flushSync, submission) { + interruptActiveLoads(); + fetchLoadMatches.delete(key); + if (!match.route.action && !match.route.lazy) { + let error = getInternalRouterError(405, { + method: submission.formMethod, + pathname: path, + routeId: routeId + }); + setFetcherError(key, routeId, error, { + flushSync + }); + return; + } + + // Put this fetcher into it's submitting state + let existingFetcher = state.fetchers.get(key); + updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), { + flushSync + }); + + // Call the action for the fetcher + let abortController = new AbortController(); + let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission); + fetchControllers.set(key, abortController); + let originatingLoadId = incrementingLoadId; + let actionResult = await callLoaderOrAction("action", fetchRequest, match, requestMatches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); + if (fetchRequest.signal.aborted) { + // We can delete this so long as we weren't aborted by our own fetcher + // re-submit which would have put _new_ controller is in fetchControllers + if (fetchControllers.get(key) === abortController) { + fetchControllers.delete(key); + } + return; + } + + // When using v7_fetcherPersist, we don't want errors bubbling up to the UI + // or redirects processed for unmounted fetchers so we just revert them to + // idle + if (future.v7_fetcherPersist && deletedFetchers.has(key)) { + if (isRedirectResult(actionResult) || isErrorResult(actionResult)) { + updateFetcherState(key, getDoneFetcher(undefined)); + return; + } + // Let SuccessResult's fall through for revalidation + } else { + if (isRedirectResult(actionResult)) { + fetchControllers.delete(key); + if (pendingNavigationLoadId > originatingLoadId) { + // A new navigation was kicked off after our action started, so that + // should take precedence over this redirect navigation. We already + // set isRevalidationRequired so all loaders for the new route should + // fire unless opted out via shouldRevalidate + updateFetcherState(key, getDoneFetcher(undefined)); + return; + } else { + fetchRedirectIds.add(key); + updateFetcherState(key, getLoadingFetcher(submission)); + return startRedirectNavigation(state, actionResult, { + fetcherSubmission: submission + }); + } + } + + // Process any non-redirect errors thrown + if (isErrorResult(actionResult)) { + setFetcherError(key, routeId, actionResult.error); + return; + } + } + if (isDeferredResult(actionResult)) { + throw getInternalRouterError(400, { + type: "defer-action" + }); + } + + // Start the data load for current matches, or the next location if we're + // in the middle of a navigation + let nextLocation = state.navigation.location || state.location; + let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal); + let routesToUse = inFlightDataRoutes || dataRoutes; + let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches; + invariant(matches, "Didn't find any matches after fetcher action"); + let loadId = ++incrementingLoadId; + fetchReloadIds.set(key, loadId); + let loadFetcher = getLoadingFetcher(submission, actionResult.data); + state.fetchers.set(key, loadFetcher); + let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, { + [match.route.id]: actionResult.data + }, undefined // No need to send through errors since we short circuit above + ); + + // Put all revalidating fetchers into the loading state, except for the + // current fetcher which we want to keep in it's current loading state which + // contains it's action submission info + action data + revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => { + let staleKey = rf.key; + let existingFetcher = state.fetchers.get(staleKey); + let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined); + state.fetchers.set(staleKey, revalidatingFetcher); + if (fetchControllers.has(staleKey)) { + abortFetcher(staleKey); + } + if (rf.controller) { + fetchControllers.set(staleKey, rf.controller); + } + }); + updateState({ + fetchers: new Map(state.fetchers) + }); + let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key)); + abortController.signal.addEventListener("abort", abortPendingFetchRevalidations); + let { + results, + loaderResults, + fetcherResults + } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest); + if (abortController.signal.aborted) { + return; + } + abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations); + fetchReloadIds.delete(key); + fetchControllers.delete(key); + revalidatingFetchers.forEach(r => fetchControllers.delete(r.key)); + let redirect = findRedirect(results); + if (redirect) { + if (redirect.idx >= matchesToLoad.length) { + // If this redirect came from a fetcher make sure we mark it in + // fetchRedirectIds so it doesn't get revalidated on the next set of + // loader executions + let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; + fetchRedirectIds.add(fetcherKey); + } + return startRedirectNavigation(state, redirect.result); + } + + // Process and commit output from loaders + let { + loaderData, + errors + } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds); + + // Since we let revalidations complete even if the submitting fetcher was + // deleted, only put it back to idle if it hasn't been deleted + if (state.fetchers.has(key)) { + let doneFetcher = getDoneFetcher(actionResult.data); + state.fetchers.set(key, doneFetcher); + } + abortStaleFetchLoads(loadId); + + // If we are currently in a navigation loading state and this fetcher is + // more recent than the navigation, we want the newer data so abort the + // navigation and complete it with the fetcher data + if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) { + invariant(pendingAction, "Expected pending action"); + pendingNavigationController && pendingNavigationController.abort(); + completeNavigation(state.navigation.location, { + matches, + loaderData, + errors, + fetchers: new Map(state.fetchers) + }); + } else { + // otherwise just update with the fetcher data, preserving any existing + // loaderData for loaders that did not need to reload. We have to + // manually merge here since we aren't going through completeNavigation + updateState({ + errors, + loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors), + fetchers: new Map(state.fetchers) + }); + isRevalidationRequired = false; + } + } + + // Call the matched loader for fetcher.load(), handling redirects, errors, etc. + async function handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission) { + let existingFetcher = state.fetchers.get(key); + updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), { + flushSync + }); + + // Call the loader for this fetcher route match + let abortController = new AbortController(); + let fetchRequest = createClientSideRequest(init.history, path, abortController.signal); + fetchControllers.set(key, abortController); + let originatingLoadId = incrementingLoadId; + let result = await callLoaderOrAction("loader", fetchRequest, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); + + // Deferred isn't supported for fetcher loads, await everything and treat it + // as a normal load. resolveDeferredData will return undefined if this + // fetcher gets aborted, so we just leave result untouched and short circuit + // below if that happens + if (isDeferredResult(result)) { + result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result; + } + + // We can delete this so long as we weren't aborted by our our own fetcher + // re-load which would have put _new_ controller is in fetchControllers + if (fetchControllers.get(key) === abortController) { + fetchControllers.delete(key); + } + if (fetchRequest.signal.aborted) { + return; + } + + // We don't want errors bubbling up or redirects followed for unmounted + // fetchers, so short circuit here if it was removed from the UI + if (deletedFetchers.has(key)) { + updateFetcherState(key, getDoneFetcher(undefined)); + return; + } + + // If the loader threw a redirect Response, start a new REPLACE navigation + if (isRedirectResult(result)) { + if (pendingNavigationLoadId > originatingLoadId) { + // A new navigation was kicked off after our loader started, so that + // should take precedence over this redirect navigation + updateFetcherState(key, getDoneFetcher(undefined)); + return; + } else { + fetchRedirectIds.add(key); + await startRedirectNavigation(state, result); + return; + } + } + + // Process any non-redirect errors thrown + if (isErrorResult(result)) { + setFetcherError(key, routeId, result.error); + return; + } + invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); + + // Put the fetcher back into an idle state + updateFetcherState(key, getDoneFetcher(result.data)); + } + + /** + * Utility function to handle redirects returned from an action or loader. + * Normally, a redirect "replaces" the navigation that triggered it. So, for + * example: + * + * - user is on /a + * - user clicks a link to /b + * - loader for /b redirects to /c + * + * In a non-JS app the browser would track the in-flight navigation to /b and + * then replace it with /c when it encountered the redirect response. In + * the end it would only ever update the URL bar with /c. + * + * In client-side routing using pushState/replaceState, we aim to emulate + * this behavior and we also do not update history until the end of the + * navigation (including processed redirects). This means that we never + * actually touch history until we've processed redirects, so we just use + * the history action from the original navigation (PUSH or REPLACE). + */ + async function startRedirectNavigation(state, redirect, _temp2) { + let { + submission, + fetcherSubmission, + replace + } = _temp2 === void 0 ? {} : _temp2; + if (redirect.revalidate) { + isRevalidationRequired = true; + } + let redirectLocation = createLocation(state.location, redirect.location, { + _isRedirect: true + }); + invariant(redirectLocation, "Expected a location on the redirect navigation"); + if (isBrowser) { + let isDocumentReload = false; + if (redirect.reloadDocument) { + // Hard reload if the response contained X-Remix-Reload-Document + isDocumentReload = true; + } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) { + const url = init.history.createURL(redirect.location); + isDocumentReload = + // Hard reload if it's an absolute URL to a new origin + url.origin !== routerWindow.location.origin || + // Hard reload if it's an absolute URL that does not match our basename + stripBasename(url.pathname, basename) == null; + } + if (isDocumentReload) { + if (replace) { + routerWindow.location.replace(redirect.location); + } else { + routerWindow.location.assign(redirect.location); + } + return; + } + } + + // There's no need to abort on redirects, since we don't detect the + // redirect until the action/loaders have settled + pendingNavigationController = null; + let redirectHistoryAction = replace === true ? Action.Replace : Action.Push; + + // Use the incoming submission if provided, fallback on the active one in + // state.navigation + let { + formMethod, + formAction, + formEncType + } = state.navigation; + if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) { + submission = getSubmissionFromNavigation(state.navigation); + } + + // If this was a 307/308 submission we want to preserve the HTTP method and + // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the + // redirected location + let activeSubmission = submission || fetcherSubmission; + if (redirectPreserveMethodStatusCodes.has(redirect.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) { + await startNavigation(redirectHistoryAction, redirectLocation, { + submission: _extends({}, activeSubmission, { + formAction: redirect.location + }), + // Preserve this flag across redirects + preventScrollReset: pendingPreventScrollReset + }); + } else { + // If we have a navigation submission, we will preserve it through the + // redirect navigation + let overrideNavigation = getLoadingNavigation(redirectLocation, submission); + await startNavigation(redirectHistoryAction, redirectLocation, { + overrideNavigation, + // Send fetcher submissions through for shouldRevalidate + fetcherSubmission, + // Preserve this flag across redirects + preventScrollReset: pendingPreventScrollReset + }); + } + } + async function callLoadersAndMaybeResolveData(currentMatches, matches, 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(match => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath)), ...fetchersToLoad.map(f => { + if (f.matches && f.match && f.controller) { + return callLoaderOrAction("loader", createClientSideRequest(init.history, f.path, f.controller.signal), f.match, f.matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); + } else { + let error = { + type: ResultType.error, + error: getInternalRouterError(404, { + pathname: f.path + }) + }; + return error; + } + })]); + let loaderResults = results.slice(0, matchesToLoad.length); + let fetcherResults = results.slice(matchesToLoad.length); + await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, loaderResults.map(() => request.signal), false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(f => f.match), fetcherResults, fetchersToLoad.map(f => f.controller ? f.controller.signal : null), 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 updateFetcherState(key, fetcher, opts) { + if (opts === void 0) { + opts = {}; + } + state.fetchers.set(key, fetcher); + updateState({ + fetchers: new Map(state.fetchers) + }, { + flushSync: (opts && opts.flushSync) === true + }); + } + function setFetcherError(key, routeId, error, opts) { + if (opts === void 0) { + opts = {}; + } + let boundaryMatch = findNearestBoundary(state.matches, routeId); + deleteFetcher(key); + updateState({ + errors: { + [boundaryMatch.route.id]: error + }, + fetchers: new Map(state.fetchers) + }, { + flushSync: (opts && opts.flushSync) === true + }); + } + function getFetcher(key) { + if (future.v7_fetcherPersist) { + activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1); + // If this fetcher was previously marked for deletion, unmark it since we + // have a new instance + if (deletedFetchers.has(key)) { + deletedFetchers.delete(key); + } + } + return state.fetchers.get(key) || IDLE_FETCHER; + } + function deleteFetcher(key) { + let fetcher = state.fetchers.get(key); + // Don't abort the controller if this is a deletion of a fetcher.submit() + // in it's loading phase since - we don't want to abort the corresponding + // revalidation and want them to complete and land + if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) { + abortFetcher(key); + } + fetchLoadMatches.delete(key); + fetchReloadIds.delete(key); + fetchRedirectIds.delete(key); + deletedFetchers.delete(key); + state.fetchers.delete(key); + } + function deleteFetcherAndUpdateState(key) { + if (future.v7_fetcherPersist) { + let count = (activeFetchers.get(key) || 0) - 1; + if (count <= 0) { + activeFetchers.delete(key); + deletedFetchers.add(key); + } else { + activeFetchers.set(key, count); + } + } else { + deleteFetcher(key); + } + updateState({ + fetchers: new Map(state.fetchers) + }); + } + function abortFetcher(key) { + let controller = fetchControllers.get(key); + invariant(controller, "Expected fetch controller: " + key); + controller.abort(); + fetchControllers.delete(key); + } + function markFetchersDone(keys) { + for (let key of keys) { + let fetcher = getFetcher(key); + let doneFetcher = getDoneFetcher(fetcher.data); + state.fetchers.set(key, doneFetcher); + } + } + function markFetchRedirectsDone() { + let doneKeys = []; + let updatedFetchers = false; + for (let key of fetchRedirectIds) { + let fetcher = state.fetchers.get(key); + invariant(fetcher, "Expected fetcher: " + key); + if (fetcher.state === "loading") { + fetchRedirectIds.delete(key); + doneKeys.push(key); + updatedFetchers = true; + } + } + markFetchersDone(doneKeys); + return updatedFetchers; + } + function abortStaleFetchLoads(landedId) { + let yeetedKeys = []; + for (let [key, id] of fetchReloadIds) { + if (id < landedId) { + let fetcher = state.fetchers.get(key); + invariant(fetcher, "Expected fetcher: " + key); + if (fetcher.state === "loading") { + abortFetcher(key); + fetchReloadIds.delete(key); + yeetedKeys.push(key); + } + } + } + markFetchersDone(yeetedKeys); + return yeetedKeys.length > 0; + } + function getBlocker(key, fn) { + let blocker = state.blockers.get(key) || IDLE_BLOCKER; + if (blockerFunctions.get(key) !== fn) { + blockerFunctions.set(key, fn); + } + return blocker; + } + function deleteBlocker(key) { + state.blockers.delete(key); + blockerFunctions.delete(key); + } + + // Utility function to update blockers, ensuring valid state transitions + function updateBlocker(key, newBlocker) { + let blocker = state.blockers.get(key) || IDLE_BLOCKER; + + // Poor mans state machine :) + // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM + invariant(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state); + let blockers = new Map(state.blockers); + blockers.set(key, newBlocker); + updateState({ + blockers + }); + } + function shouldBlockNavigation(_ref2) { + let { + currentLocation, + nextLocation, + historyAction + } = _ref2; + if (blockerFunctions.size === 0) { + return; + } + + // We ony support a single active blocker at the moment since we don't have + // any compelling use cases for multi-blocker yet + if (blockerFunctions.size > 1) { + warning(false, "A router only supports one blocker at a time"); + } + let entries = Array.from(blockerFunctions.entries()); + let [blockerKey, blockerFunction] = entries[entries.length - 1]; + let blocker = state.blockers.get(blockerKey); + if (blocker && blocker.state === "proceeding") { + // If the blocker is currently proceeding, we don't need to re-check + // it and can let this navigation continue + return; + } + + // At this point, we know we're unblocked/blocked so we need to check the + // user-provided blocker function + if (blockerFunction({ + currentLocation, + nextLocation, + historyAction + })) { + return blockerKey; + } + } + function 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 || null; + + // 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 getScrollKey(location, matches) { + if (getScrollRestorationKey) { + let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData))); + return key || location.key; + } + return location.key; + } + function saveScrollPosition(location, matches) { + if (savedScrollPositions && getScrollPosition) { + let key = getScrollKey(location, matches); + savedScrollPositions[key] = getScrollPosition(); + } + } + function getSavedScrollPosition(location, matches) { + if (savedScrollPositions) { + let key = getScrollKey(location, matches); + let y = savedScrollPositions[key]; + if (typeof y === "number") { + return y; + } + } + return null; + } + function _internalSetRoutes(newRoutes) { + manifest = {}; + inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest); + } + router = { + get basename() { + return basename; + }, + get future() { + return future; + }, + get state() { + return state; + }, + get routes() { + return dataRoutes; + }, + get window() { + return routerWindow; + }, + initialize, + subscribe, + enableScrollRestoration, + navigate, + fetch, + revalidate, + // Passthrough to history-aware createHref used by useHref so we get proper + // hash-aware URLs in DOM paths + createHref: to => init.history.createHref(to), + encodeLocation: to => init.history.encodeLocation(to), + getFetcher, + deleteFetcher: deleteFetcherAndUpdateState, + dispose, + getBlocker, + deleteBlocker, + _internalFetchControllers: fetchControllers, + _internalActiveDeferreds: activeDeferreds, + // TODO: Remove setRoutes, it's temporary to avoid dealing with + // updating the tree while validating the update algorithm. + _internalSetRoutes + }; + return router; +} +//#endregion + +//////////////////////////////////////////////////////////////////////////////// +//#region createStaticHandler +//////////////////////////////////////////////////////////////////////////////// + +const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred"); + +/** + * Future flags to toggle new feature behavior + */ + +function createStaticHandler(routes, opts) { + invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler"); + let manifest = {}; + let basename = (opts ? opts.basename : null) || "/"; + let mapRouteProperties; + if (opts != null && opts.mapRouteProperties) { + mapRouteProperties = opts.mapRouteProperties; + } else if (opts != null && opts.detectErrorBoundary) { + // If they are still using the deprecated version, wrap it with the new API + let detectErrorBoundary = opts.detectErrorBoundary; + mapRouteProperties = route => ({ + hasErrorBoundary: detectErrorBoundary(route) + }); + } else { + mapRouteProperties = defaultMapRouteProperties; + } + // Config driven behavior flags + let future = _extends({ + v7_relativeSplatPath: false + }, opts ? opts.future : null); + let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest); + + /** + * The query() method is intended for document requests, in which we want to + * call an optional action and potentially multiple loaders for all nested + * routes. It returns a StaticHandlerContext object, which is very similar + * to the router state (location, loaderData, actionData, errors, etc.) and + * also adds SSR-specific information such as the statusCode and headers + * from action/loaders Responses. + * + * It _should_ never throw and should report all errors through the + * returned context.errors object, properly associating errors to their error + * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be + * used to emulate React error boundaries during SSr by performing a second + * pass only down to the boundaryId. + * + * The one exception where we do not return a StaticHandlerContext is when a + * redirect response is returned or thrown from any action/loader. We + * propagate that out and return the raw Response so the HTTP server can + * return it directly. + */ + async function query(request, _temp3) { + let { + requestContext + } = _temp3 === void 0 ? {} : _temp3; + let url = new URL(request.url); + let method = request.method; + let location = createLocation("", createPath(url), null, "default"); + let matches = matchRoutes(dataRoutes, location, basename); + + // SSR supports HEAD requests while SPA doesn't + if (!isValidMethod(method) && method !== "HEAD") { + let error = getInternalRouterError(405, { + method + }); + let { + matches: methodNotAllowedMatches, + route + } = getShortCircuitMatches(dataRoutes); + return { + basename, + location, + matches: methodNotAllowedMatches, + loaderData: {}, + actionData: null, + errors: { + [route.id]: error + }, + statusCode: error.status, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } else if (!matches) { + let error = getInternalRouterError(404, { + pathname: location.pathname + }); + let { + matches: notFoundMatches, + route + } = getShortCircuitMatches(dataRoutes); + return { + basename, + location, + matches: notFoundMatches, + loaderData: {}, + actionData: null, + errors: { + [route.id]: error + }, + statusCode: error.status, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } + let result = await queryImpl(request, location, matches, requestContext); + if (isResponse(result)) { + return result; + } + + // When returning StaticHandlerContext, we patch back in the location here + // since we need it for React Context. But this helps keep our submit and + // loadRouteData operating on a Request instead of a Location + return _extends({ + location, + basename + }, result); + } + + /** + * The queryRoute() method is intended for targeted route requests, either + * for fetch ?_data requests or resource route requests. In this case, we + * are only ever calling a single action or loader, and we are returning the + * returned value directly. In most cases, this will be a Response returned + * from the action/loader, but it may be a primitive or other value as well - + * and in such cases the calling context should handle that accordingly. + * + * We do respect the throw/return differentiation, so if an action/loader + * throws, then this method will throw the value. This is important so we + * can do proper boundary identification in Remix where a thrown Response + * must go to the Catch Boundary but a returned Response is happy-path. + * + * One thing to note is that any Router-initiated Errors that make sense + * to associate with a status code will be thrown as an ErrorResponse + * instance which include the raw Error, such that the calling context can + * serialize the error as they see fit while including the proper response + * code. Examples here are 404 and 405 errors that occur prior to reaching + * any user-defined loaders. + */ + async function queryRoute(request, _temp4) { + let { + routeId, + requestContext + } = _temp4 === void 0 ? {} : _temp4; + let url = new URL(request.url); + let method = request.method; + let location = createLocation("", createPath(url), null, "default"); + let matches = matchRoutes(dataRoutes, location, basename); + + // SSR supports HEAD requests while SPA doesn't + if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") { + throw getInternalRouterError(405, { + method + }); + } else if (!matches) { + throw getInternalRouterError(404, { + pathname: location.pathname + }); + } + let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location); + if (routeId && !match) { + throw getInternalRouterError(403, { + pathname: location.pathname, + routeId + }); + } else if (!match) { + // This should never hit I don't think? + throw getInternalRouterError(404, { + pathname: location.pathname + }); + } + let result = await queryImpl(request, location, matches, requestContext, match); + if (isResponse(result)) { + return result; + } + let error = result.errors ? Object.values(result.errors)[0] : undefined; + if (error !== undefined) { + // If we got back result.errors, that means the loader/action threw + // _something_ that wasn't a Response, but it's not guaranteed/required + // to be an `instanceof Error` either, so we have to use throw here to + // preserve the "error" state outside of queryImpl. + throw error; + } + + // Pick off the right state value to return + if (result.actionData) { + return Object.values(result.actionData)[0]; + } + if (result.loaderData) { + var _result$activeDeferre; + let data = Object.values(result.loaderData)[0]; + if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) { + data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id]; + } + return data; + } + return undefined; + } + async function queryImpl(request, location, matches, requestContext, routeMatch) { + invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal"); + try { + if (isMutationMethod(request.method.toLowerCase())) { + let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, routeMatch != null); + return result; + } + let result = await loadRouteData(request, matches, requestContext, routeMatch); + return isResponse(result) ? result : _extends({}, result, { + actionData: null, + actionHeaders: {} + }); + } catch (e) { + // If the user threw/returned a Response in callLoaderOrAction, we throw + // it to bail out and then return or throw here based on whether the user + // returned or threw + if (isQueryRouteResponse(e)) { + if (e.type === ResultType.error) { + throw e.response; + } + return e.response; + } + // Redirects are always returned since they don't propagate to catch + // boundaries + if (isRedirectResponse(e)) { + return e; + } + throw e; + } + } + async function submit(request, matches, actionMatch, requestContext, isRouteRequest) { + let result; + if (!actionMatch.route.action && !actionMatch.route.lazy) { + let error = getInternalRouterError(405, { + method: request.method, + pathname: new URL(request.url).pathname, + routeId: actionMatch.route.id + }); + if (isRouteRequest) { + throw error; + } + result = { + type: ResultType.error, + error + }; + } else { + result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath, { + isStaticRequest: true, + isRouteRequest, + requestContext + }); + if (request.signal.aborted) { + let method = isRouteRequest ? "queryRoute" : "query"; + throw new Error(method + "() call aborted: " + request.method + " " + request.url); + } + } + if (isRedirectResult(result)) { + // Uhhhh - this should never happen, we should always throw these from + // callLoaderOrAction, but the type narrowing here keeps TS happy and we + // can get back on the "throw all redirect responses" train here should + // this ever happen :/ + throw new Response(null, { + status: result.status, + headers: { + Location: result.location + } + }); + } + if (isDeferredResult(result)) { + let error = getInternalRouterError(400, { + type: "defer-action" + }); + if (isRouteRequest) { + throw error; + } + result = { + type: ResultType.error, + error + }; + } + if (isRouteRequest) { + // Note: This should only be non-Response values if we get here, since + // isRouteRequest should throw any Response received in callLoaderOrAction + if (isErrorResult(result)) { + throw result.error; + } + return { + matches: [actionMatch], + loaderData: {}, + actionData: { + [actionMatch.route.id]: result.data + }, + errors: null, + // Note: statusCode + headers are unused here since queryRoute will + // return the raw Response or value + statusCode: 200, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } + 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, requestContext, undefined, { + [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 + } : {}) + }); + } + + // Create a GET request for the loaders + let loaderRequest = new Request(request.url, { + headers: request.headers, + redirect: request.redirect, + signal: request.signal + }); + let context = await loadRouteData(loaderRequest, matches, requestContext); + return _extends({}, context, result.statusCode ? { + statusCode: result.statusCode + } : {}, { + actionData: { + [actionMatch.route.id]: result.data + }, + actionHeaders: _extends({}, result.headers ? { + [actionMatch.route.id]: result.headers + } : {}) + }); + } + async function loadRouteData(request, matches, requestContext, routeMatch, pendingActionError) { + let isRouteRequest = routeMatch != null; + + // Short circuit if we have no loaders to run (queryRoute()) + if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) { + throw getInternalRouterError(400, { + method: request.method, + pathname: new URL(request.url).pathname, + routeId: routeMatch == null ? void 0 : routeMatch.route.id + }); + } + let requestMatches = routeMatch ? [routeMatch] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]); + let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy); + + // Short circuit if we have no loaders to run (query()) + if (matchesToLoad.length === 0) { + return { + matches, + // Add a null for all matched routes for proper revalidation on the client + loaderData: matches.reduce((acc, m) => Object.assign(acc, { + [m.route.id]: null + }), {}), + errors: pendingActionError || null, + statusCode: 200, + loaderHeaders: {}, + activeDeferreds: null + }; + } + let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath, { + isStaticRequest: true, + isRouteRequest, + requestContext + }))]); + if (request.signal.aborted) { + let method = isRouteRequest ? "queryRoute" : "query"; + throw new Error(method + "() call aborted: " + request.method + " " + request.url); + } + + // Process and commit output from loaders + let activeDeferreds = new Map(); + let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError, activeDeferreds); + + // Add a null for any non-loader matches for proper revalidation on the client + let executedLoaders = new Set(matchesToLoad.map(match => match.route.id)); + matches.forEach(match => { + if (!executedLoaders.has(match.route.id)) { + context.loaderData[match.route.id] = null; + } + }); + return _extends({}, context, { + matches, + activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null + }); + } + 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; +} +function isSubmissionNavigation(opts) { + return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== undefined); +} +function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) { + let contextualMatches; + let activeRouteMatch; + if (fromRouteId) { + // Grab matches up to the calling route so our route-relative logic is + // relative to the correct source route + contextualMatches = []; + for (let match of matches) { + contextualMatches.push(match); + if (match.route.id === fromRouteId) { + activeRouteMatch = match; + break; + } + } + } else { + contextualMatches = matches; + activeRouteMatch = matches[matches.length - 1]; + } + + // Resolve the relative path + let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path"); + + // When `to` is not specified we inherit search/hash from the current + // location, unlike when to="." and we just inherit the path. + // See https://github.com/remix-run/remix/issues/927 + if (to == null) { + path.search = location.search; + path.hash = location.hash; + } + + // Add an ?index param for matched index routes if we don't already have one + if ((to == null || to === "" || to === ".") && activeRouteMatch && activeRouteMatch.route.index && !hasNakedIndexQuery(path.search)) { + path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index"; + } + + // If we're operating within a basename, prepend it to the pathname. If + // this is a root navigation, then just use the raw basename which allows + // the basename to have full control over the presence of a trailing slash + // on root actions + if (prependBasename && basename !== "/") { + path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]); + } + return createPath(path); +} + +// Normalize navigation options by converting formMethod=GET formData objects to +// URLSearchParams so they behave identically to links with query params +function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) { + // Return location verbatim on non-submission navigations + if (!opts || !isSubmissionNavigation(opts)) { + return { + path + }; + } + if (opts.formMethod && !isValidMethod(opts.formMethod)) { + return { + path, + error: getInternalRouterError(405, { + method: opts.formMethod + }) + }; + } + let getInvalidBodyError = () => ({ + path, + error: getInternalRouterError(400, { + type: "invalid-body" + }) + }); + + // Create a Submission on non-GET navigations + let rawFormMethod = opts.formMethod || "get"; + let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase(); + let formAction = stripHashFromPath(path); + if (opts.body !== undefined) { + if (opts.formEncType === "text/plain") { + // text only support POST/PUT/PATCH/DELETE submissions + if (!isMutationMethod(formMethod)) { + return getInvalidBodyError(); + } + let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? + // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data + Array.from(opts.body.entries()).reduce((acc, _ref3) => { + let [name, value] = _ref3; + return "" + acc + name + "=" + value + "\n"; + }, "") : String(opts.body); + return { + path, + submission: { + formMethod, + formAction, + formEncType: opts.formEncType, + formData: undefined, + json: undefined, + text + } + }; + } else if (opts.formEncType === "application/json") { + // json only supports POST/PUT/PATCH/DELETE submissions + if (!isMutationMethod(formMethod)) { + return getInvalidBodyError(); + } + try { + let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body; + return { + path, + submission: { + formMethod, + formAction, + formEncType: opts.formEncType, + formData: undefined, + json, + text: undefined + } + }; + } catch (e) { + return getInvalidBodyError(); + } + } + } + invariant(typeof FormData === "function", "FormData is not available in this environment"); + let searchParams; + let formData; + if (opts.formData) { + searchParams = convertFormDataToSearchParams(opts.formData); + formData = opts.formData; + } else if (opts.body instanceof FormData) { + searchParams = convertFormDataToSearchParams(opts.body); + formData = opts.body; + } else if (opts.body instanceof URLSearchParams) { + searchParams = opts.body; + formData = convertSearchParamsToFormData(searchParams); + } else if (opts.body == null) { + searchParams = new URLSearchParams(); + formData = new FormData(); + } else { + try { + searchParams = new URLSearchParams(opts.body); + formData = convertSearchParamsToFormData(searchParams); + } catch (e) { + return getInvalidBodyError(); + } + } + let submission = { + formMethod, + formAction, + formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded", + formData, + json: undefined, + text: undefined + }; + if (isMutationMethod(submission.formMethod)) { + return { + path, + submission + }; + } + + // Flatten submission onto URLSearchParams for GET submissions + let parsedPath = parsePath(path); + // On GET navigation submissions we can drop the ?index param from the + // resulting location since all loaders will run. But fetcher GET submissions + // only run a single loader so we need to preserve any incoming ?index params + if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) { + searchParams.append("index", ""); + } + parsedPath.search = "?" + searchParams; + return { + path: createPath(parsedPath), + submission + }; +} + +// Filter out all routes 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(history, state, matches, submission, location, isInitialLoad, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError) { + let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : undefined; + let currentUrl = history.createURL(state.location); + let nextUrl = history.createURL(location); + + // 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) => { + let { + route + } = match; + if (route.lazy) { + // We haven't loaded this route yet so we don't know if it's got a loader! + return true; + } + if (route.loader == null) { + return false; + } + if (isInitialLoad) { + if (route.loader.hydrate) { + return true; + } + return state.loaderData[route.id] === undefined && ( + // Don't re-run if the loader ran and threw an error + !state.errors || state.errors[route.id] === undefined); + } + + // Always call the loader on new route instances and pending defer cancellations + if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) { + return true; + } + + // This is the default implementation for when we revalidate. If the route + // provides it's own implementation, then we give them full control but + // provide this value so they can leverage it if needed after they check + // their own specific use cases + let currentRouteMatch = state.matches[index]; + let nextRouteMatch = match; + return shouldRevalidateLoader(match, _extends({ + currentUrl, + currentParams: currentRouteMatch.params, + nextUrl, + nextParams: nextRouteMatch.params + }, submission, { + actionResult, + defaultShouldRevalidate: + // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate + isRevalidationRequired || + // Clicked the same link, resubmitted a GET form + currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || + // Search params affect all loaders + currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch) + })); + }); + + // Pick fetcher.loads that need to be revalidated + let revalidatingFetchers = []; + fetchLoadMatches.forEach((f, key) => { + // Don't revalidate: + // - on initial load (shouldn't be any fetchers then anyway) + // - if fetcher won't be present in the subsequent render + // - no longer matches the URL (v7_fetcherPersist=false) + // - was unmounted but persisted due to v7_fetcherPersist=true + if (isInitialLoad || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) { + return; + } + let fetcherMatches = matchRoutes(routesToUse, f.path, basename); + + // If the fetcher path no longer matches, push it in with null matches so + // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is + // currently only a use-case for Remix HMR where the route tree can change + // at runtime and remove a route previously loaded via a fetcher + if (!fetcherMatches) { + revalidatingFetchers.push({ + key, + routeId: f.routeId, + path: f.path, + matches: null, + match: null, + controller: null + }); + return; + } + + // Revalidating fetchers are decoupled from the route matches since they + // load from a static href. They revalidate based on explicit revalidation + // (submission, useRevalidator, or X-Remix-Revalidate) + let fetcher = state.fetchers.get(key); + let fetcherMatch = getTargetMatch(fetcherMatches, f.path); + let shouldRevalidate = false; + if (fetchRedirectIds.has(key)) { + // Never trigger a revalidation of an actively redirecting fetcher + shouldRevalidate = false; + } else if (cancelledFetcherLoads.includes(key)) { + // Always revalidate if the fetcher was cancelled + shouldRevalidate = true; + } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) { + // If the fetcher hasn't ever completed loading yet, then this isn't a + // revalidation, it would just be a brand new load if an explicit + // revalidation is required + shouldRevalidate = isRevalidationRequired; + } else { + // Otherwise fall back on any user-defined shouldRevalidate, defaulting + // to explicit revalidations only + shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({ + currentUrl, + currentParams: state.matches[state.matches.length - 1].params, + nextUrl, + nextParams: matches[matches.length - 1].params + }, submission, { + actionResult, + defaultShouldRevalidate: isRevalidationRequired + })); + } + if (shouldRevalidate) { + revalidatingFetchers.push({ + key, + routeId: f.routeId, + path: f.path, + matches: fetcherMatches, + match: fetcherMatch, + controller: new AbortController() + }); + } + }); + return [navigationMatches, revalidatingFetchers]; +} +function isNewLoader(currentLoaderData, currentMatch, match) { + let isNew = + // [a] -> [a, b] + !currentMatch || + // [a, b] -> [a, c] + match.route.id !== currentMatch.route.id; + + // Handle the case that we don't have data for a re-used route, potentially + // from a prior error or from a cancelled pending deferred + let isMissingData = currentLoaderData[match.route.id] === undefined; + + // Always load if this is a net-new route or we don't yet have data + return isNew || isMissingData; +} +function isNewRouteInstance(currentMatch, match) { + let currentPath = currentMatch.route.path; + return ( + // param change for this match, /users/123 -> /users/456 + currentMatch.pathname !== match.pathname || + // splat param changed, which is not present in match.path + // e.g. /files/images/avatar.jpg -> files/finances.xls + currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"] + ); +} +function shouldRevalidateLoader(loaderMatch, arg) { + if (loaderMatch.route.shouldRevalidate) { + let routeChoice = loaderMatch.route.shouldRevalidate(arg); + if (typeof routeChoice === "boolean") { + return routeChoice; + } + } + return arg.defaultShouldRevalidate; +} + +/** + * Execute route.lazy() methods to lazily load route modules (loader, action, + * shouldRevalidate) and update the routeManifest in place which shares objects + * with dataRoutes so those get updated as well. + */ +async function loadLazyRouteModule(route, mapRouteProperties, manifest) { + if (!route.lazy) { + return; + } + let lazyRoute = await route.lazy(); + + // If the lazy route function was executed and removed by another parallel + // call then we can return - first lazy() to finish wins because the return + // value of lazy is expected to be static + if (!route.lazy) { + return; + } + let routeToUpdate = manifest[route.id]; + invariant(routeToUpdate, "No route found in manifest"); + + // Update the route in place. This should be safe because there's no way + // we could yet be sitting on this route as we can't get there without + // resolving lazy() first. + // + // This is different than the HMR "update" use-case where we may actively be + // on the route being updated. The main concern boils down to "does this + // mutation affect any ongoing navigations or any current state.matches + // values?". If not, it should be safe to update in place. + let routeUpdates = {}; + for (let lazyRouteProperty in lazyRoute) { + let staticRouteValue = routeToUpdate[lazyRouteProperty]; + let isPropertyStaticallyDefined = staticRouteValue !== undefined && + // This property isn't static since it should always be updated based + // on the route updates + lazyRouteProperty !== "hasErrorBoundary"; + warning(!isPropertyStaticallyDefined, "Route \"" + routeToUpdate.id + "\" has a static property \"" + lazyRouteProperty + "\" " + "defined but its lazy function is also returning a value for this property. " + ("The lazy route property \"" + lazyRouteProperty + "\" will be ignored.")); + if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) { + routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty]; + } + } + + // Mutate the route with the provided updates. Do this first so we pass + // the updated version to mapRouteProperties + Object.assign(routeToUpdate, routeUpdates); + + // Mutate the `hasErrorBoundary` property on the route based on the route + // updates and remove the `lazy` function so we don't resolve the lazy + // route again. + Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), { + lazy: undefined + })); +} +async function callLoaderOrAction(type, request, match, matches, manifest, mapRouteProperties, basename, v7_relativeSplatPath, opts) { + if (opts === void 0) { + opts = {}; + } + let resultType; + let result; + let onReject; + let runHandler = handler => { + // Setup a promise we can race against so that abort signals short circuit + let reject; + let abortPromise = new Promise((_, r) => reject = r); + onReject = () => reject(); + request.signal.addEventListener("abort", onReject); + return Promise.race([handler({ + request, + params: match.params, + context: opts.requestContext + }), abortPromise]); + }; + try { + let handler = match.route[type]; + if (match.route.lazy) { + if (handler) { + // Run statically defined handler in parallel with lazy() + let handlerError; + let values = await Promise.all([ + // If the handler throws, don't let it immediately bubble out, + // since we need to let the lazy() execution finish so we know if this + // route has a boundary that can handle the error + runHandler(handler).catch(e => { + handlerError = e; + }), loadLazyRouteModule(match.route, mapRouteProperties, manifest)]); + if (handlerError) { + throw handlerError; + } + result = values[0]; + } else { + // Load lazy route module, then run any returned handler + await loadLazyRouteModule(match.route, mapRouteProperties, manifest); + handler = match.route[type]; + if (handler) { + // Handler still run even if we got interrupted to maintain consistency + // with un-abortable behavior of handler execution on non-lazy or + // previously-lazy-loaded routes + result = await runHandler(handler); + } else if (type === "action") { + let url = new URL(request.url); + let pathname = url.pathname + url.search; + throw getInternalRouterError(405, { + method: request.method, + pathname, + routeId: match.route.id + }); + } else { + // lazy() route has no loader to run. Short circuit here so we don't + // hit the invariant below that errors on returning undefined. + return { + type: ResultType.data, + data: undefined + }; + } + } + } else if (!handler) { + let url = new URL(request.url); + let pathname = url.pathname + url.search; + throw getInternalRouterError(404, { + pathname + }); + } else { + result = await runHandler(handler); + } + invariant(result !== undefined, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ("\"" + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`."); + } catch (e) { + resultType = ResultType.error; + result = e; + } finally { + if (onReject) { + request.signal.removeEventListener("abort", onReject); + } + } + if (isResponse(result)) { + let status = result.status; + + // Process redirects + if (redirectStatusCodes.has(status)) { + let location = result.headers.get("Location"); + invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header"); + + // Support relative routing in internal redirects + if (!ABSOLUTE_URL_REGEX.test(location)) { + location = normalizeTo(new URL(request.url), matches.slice(0, matches.indexOf(match) + 1), basename, true, location, v7_relativeSplatPath); + } else if (!opts.isStaticRequest) { + // Strip off the protocol+origin for same-origin + same-basename absolute + // redirects. If this is a static request, we can let it go back to the + // browser as-is + let currentUrl = new URL(request.url); + let url = location.startsWith("//") ? new URL(currentUrl.protocol + location) : new URL(location); + let isSameBasename = stripBasename(url.pathname, basename) != null; + if (url.origin === currentUrl.origin && isSameBasename) { + location = url.pathname + url.search + url.hash; + } + } + + // Don't process redirects in the router during static requests requests. + // Instead, throw the Response and let the server handle it with an HTTP + // redirect. We also update the Location header in place in this flow so + // basename and relative routing is taken into account + if (opts.isStaticRequest) { + result.headers.set("Location", location); + throw result; + } + return { + type: ResultType.redirect, + status, + location, + revalidate: result.headers.get("X-Remix-Revalidate") !== null, + reloadDocument: result.headers.get("X-Remix-Reload-Document") !== null + }; + } + + // For SSR single-route requests, we want to hand Responses back directly + // without unwrapping. We do this with the QueryRouteResponse wrapper + // interface so we can know whether it was returned or thrown + if (opts.isRouteRequest) { + let queryRouteResponse = { + type: resultType === ResultType.error ? ResultType.error : ResultType.data, + response: result + }; + throw queryRouteResponse; + } + let data; + try { + let contentType = result.headers.get("Content-Type"); + // Check between word boundaries instead of startsWith() due to the last + // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type + if (contentType && /\bapplication\/json\b/.test(contentType)) { + if (result.body == null) { + data = null; + } else { + data = await result.json(); + } + } else { + data = await result.text(); + } + } catch (e) { + return { + type: ResultType.error, + error: e + }; + } + if (resultType === ResultType.error) { + return { + type: resultType, + error: new ErrorResponseImpl(status, result.statusText, data), + headers: result.headers + }; + } + return { + type: ResultType.data, + data, + statusCode: result.status, + headers: result.headers + }; + } + if (resultType === ResultType.error) { + return { + type: resultType, + error: result + }; + } + if (isDeferredData(result)) { + var _result$init, _result$init2; + return { + type: ResultType.deferred, + deferredData: result, + statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status, + headers: ((_result$init2 = result.init) == null ? void 0 : _result$init2.headers) && new Headers(result.init.headers) + }; + } + return { + type: ResultType.data, + data: result + }; +} + +// Utility method for creating the Request instances for loaders/actions during +// client-side navigations and fetches. During SSR we will always have a +// Request instance from the static handler (query/queryRoute) +function createClientSideRequest(history, location, signal, submission) { + let url = history.createURL(stripHashFromPath(location)).toString(); + let init = { + signal + }; + if (submission && isMutationMethod(submission.formMethod)) { + let { + formMethod, + formEncType + } = submission; + // Didn't think we needed this but it turns out unlike other methods, patch + // won't be properly normalized to uppercase and results in a 405 error. + // See: https://fetch.spec.whatwg.org/#concept-method + init.method = formMethod.toUpperCase(); + if (formEncType === "application/json") { + init.headers = new Headers({ + "Content-Type": formEncType + }); + init.body = JSON.stringify(submission.json); + } else if (formEncType === "text/plain") { + // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) + init.body = submission.text; + } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) { + // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) + init.body = convertFormDataToSearchParams(submission.formData); + } else { + // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) + init.body = submission.formData; + } + } + return new Request(url, init); +} +function convertFormDataToSearchParams(formData) { + let searchParams = new URLSearchParams(); + for (let [key, value] of formData.entries()) { + // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs + searchParams.append(key, typeof value === "string" ? value : value.name); + } + return searchParams; +} +function convertSearchParamsToFormData(searchParams) { + let formData = new FormData(); + for (let [key, value] of searchParams.entries()) { + formData.append(key, value); + } + return formData; +} +function processRouteLoaderData(matches, 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 = errors || {}; + + // Prefer higher error values if lower errors bubble to the same boundary + if (errors[boundaryMatch.route.id] == null) { + errors[boundaryMatch.route.id] = error; + } + + // Clear our any prior loaderData for the throwing route + loaderData[id] = undefined; + + // Once we find our first (highest) error, we set the status code and + // prevent deeper status codes from overriding + if (!foundError) { + foundError = true; + statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500; + } + if (result.headers) { + loaderHeaders[id] = result.headers; + } + } else { + if (isDeferredResult(result)) { + activeDeferreds.set(id, result.deferredData); + loaderData[id] = result.deferredData.data; + } 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. Also clear out any loaderData for the + // throwing route + if (pendingError) { + errors = pendingError; + loaderData[Object.keys(pendingError)[0]] = undefined; + } + 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, + controller + } = revalidatingFetchers[index]; + invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result"); + let result = fetcherResults[index]; + + // Process fetcher non-redirect errors + if (controller && controller.signal.aborted) { + // Nothing to do for aborted fetchers + continue; + } else if (isErrorResult(result)) { + let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id); + if (!(errors && errors[boundaryMatch.route.id])) { + errors = _extends({}, errors, { + [boundaryMatch.route.id]: result.error + }); + } + state.fetchers.delete(key); + } else if (isRedirectResult(result)) { + // Should never get here, redirects should get processed above, but we + // keep this to type narrow to a success result in the else + invariant(false, "Unhandled fetcher revalidation redirect"); + } else if (isDeferredResult(result)) { + // Should never get here, deferred data should be awaited for fetchers + // in resolveDeferredResults + invariant(false, "Unhandled fetcher deferred data"); + } else { + let doneFetcher = getDoneFetcher(result.data); + state.fetchers.set(key, doneFetcher); + } + } + return { + loaderData, + errors + }; +} +function mergeLoaderData(loaderData, newLoaderData, matches, errors) { + let mergedLoaderData = _extends({}, newLoaderData); + for (let match of matches) { + let id = match.route.id; + if (newLoaderData.hasOwnProperty(id)) { + if (newLoaderData[id] !== undefined) { + mergedLoaderData[id] = newLoaderData[id]; + } + } else if (loaderData[id] !== undefined && match.route.loader) { + // Preserve existing keys not included in newLoaderData and where a loader + // wasn't removed by HMR + mergedLoaderData[id] = loaderData[id]; + } + if (errors && errors.hasOwnProperty(id)) { + // Don't keep any loader data below the boundary + break; + } + } + return mergedLoaderData; +} + +// Find the nearest error boundary, looking upwards from the leaf route (or the +// route specified by routeId) for the closest ancestor error boundary, +// defaulting to the root match +function findNearestBoundary(matches, routeId) { + let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches]; + return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0]; +} +function getShortCircuitMatches(routes) { + // Prefer a root layout route if present, otherwise shim in a route object + let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || { + id: "__shim-error-route__" + }; + return { + matches: [{ + params: {}, + pathname: "", + pathnameBase: "", + route + }], + route + }; +} +function getInternalRouterError(status, _temp5) { + let { + pathname, + routeId, + method, + type + } = _temp5 === void 0 ? {} : _temp5; + let statusText = "Unknown Server Error"; + let errorMessage = "Unknown @remix-run/router error"; + if (status === 400) { + statusText = "Bad Request"; + if (method && pathname && routeId) { + errorMessage = "You made a " + method + " request to \"" + pathname + "\" but " + ("did not provide a `loader` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; + } else if (type === "defer-action") { + errorMessage = "defer() is not supported in actions"; + } else if (type === "invalid-body") { + errorMessage = "Unable to encode submission body"; + } + } else if (status === 403) { + statusText = "Forbidden"; + errorMessage = "Route \"" + routeId + "\" does not match URL \"" + pathname + "\""; + } else if (status === 404) { + statusText = "Not Found"; + errorMessage = "No route matches URL \"" + pathname + "\""; + } else if (status === 405) { + statusText = "Method Not Allowed"; + if (method && pathname && routeId) { + errorMessage = "You made a " + method.toUpperCase() + " request to \"" + pathname + "\" but " + ("did not provide an `action` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; + } else if (method) { + errorMessage = "Invalid request method \"" + method.toUpperCase() + "\""; + } + } + return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true); +} + +// Find any returned redirect errors, starting from the lowest match +function findRedirect(results) { + for (let i = results.length - 1; i >= 0; i--) { + let result = results[i]; + if (isRedirectResult(result)) { + return { + result, + idx: i + }; + } + } +} +function stripHashFromPath(path) { + let parsedPath = typeof path === "string" ? parsePath(path) : path; + return createPath(_extends({}, parsedPath, { + hash: "" + })); +} +function isHashChangeOnly(a, b) { + if (a.pathname !== b.pathname || a.search !== b.search) { + return false; + } + if (a.hash === "") { + // /page -> /page#hash + return b.hash !== ""; + } else if (a.hash === b.hash) { + // /page#hash -> /page#hash + return true; + } else if (b.hash !== "") { + // /page#hash -> /page#other + return true; + } + + // If the hash is removed the browser will re-perform a request to the server + // /page#hash -> /page + return false; +} +function isDeferredResult(result) { + return result.type === ResultType.deferred; +} +function isErrorResult(result) { + return result.type === ResultType.error; +} +function isRedirectResult(result) { + return (result && result.type) === ResultType.redirect; +} +function isDeferredData(value) { + let deferred = value; + return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function"; +} +function isResponse(value) { + return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined"; +} +function isRedirectResponse(result) { + if (!isResponse(result)) { + return false; + } + let status = result.status; + let location = result.headers.get("Location"); + return status >= 300 && status <= 399 && location != null; +} +function isQueryRouteResponse(obj) { + return obj && isResponse(obj.response) && (obj.type === ResultType.data || obj.type === ResultType.error); +} +function isValidMethod(method) { + return validRequestMethods.has(method.toLowerCase()); +} +function isMutationMethod(method) { + return validMutationMethods.has(method.toLowerCase()); +} +async function resolveDeferredResults(currentMatches, matchesToLoad, results, signals, isFetcher, currentLoaderData) { + for (let index = 0; index < results.length; index++) { + let result = results[index]; + let match = matchesToLoad[index]; + // If we don't have a match, then we can have a deferred result to do + // anything with. This is for revalidating fetchers where the route was + // removed during HMR + if (!match) { + continue; + } + let currentMatch = currentMatches.find(m => m.route.id === match.route.id); + let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined; + if (isDeferredResult(result) && (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 + let signal = signals[index]; + invariant(signal, "Expected an AbortSignal for revalidating fetcher deferred result"); + 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 === ""); +} +function getTargetMatch(matches, location) { + let search = typeof location === "string" ? parsePath(location).search : location.search; + if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) { + // Return the leaf index route when index is present + return matches[matches.length - 1]; + } + // Otherwise grab the deepest "path contributing" match (ignoring index and + // pathless layout routes) + let pathMatches = getPathContributingMatches(matches); + return pathMatches[pathMatches.length - 1]; +} +function getSubmissionFromNavigation(navigation) { + let { + formMethod, + formAction, + formEncType, + text, + formData, + json + } = navigation; + if (!formMethod || !formAction || !formEncType) { + return; + } + if (text != null) { + return { + formMethod, + formAction, + formEncType, + formData: undefined, + json: undefined, + text + }; + } else if (formData != null) { + return { + formMethod, + formAction, + formEncType, + formData, + json: undefined, + text: undefined + }; + } else if (json !== undefined) { + return { + formMethod, + formAction, + formEncType, + formData: undefined, + json, + text: undefined + }; + } +} +function getLoadingNavigation(location, submission) { + if (submission) { + let navigation = { + state: "loading", + location, + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text + }; + return navigation; + } else { + let navigation = { + state: "loading", + location, + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined + }; + return navigation; + } +} +function getSubmittingNavigation(location, submission) { + let navigation = { + state: "submitting", + location, + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text + }; + return navigation; +} +function getLoadingFetcher(submission, data) { + if (submission) { + let fetcher = { + state: "loading", + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text, + data + }; + return fetcher; + } else { + let fetcher = { + state: "loading", + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined, + data + }; + return fetcher; + } +} +function getSubmittingFetcher(submission, existingFetcher) { + let fetcher = { + state: "submitting", + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text, + data: existingFetcher ? existingFetcher.data : undefined + }; + return fetcher; +} +function getDoneFetcher(data) { + let fetcher = { + state: "idle", + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined, + data + }; + return fetcher; +} +function restoreAppliedTransitions(_window, transitions) { + try { + let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY); + if (sessionPositions) { + let json = JSON.parse(sessionPositions); + for (let [k, v] of Object.entries(json || {})) { + if (v && Array.isArray(v)) { + transitions.set(k, new Set(v || [])); + } + } + } + } catch (e) { + // no-op, use default empty object + } +} +function persistAppliedTransitions(_window, transitions) { + if (transitions.size > 0) { + let json = {}; + for (let [k, v] of transitions) { + json[k] = [...v]; + } + try { + _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json)); + } catch (error) { + warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ")."); + } + } +} + +//#endregion + +exports.AbortedDeferredError = AbortedDeferredError; +exports.Action = Action; +exports.IDLE_BLOCKER = IDLE_BLOCKER; +exports.IDLE_FETCHER = IDLE_FETCHER; +exports.IDLE_NAVIGATION = IDLE_NAVIGATION; +exports.UNSAFE_DEFERRED_SYMBOL = UNSAFE_DEFERRED_SYMBOL; +exports.UNSAFE_DeferredData = DeferredData; +exports.UNSAFE_ErrorResponseImpl = ErrorResponseImpl; +exports.UNSAFE_convertRouteMatchToUiMatch = convertRouteMatchToUiMatch; +exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes; +exports.UNSAFE_getResolveToMatches = getResolveToMatches; +exports.UNSAFE_invariant = invariant; +exports.UNSAFE_warning = warning; +exports.createBrowserHistory = createBrowserHistory; +exports.createHashHistory = createHashHistory; +exports.createMemoryHistory = createMemoryHistory; +exports.createPath = createPath; +exports.createRouter = createRouter; +exports.createStaticHandler = createStaticHandler; +exports.defer = defer; +exports.generatePath = generatePath; +exports.getStaticContextFromError = getStaticContextFromError; +exports.getToPathname = getToPathname; +exports.isDeferredData = isDeferredData; +exports.isRouteErrorResponse = isRouteErrorResponse; +exports.joinPaths = joinPaths; +exports.json = json; +exports.matchPath = matchPath; +exports.matchRoutes = matchRoutes; +exports.normalizePathname = normalizePathname; +exports.parsePath = parsePath; +exports.redirect = redirect; +exports.redirectDocument = redirectDocument; +exports.resolvePath = resolvePath; +exports.resolveTo = resolveTo; +exports.stripBasename = stripBasename; +//# 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 new file mode 100644 index 0000000..b5c807c --- /dev/null +++ b/node_modules/@remix-run/router/dist/router.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"router.cjs.js","sources":["../history.ts","../utils.ts","../router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\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 * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly {\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 let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: 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 statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n status: number;\n location: string;\n revalidate: boolean;\n reloadDocument?: 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\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on ``,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable | null;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (args: LoaderFunctionArgs):\n | Promise\n | DataFunctionValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (args: ActionFunctionArgs):\n | Promise\n | DataFunctionValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction {\n (): Promise>>;\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 lazy?: LazyRouteFunction;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record;\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 `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam =\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 you 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 mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: number[] = [],\n manifest: RouteManifest = {}\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 !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/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(\n branches[i],\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n safelyDecodeURI(pathname)\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch,\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/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\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/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, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = safelyDecodeURIComponent(value || \"\", paramName);\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(\n /\\/:([\\w-]+)(\\?)?/g,\n (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n }\n );\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nfunction safelyDecodeURI(value: string) {\n try {\n return decodeURI(value);\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\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 * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/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 *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === matches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial;\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 (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\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 pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n ActionFunction,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n AgnosticRouteObject,\n DataResult,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n ImmutableRouteKey,\n LoaderFunction,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(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 * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\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 * Map of current blockers\n */\n blockers: 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 * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record;\n actionHeaders: Record;\n activeDeferreds: Record | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: { requestContext?: unknown }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: { routeId?: string; requestContext?: unknown }\n ): Promise;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n unstable_viewTransitionOpts?: ViewTransitionOpts;\n unstable_flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\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 * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\n/**\n * Wrapper object to allow us to throw any response out from callLoaderOrAction\n * for queryRouter while preserving whether or not it was thrown or returned\n * from the loader/action\n */\ninterface QueryRouteResponse {\n type: ResultType.data | ResultType.error;\n response: Response;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\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 // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let 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 error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized: boolean;\n let hasLazyRoutes = initialMatches.some((m) => m.route.lazy);\n let hasLoaders = initialMatches.some((m) => m.route.loader);\n if (hasLazyRoutes) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!hasLoaders) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n initialized = initialMatches.every(\n (m) =>\n m.route.loader &&\n m.route.loader.hydrate !== true &&\n ((loaderData && loaderData[m.route.id] !== undefined) ||\n (errors && errors[m.route.id] !== undefined))\n );\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map> = new Map<\n string,\n Set\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location, {\n initialHydration: true,\n });\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n }\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 { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n 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 | null,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.unstable_viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n { 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 initialHydration?: boolean;\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a \n // which will default to a navigation to /page\n if (\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let 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 (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\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, flushSync }\n );\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n\n // Create a GET request for the loaders\n request = new Request(request.url, { signal: request.signal });\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.fetcherSubmission,\n opts && opts.replace,\n opts && opts.initialHydration === true,\n flushSync,\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 ...(pendingActionData ? { actionData: pendingActionData } : {}),\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; flushSync?: boolean } = {}\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n replace =\n result.location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(state, result, { submission, replace });\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 // Send back an empty object we can use to clear out any prior actionData\n pendingActionData: {},\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\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 fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: 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 =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionData,\n pendingError\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\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 we have partialHydration enabled, then don't update the state for the\n // initial data load since iot's not a \"navigation\"\n if (\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration)\n ) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n let actionData = pendingActionData || state.actionData;\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData\n ? Object.keys(actionData).length === 0\n ? { actionData: null }\n : { actionData }\n : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(state, redirect.result, { 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 let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResult = await callLoaderOrAction(\n \"action\",\n fetchRequest,\n match,\n requestMatches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(state, actionResult, {\n fetcherSubmission: submission,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n false,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n { [match.route.id]: actionResult.data },\n undefined // No need to send through errors since we short circuit above\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(state, redirect.result);\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 // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(state, result);\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n state: RouterState,\n redirect: RedirectResult,\n {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n\n let redirectLocation = createLocation(state.location, redirect.location, {\n _isRedirect: true,\n });\n invariant(\n redirectLocation,\n \"Expected a location on the redirect navigation\"\n );\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.reloadDocument) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) {\n const url = init.history.createURL(redirect.location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(redirect.location);\n } else {\n routerWindow.location.assign(redirect.location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: redirect.location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: 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((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n )\n ),\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n return callLoaderOrAction(\n \"loader\",\n createClientSideRequest(init.history, f.path, f.controller.signal),\n f.match,\n f.matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n } else {\n let error: ErrorResult = {\n type: ResultType.error,\n error: getInternalRouterError(404, { pathname: f.path }),\n };\n return error;\n }\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 loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\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 updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher(key: string): Fetcher {\n if (future.v7_fetcherPersist) {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({ fetchers: new Map(state.fetchers) });\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 = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function 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 || null;\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 getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n ...(opts ? opts.future : null),\n };\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n */\n async function query(\n request: Request,\n { requestContext }: { requestContext?: unknown } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(request, location, matches, requestContext);\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n }: { requestContext?: unknown; routeId?: string } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n match\n );\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction, we throw\n // it to bail out and then return or throw here based on whether the user\n // returned or threw\n if (isQueryRouteResponse(e)) {\n if (e.type === ResultType.error) {\n throw e.response;\n }\n return e.response;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath,\n { isStaticRequest: true, isRouteRequest, requestContext }\n );\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.status,\n headers: {\n Location: result.location,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n 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(\n request,\n matches,\n requestContext,\n undefined,\n {\n [boundaryMatch.route.id]: result.error,\n }\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 // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n let context = await loadRouteData(loaderRequest, matches, requestContext);\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 requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch,\n pendingActionError?: RouteData\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n );\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath,\n { isStaticRequest: true, isRouteRequest, requestContext }\n )\n ),\n ]);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError,\n activeDeferreds\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n 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\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes 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 history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isInitialLoad: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : undefined;\n\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let { route } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n\n if (route.loader == null) {\n return false;\n }\n\n if (isInitialLoad) {\n if (route.loader.hydrate) {\n return true;\n }\n return (\n state.loaderData[route.id] === undefined &&\n // Don't re-run if the loader ran and threw an error\n (!state.errors || state.errors[route.id] === undefined)\n );\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n defaultShouldRevalidate:\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial load (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (\n isInitialLoad ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.includes(key)) {\n // Always revalidate if the fetcher was cancelled\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n defaultShouldRevalidate: isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n basename: string,\n v7_relativeSplatPath: boolean,\n opts: {\n isStaticRequest?: boolean;\n isRouteRequest?: boolean;\n requestContext?: unknown;\n } = {}\n): Promise {\n let resultType;\n let result;\n let onReject: (() => void) | undefined;\n\n let runHandler = (handler: ActionFunction | LoaderFunction) => {\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 onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n return Promise.race([\n handler({\n request,\n params: match.params,\n context: opts.requestContext,\n }),\n abortPromise,\n ]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let values = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadLazyRouteModule(match.route, mapRouteProperties, manifest),\n ]);\n if (handlerError) {\n throw handlerError;\n }\n result = values[0];\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n\n handler = match.route[type];\n if (handler) {\n // Handler still run even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, data: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n if (isResponse(result)) {\n let status = result.status;\n\n // Process redirects\n if (redirectStatusCodes.has(status)) {\n let location = result.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n // Support relative routing in internal redirects\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n location = normalizeTo(\n new URL(request.url),\n matches.slice(0, matches.indexOf(match) + 1),\n basename,\n true,\n location,\n v7_relativeSplatPath\n );\n } else if (!opts.isStaticRequest) {\n // Strip off the protocol+origin for same-origin + same-basename absolute\n // redirects. If this is a static request, we can let it go back to the\n // browser as-is\n let currentUrl = new URL(request.url);\n let url = location.startsWith(\"//\")\n ? new URL(currentUrl.protocol + location)\n : new URL(location);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n location = url.pathname + url.search + url.hash;\n }\n }\n\n // Don't process redirects in the router during static requests requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect. We also update the Location header in place in this flow so\n // basename and relative routing is taken into account\n if (opts.isStaticRequest) {\n result.headers.set(\"Location\", location);\n throw result;\n }\n\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n reloadDocument: result.headers.get(\"X-Remix-Reload-Document\") !== null,\n };\n }\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping. We do this with the QueryRouteResponse wrapper\n // interface so we can know whether it was returned or thrown\n if (opts.isRouteRequest) {\n let queryRouteResponse: QueryRouteResponse = {\n type:\n resultType === ResultType.error ? ResultType.error : ResultType.data,\n response: result,\n };\n throw queryRouteResponse;\n }\n\n let data: any;\n\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return { type: ResultType.error, error: e };\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponseImpl(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 (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n 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\n errors = errors || {};\n\n // Prefer higher error values if lower errors bubble to the same boundary\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n } else {\n loaderData[id] = result.data;\n }\n\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. Also clear out any loaderData for the\n // throwing route\n if (pendingError) {\n errors = pendingError;\n loaderData[Object.keys(pendingError)[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n 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, controller } = 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 (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isQueryRouteResponse(obj: any): obj is QueryRouteResponse {\n return (\n obj &&\n isResponse(obj.response) &&\n (obj.type === ResultType.data || obj.type === ResultType.error)\n );\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\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 // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (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 let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\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\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n\n//#endregion\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","createHref","createPath","history","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","substr","startsWith","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","invariant","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","idx","current","_extends","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","getIndex","replaceState","handlePop","historyState","pushState","error","DOMException","name","assign","origin","addEventListener","removeEventListener","ResultType","immutableRouteKeys","Set","isIndexRoute","route","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","treePath","id","join","children","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","i","matchRouteBranch","safelyDecodeURI","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","joinPaths","routesMeta","concat","score","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","String","array","isLastSegment","star","keyMatch","optional","param","pattern","matcher","compiledParams","compilePath","captureGroups","memo","paramName","splatValue","safelyDecodeURIComponent","regexpSource","_","RegExp","decodeURI","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","resolvePathname","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","init","responseInit","status","headers","Headers","has","set","Response","AbortedDeferredError","DeferredData","constructor","pendingKeysSet","subscribers","deferredKeys","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","v","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","isTrackedPromise","_tracked","_error","_data","defer","redirect","redirectDocument","response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","dataRoutes","inFlightDataRoutes","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialErrors","getInternalRouterError","getShortCircuitMatches","initialized","hasLazyRoutes","m","lazy","hasLoaders","loader","errors","hydrate","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","deletedFetchers","activeDeferreds","blockerFunctions","ignoreNextHistoryUpdate","initialize","blockerKey","shouldBlockNavigation","currentLocation","updateBlocker","updateState","startNavigation","restoreAppliedTransitions","_saveAppliedTransitions","persistAppliedTransitions","initialHydration","dispose","clear","deleteFetcher","deleteBlocker","newState","opts","completedFetchers","deletedFetchersKeys","fetcher","unstable_viewTransitionOpts","viewTransitionOpts","unstable_flushSync","flushSync","completeNavigation","_temp","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","toPaths","getSavedScrollPosition","navigate","normalizedPath","normalizeTo","fromRouteId","relative","submission","normalizeNavigateOptions","userReplace","pendingError","enableViewTransition","unstable_viewTransition","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","routesToUse","loadingNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","request","createClientSideRequest","pendingActionData","findNearestBoundary","actionOutput","handleAction","shortCircuited","pendingActionError","getLoadingNavigation","Request","handleLoaders","fetcherSubmission","getSubmittingNavigation","actionMatch","getTargetMatch","type","method","routeId","callLoaderOrAction","isRedirectResult","startRedirectNavigation","isErrorResult","boundaryMatch","isDeferredResult","activeSubmission","getSubmissionFromNavigation","matchesToLoad","revalidatingFetchers","getMatchesToLoad","updatedFetchers","markFetchRedirectsDone","rf","revalidatingFetcher","getLoadingFetcher","abortFetcher","abortPendingFetchRevalidations","f","results","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","fetcherKey","processLoaderData","deferredData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","fetch","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","existingFetcher","updateFetcherState","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResult","getDoneFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","_temp2","redirectLocation","isDocumentReload","reloadDocument","redirectHistoryAction","currentMatches","fetchersToLoad","all","resolveDeferredResults","getFetcher","deleteFetcherAndUpdateState","count","markFetchersDone","doneKeys","landedId","yeetedKeys","getBlocker","blocker","newBlocker","blockerFunction","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","getScrollKey","_internalSetRoutes","newRoutes","_internalFetchControllers","_internalActiveDeferreds","UNSAFE_DEFERRED_SYMBOL","Symbol","createStaticHandler","query","_temp3","requestContext","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp4","find","values","_result$activeDeferre","routeMatch","submit","loadRouteData","isQueryRouteResponse","isRedirectResponse","isRouteRequest","isStaticRequest","Location","context","loaderRequest","getLoaderMatchesUntilBoundary","processRouteLoaderData","executedLoaders","fromEntries","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","isSubmissionNavigation","body","prependBasename","contextualMatches","activeRouteMatch","hasNakedIndexQuery","normalizeFormMethod","isFetcher","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","URLSearchParams","parse","searchParams","convertFormDataToSearchParams","convertSearchParamsToFormData","append","boundaryId","boundaryMatches","findIndex","isInitialLoad","currentUrl","nextUrl","navigationMatches","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","currentLoaderData","currentMatch","isNew","isMissingData","currentPath","loaderMatch","arg","routeChoice","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","staticRouteValue","isPropertyStaticallyDefined","resultType","onReject","runHandler","handler","handlerError","protocol","isSameBasename","queryRouteResponse","contentType","isDeferredData","_result$init","_result$init2","deferred","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","_temp5","errorMessage","obj","signals","isRevalidatingLoader","unwrap","getAll","_window","transitions","sessionPositions","sessionStorage","getItem","setItem"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;;AAEA;AACA;AACA;AACYA,IAAAA,MAAM,0BAANA,MAAM,EAAA;EAANA,MAAM,CAAA,KAAA,CAAA,GAAA,KAAA,CAAA;EAANA,MAAM,CAAA,MAAA,CAAA,GAAA,MAAA,CAAA;EAANA,MAAM,CAAA,SAAA,CAAA,GAAA,SAAA,CAAA;AAAA,EAAA,OAANA,MAAM,CAAA;AAAA,CAAA,CAAA,EAAA,EAAA;;AAwBlB;AACA;AACA;;AAkBA;AACA;AAEA;AACA;AACA;AACA;AAgBA;AACA;AACA;AAkBA;AACA;AACA;AAKA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAgFA,MAAMC,iBAAiB,GAAG,UAAU,CAAA;AACpC;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AASA;AACA;AACA;AACA;AACA;AAQA;AACA;AACA;AACA;AACO,SAASC,mBAAmBA,CACjCC,OA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AAuB,EACvBxT,IAAI,CAACC,SAAS,CAAC+N,IAAI,CACrB,CAAC,CAAA;KACF,CAAC,OAAOzJ,KAAK,EAAE;AACdzE,MAAAA,OAAO,CACL,KAAK,EACyDyE,6DAAAA,GAAAA,KAAK,OACrE,CAAC,CAAA;AACH,KAAA;AACF,GAAA;AACF,CAAA;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ 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 new file mode 100644 index 0000000..2d6a16a --- /dev/null +++ b/node_modules/@remix-run/router/dist/router.d.ts @@ -0,0 +1,507 @@ +import type { History, Location, Path, To } from "./history"; +import { Action as HistoryAction } from "./history"; +import type { AgnosticDataRouteMatch, AgnosticDataRouteObject, AgnosticRouteObject, DeferredData, DetectErrorBoundaryFunction, FormEncType, HTMLFormMethod, MapRoutePropertiesFunction, RouteData, Submission, UIMatch } 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 future config for the router + */ + get future(): FutureConfig; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Return the current state of the router + */ + get state(): RouterState; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Return the routes for this router instance + */ + get routes(): AgnosticDataRouteObject[]; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Return the window associated with the router + */ + get window(): RouterInit["window"]; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Initialize the router, including adding history listeners and kicking off + * initial data fetches. Returns a function to cleanup listeners and abort + * any in-progress loads + */ + initialize(): Router; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Subscribe to router.state updates + * + * @param fn function to call with the new state + */ + subscribe(fn: RouterSubscriber): () => void; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Enable scroll restoration behavior in the router + * + * @param savedScrollPositions Object that will manage positions, in case + * it's being restored from sessionStorage + * @param getScrollPosition Function to get the active Y scroll position + * @param getKey Function to get the key to use for restoration + */ + enableScrollRestoration(savedScrollPositions: Record, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Navigate forward/backward in the history stack + * @param to Delta to move in the history stack + */ + navigate(to: number): Promise; + /** + * Navigate to the given path + * @param to Path to navigate to + * @param opts Navigation options (method, submission, etc.) + */ + navigate(to: To | null, opts?: RouterNavigateOptions): Promise; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Trigger a fetcher load/submission + * + * @param key Fetcher key + * @param routeId Route that owns the fetcher + * @param href href to fetch + * @param opts Fetcher options, (method, submission, etc.) + */ + fetch(key: string, routeId: string, href: string | null, opts?: RouterFetchOptions): void; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Trigger a revalidation of all current route loaders and fetcher loads + */ + revalidate(): void; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Utility function to create an href for the given location + * @param location + */ + createHref(location: Location | URL): string; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Utility function to URL encode a destination path according to the internal + * history implementation + * @param to + */ + encodeLocation(to: To): Path; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Get/create a fetcher for the given key + * @param key + */ + getFetcher(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 + * + * Get a navigation blocker + * @param key The identifier for the blocker + * @param fn The blocker function implementation + */ + getBlocker(key: string, fn: BlockerFunction): Blocker; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Delete a navigation blocker + * @param key The identifier for the blocker + */ + deleteBlocker(key: string): void; + /** + * @internal + * PRIVATE - DO NOT USE + * + * HMR needs to pass in-flight route updates to React Router + * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute) + */ + _internalSetRoutes(routes: AgnosticRouteObject[]): void; + /** + * @internal + * PRIVATE - DO NOT USE + * + * Internal fetch AbortControllers accessed by unit tests + */ + _internalFetchControllers: Map; + /** + * @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; + /** + * Map of current blockers + */ + blockers: Map; +} +/** + * Data that can be passed into hydrate a Router from SSR + */ +export type HydrationState = Partial>; +/** + * Future flags to toggle new feature behavior + */ +export interface FutureConfig { + v7_fetcherPersist: boolean; + v7_normalizeFormMethod: boolean; + v7_partialHydration: boolean; + v7_prependBasename: boolean; + v7_relativeSplatPath: boolean; +} +/** + * Initialization options for createRouter + */ +export interface RouterInit { + routes: AgnosticRouteObject[]; + history: History; + basename?: string; + /** + * @deprecated Use `mapRouteProperties` instead + */ + detectErrorBoundary?: DetectErrorBoundaryFunction; + mapRouteProperties?: MapRoutePropertiesFunction; + future?: Partial; + hydrationData?: HydrationState; + window?: Window; +} +/** + * State returned from a server-side query() call + */ +export interface StaticHandlerContext { + basename: Router["basename"]; + location: RouterState["location"]; + matches: RouterState["matches"]; + loaderData: RouterState["loaderData"]; + actionData: RouterState["actionData"]; + errors: RouterState["errors"]; + statusCode: number; + loaderHeaders: Record; + actionHeaders: Record; + activeDeferreds: Record | null; + _deepestRenderedBoundaryId?: string | null; +} +/** + * A StaticHandler instance manages a singular SSR navigation/fetch event + */ +export interface StaticHandler { + dataRoutes: AgnosticDataRouteObject[]; + query(request: Request, opts?: { + requestContext?: unknown; + }): Promise; + queryRoute(request: Request, opts?: { + routeId?: string; + requestContext?: unknown; + }): Promise; +} +type ViewTransitionOpts = { + currentLocation: Location; + nextLocation: Location; +}; +/** + * Subscriber function signature for changes to router state + */ +export interface RouterSubscriber { + (state: RouterState, opts: { + deletedFetchers: string[]; + unstable_viewTransitionOpts?: ViewTransitionOpts; + unstable_flushSync: boolean; + }): void; +} +/** + * Function signature for determining the key to be used in scroll restoration + * for a given location + */ +export interface GetScrollRestorationKeyFunction { + (location: Location, matches: UIMatch[]): string | null; +} +/** + * Function signature for determining the current scroll position + */ +export interface GetScrollPositionFunction { + (): number; +} +export type RelativeRoutingType = "route" | "path"; +type BaseNavigateOrFetchOptions = { + preventScrollReset?: boolean; + relative?: RelativeRoutingType; + unstable_flushSync?: boolean; +}; +type BaseNavigateOptions = BaseNavigateOrFetchOptions & { + replace?: boolean; + state?: any; + fromRouteId?: string; + unstable_viewTransition?: boolean; +}; +type BaseSubmissionOptions = { + formMethod?: HTMLFormMethod; + formEncType?: FormEncType; +} & ({ + formData: FormData; + body?: undefined; +} | { + formData?: undefined; + body: any; +}); +/** + * Options for a navigate() call for a normal (non-submission) navigation + */ +type LinkNavigateOptions = BaseNavigateOptions; +/** + * Options for a navigate() call for a submission navigation + */ +type SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions; +/** + * Options to pass to navigate() for a navigation + */ +export type RouterNavigateOptions = LinkNavigateOptions | SubmissionNavigateOptions; +/** + * Options for a fetch() load + */ +type LoadFetchOptions = BaseNavigateOrFetchOptions; +/** + * Options for a fetch() submission + */ +type SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions; +/** + * Options to pass to fetch() + */ +export type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions; +/** + * Potential states for state.navigation + */ +export type NavigationStates = { + Idle: { + state: "idle"; + location: undefined; + formMethod: undefined; + formAction: undefined; + formEncType: undefined; + formData: undefined; + json: undefined; + text: undefined; + }; + Loading: { + state: "loading"; + location: Location; + formMethod: Submission["formMethod"] | undefined; + formAction: Submission["formAction"] | undefined; + formEncType: Submission["formEncType"] | undefined; + formData: Submission["formData"] | undefined; + json: Submission["json"] | undefined; + text: Submission["text"] | undefined; + }; + Submitting: { + state: "submitting"; + location: Location; + formMethod: Submission["formMethod"]; + formAction: Submission["formAction"]; + formEncType: Submission["formEncType"]; + formData: Submission["formData"]; + json: Submission["json"]; + text: Submission["text"]; + }; +}; +export type Navigation = NavigationStates[keyof NavigationStates]; +export type RevalidationState = "idle" | "loading"; +/** + * Potential states for fetchers + */ +type FetcherStates = { + Idle: { + state: "idle"; + formMethod: undefined; + formAction: undefined; + formEncType: undefined; + text: undefined; + formData: undefined; + json: undefined; + data: TData | undefined; + }; + Loading: { + state: "loading"; + formMethod: Submission["formMethod"] | undefined; + formAction: Submission["formAction"] | undefined; + formEncType: Submission["formEncType"] | undefined; + text: Submission["text"] | undefined; + formData: Submission["formData"] | undefined; + json: Submission["json"] | undefined; + data: TData | undefined; + }; + Submitting: { + state: "submitting"; + formMethod: Submission["formMethod"]; + formAction: Submission["formAction"]; + formEncType: Submission["formEncType"]; + text: Submission["text"]; + formData: Submission["formData"]; + json: Submission["json"]; + data: TData | undefined; + }; +}; +export type Fetcher = FetcherStates[keyof FetcherStates]; +interface BlockerBlocked { + state: "blocked"; + reset(): void; + proceed(): void; + location: Location; +} +interface BlockerUnblocked { + state: "unblocked"; + reset: undefined; + proceed: undefined; + location: undefined; +} +interface BlockerProceeding { + state: "proceeding"; + reset: undefined; + proceed: undefined; + location: Location; +} +export type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding; +export type BlockerFunction = (args: { + currentLocation: Location; + nextLocation: Location; + historyAction: HistoryAction; +}) => boolean; +export declare const IDLE_NAVIGATION: NavigationStates["Idle"]; +export declare const IDLE_FETCHER: FetcherStates["Idle"]; +export declare const IDLE_BLOCKER: BlockerUnblocked; +/** + * Create a router and listen to history POP navigations + */ +export declare function createRouter(init: RouterInit): Router; +export declare const UNSAFE_DEFERRED_SYMBOL: unique symbol; +/** + * Future flags to toggle new feature behavior + */ +export interface StaticHandlerFutureConfig { + v7_relativeSplatPath: boolean; +} +export interface CreateStaticHandlerOptions { + basename?: string; + /** + * @deprecated Use `mapRouteProperties` instead + */ + detectErrorBoundary?: DetectErrorBoundaryFunction; + mapRouteProperties?: MapRoutePropertiesFunction; + future?: Partial; +} +export declare function createStaticHandler(routes: AgnosticRouteObject[], opts?: CreateStaticHandlerOptions): 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 declare function isDeferredData(value: any): value is DeferredData; +export {}; diff --git a/node_modules/@remix-run/router/dist/router.js b/node_modules/@remix-run/router/dist/router.js new file mode 100644 index 0000000..dc565ad --- /dev/null +++ b/node_modules/@remix-run/router/dist/router.js @@ -0,0 +1,4299 @@ +/** + * @remix-run/router v1.14.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(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to)); + return location; + } + function createHref(to) { + return typeof to === "string" ? to : createPath(to); + } + let history = { + get index() { + return index; + }, + get action() { + return action; + }, + get location() { + return getCurrentLocation(); + }, + createHref, + createURL(to) { + return new URL(createHref(to), "http://localhost"); + }, + encodeLocation(to) { + let path = typeof to === "string" ? parsePath(to) : to; + return { + pathname: path.pathname || "", + search: path.search || "", + hash: path.hash || "" + }; + }, + push(to, state) { + action = Action.Push; + let nextLocation = createMemoryLocation(to, state); + index += 1; + entries.splice(index, entries.length, nextLocation); + if (v5Compat && listener) { + listener({ + action, + location: nextLocation, + delta: 1 + }); + } + }, + replace(to, state) { + action = Action.Replace; + let nextLocation = createMemoryLocation(to, state); + entries[index] = nextLocation; + if (v5Compat && listener) { + listener({ + action, + location: nextLocation, + delta: 0 + }); + } + }, + go(delta) { + action = Action.Pop; + let nextIndex = clampIndex(index + delta); + let nextLocation = entries[nextIndex]; + index = nextIndex; + if (listener) { + listener({ + action, + location: nextLocation, + delta + }); + } + }, + listen(fn) { + listener = fn; + return () => { + listener = null; + }; + } + }; + return history; +} +/** + * Browser history stores the location in regular URLs. This is the standard for + * most web apps, but it requires some configuration on the server to ensure you + * serve the same app at multiple URLs. + * + * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory + */ +function createBrowserHistory(options) { + if (options === void 0) { + options = {}; + } + function createBrowserLocation(window, globalHistory) { + let { + pathname, + search, + hash + } = window.location; + return createLocation("", { + pathname, + search, + hash + }, + // state defaults to `null` because `window.history.state` does + globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); + } + function createBrowserHref(window, to) { + return typeof to === "string" ? to : createPath(to); + } + return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options); +} +/** + * Hash history stores the location in window.location.hash. This makes it ideal + * for situations where you don't want to send the location to the server for + * some reason, either because you do cannot configure it or the URL space is + * reserved for something else. + * + * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory + */ +function createHashHistory(options) { + if (options === void 0) { + options = {}; + } + function createHashLocation(window, globalHistory) { + let { + pathname = "/", + search = "", + hash = "" + } = parsePath(window.location.hash.substr(1)); + // Hash URL should always have a leading / just like window.location.pathname + // does, so if an app ends up at a route like /#something then we add a + // leading slash so all of our path-matching behaves the same as if it would + // in a browser router. This is particularly important when there exists a + // root splat route () since that matches internally against + // "/*" and we'd expect /#something to 404 in a hash router app. + if (!pathname.startsWith("/") && !pathname.startsWith(".")) { + pathname = "/" + pathname; + } + return createLocation("", { + pathname, + search, + hash + }, + // state defaults to `null` because `window.history.state` does + globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); + } + function createHashHref(window, to) { + let base = window.document.querySelector("base"); + let href = ""; + if (base && base.getAttribute("href")) { + let url = window.location.href; + let hashIndex = url.indexOf("#"); + href = hashIndex === -1 ? url : url.slice(0, hashIndex); + } + return href + "#" + (typeof to === "string" ? to : createPath(to)); + } + function validateHashLocation(location, to) { + warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")"); + } + return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options); +} +function invariant(value, message) { + if (value === false || value === null || typeof value === "undefined") { + throw new Error(message); + } +} +function warning(cond, message) { + if (!cond) { + // eslint-disable-next-line no-console + if (typeof console !== "undefined") console.warn(message); + try { + // Welcome to debugging history! + // + // This error is thrown as a convenience, so you can more easily + // find the source for a warning that appears in the console by + // enabling "pause on exceptions" in your JavaScript debugger. + throw new Error(message); + // eslint-disable-next-line no-empty + } catch (e) {} + } +} +function createKey() { + return Math.random().toString(36).substr(2, 8); +} +/** + * For browser-based histories, we combine the state and key into an object + */ +function getHistoryState(location, index) { + return { + usr: location.state, + key: location.key, + idx: index + }; +} +/** + * Creates a Location object with a unique key from the given Path + */ +function createLocation(current, to, state, key) { + if (state === void 0) { + state = null; + } + let location = _extends({ + pathname: typeof current === "string" ? current : current.pathname, + search: "", + hash: "" + }, typeof to === "string" ? parsePath(to) : to, { + state, + // TODO: This could be cleaned up. push/replace should probably just take + // full Locations now and avoid the need to run through this flow at all + // But that's a pretty big refactor to the current test suite so going to + // keep as is for the time being and just let any incoming keys take precedence + key: to && to.key || key || createKey() + }); + return location; +} +/** + * Creates a string URL path from the given pathname, search, and hash components. + */ +function createPath(_ref) { + let { + pathname = "/", + search = "", + hash = "" + } = _ref; + if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search; + if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash; + return pathname; +} +/** + * Parses a string URL path into its separate pathname, search, and hash components. + */ +function parsePath(path) { + let parsedPath = {}; + if (path) { + let hashIndex = path.indexOf("#"); + if (hashIndex >= 0) { + parsedPath.hash = path.substr(hashIndex); + path = path.substr(0, hashIndex); + } + let searchIndex = path.indexOf("?"); + if (searchIndex >= 0) { + parsedPath.search = path.substr(searchIndex); + path = path.substr(0, searchIndex); + } + if (path) { + parsedPath.pathname = path; + } + } + return parsedPath; +} +function getUrlBasedHistory(getLocation, createHref, validateLocation, options) { + if (options === void 0) { + options = {}; + } + let { + window = document.defaultView, + v5Compat = false + } = options; + let globalHistory = window.history; + let action = Action.Pop; + let listener = null; + let index = getIndex(); + // Index should only be null when we initialize. If not, it's because the + // user called history.pushState or history.replaceState directly, in which + // case we should log a warning as it will result in bugs. + if (index == null) { + index = 0; + globalHistory.replaceState(_extends({}, globalHistory.state, { + idx: index + }), ""); + } + function getIndex() { + let state = globalHistory.state || { + idx: null + }; + return state.idx; + } + function handlePop() { + action = Action.Pop; + let nextIndex = getIndex(); + let delta = nextIndex == null ? null : nextIndex - index; + index = nextIndex; + if (listener) { + listener({ + action, + location: history.location, + delta + }); + } + } + function push(to, state) { + action = Action.Push; + let location = createLocation(history.location, to, state); + if (validateLocation) validateLocation(location, to); + index = getIndex() + 1; + let historyState = getHistoryState(location, index); + let url = history.createHref(location); + // try...catch because iOS limits us to 100 pushState calls :/ + try { + globalHistory.pushState(historyState, "", url); + } catch (error) { + // If the exception is because `state` can't be serialized, let that throw + // outwards just like a replace call would so the dev knows the cause + // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps + // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal + if (error instanceof DOMException && error.name === "DataCloneError") { + throw error; + } + // They are going to lose state here, but there is no real + // way to warn them about it since the page will refresh... + window.location.assign(url); + } + if (v5Compat && listener) { + listener({ + action, + location: history.location, + delta: 1 + }); + } + } + function replace(to, state) { + action = Action.Replace; + let location = createLocation(history.location, to, state); + if (validateLocation) validateLocation(location, to); + index = getIndex(); + let historyState = getHistoryState(location, index); + let url = history.createHref(location); + globalHistory.replaceState(historyState, "", url); + if (v5Compat && listener) { + listener({ + action, + location: history.location, + delta: 0 + }); + } + } + function createURL(to) { + // window.location.origin is "null" (the literal string value) in Firefox + // under certain conditions, notably when serving from a local HTML file + // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297 + let base = window.location.origin !== "null" ? window.location.origin : window.location.href; + let href = typeof to === "string" ? to : createPath(to); + invariant(base, "No window.location.(origin|href) available to create URL for href: " + href); + return new URL(href, base); + } + let history = { + get action() { + return action; + }, + get location() { + return getLocation(window, globalHistory); + }, + listen(fn) { + if (listener) { + throw new Error("A history only accepts one active listener"); + } + window.addEventListener(PopStateEventType, handlePop); + listener = fn; + return () => { + window.removeEventListener(PopStateEventType, handlePop); + listener = null; + }; + }, + createHref(to) { + return createHref(window, to); + }, + createURL, + encodeLocation(to) { + // Encode a Location the same way window.location would + let url = createURL(to); + return { + pathname: url.pathname, + search: url.search, + hash: url.hash + }; + }, + push, + replace, + go(n) { + return globalHistory.go(n); + } + }; + return history; +} +//#endregion + +var ResultType; +(function (ResultType) { + ResultType["data"] = "data"; + ResultType["deferred"] = "deferred"; + ResultType["redirect"] = "redirect"; + ResultType["error"] = "error"; +})(ResultType || (ResultType = {})); +const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]); +function isIndexRoute(route) { + return route.index === true; +} +// Walk the route tree generating unique IDs where necessary, so we are working +// solely with AgnosticDataRouteObject's within the Router +function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) { + if (parentPath === void 0) { + parentPath = []; + } + if (manifest === void 0) { + manifest = {}; + } + return routes.map((route, index) => { + let treePath = [...parentPath, index]; + let id = typeof route.id === "string" ? route.id : treePath.join("-"); + invariant(route.index !== true || !route.children, "Cannot specify children on an index route"); + invariant(!manifest[id], "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages"); + if (isIndexRoute(route)) { + let indexRoute = _extends({}, route, mapRouteProperties(route), { + id + }); + manifest[id] = indexRoute; + return indexRoute; + } else { + let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), { + id, + children: undefined + }); + manifest[id] = pathOrLayoutRoute; + if (route.children) { + pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest); + } + return pathOrLayoutRoute; + } + }); +} +/** + * Matches the given routes to a location and returns the match data. + * + * @see https://reactrouter.com/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], + // Incoming pathnames are generally encoded from either window.location + // or from router.navigate, but we want to match against the unencoded + // paths in the route definitions. Memory router locations won't be + // encoded here but there also shouldn't be anything to decode so this + // should be a safe operation. This avoids needing matchRoutes to be + // history-aware. + safelyDecodeURI(pathname)); + } + return matches; +} +function convertRouteMatchToUiMatch(match, loaderData) { + let { + route, + pathname, + params + } = match; + return { + id: route.id, + pathname, + params, + data: loaderData[route.id], + handle: route.handle + }; +} +function flattenRoutes(routes, branches, parentsMeta, parentPath) { + if (branches === void 0) { + branches = []; + } + if (parentsMeta === void 0) { + parentsMeta = []; + } + if (parentPath === void 0) { + parentPath = ""; + } + let flattenRoute = (route, index, relativePath) => { + let meta = { + relativePath: relativePath === undefined ? route.path || "" : relativePath, + caseSensitive: route.caseSensitive === true, + childrenIndex: index, + route + }; + if (meta.relativePath.startsWith("/")) { + invariant(meta.relativePath.startsWith(parentPath), "Absolute route path \"" + meta.relativePath + "\" nested under path " + ("\"" + parentPath + "\" is not valid. An absolute child route path ") + "must start with the combined path of all its parent routes."); + meta.relativePath = meta.relativePath.slice(parentPath.length); + } + let path = joinPaths([parentPath, meta.relativePath]); + let routesMeta = parentsMeta.concat(meta); + // Add the children before adding this route to the array, so we traverse the + // route tree depth-first and child routes appear before their parents in + // the "flattened" version. + if (route.children && route.children.length > 0) { + invariant( + // Our types know better, but runtime JS may not! + // @ts-expect-error + route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\".")); + flattenRoutes(route.children, branches, routesMeta, path); + } + // Routes without a path shouldn't ever match by themselves unless they are + // index routes, so don't add them to the list of possible branches. + if (route.path == null && !route.index) { + return; + } + branches.push({ + path, + score: computeScore(path, route.index), + routesMeta + }); + }; + routes.forEach((route, index) => { + var _route$path; + // coarse-grain check for optional params + if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) { + flattenRoute(route, index); + } else { + for (let exploded of explodeOptionalSegments(route.path)) { + flattenRoute(route, index, exploded); + } + } + }); + return branches; +} +/** + * Computes all combinations of optional path segments for a given path, + * excluding combinations that are ambiguous and of lower priority. + * + * For example, `/one/:two?/three/:four?/:five?` explodes to: + * - `/one/three` + * - `/one/:two/three` + * - `/one/three/:four` + * - `/one/three/:five` + * - `/one/:two/three/:four` + * - `/one/:two/three/:five` + * - `/one/three/:four/:five` + * - `/one/:two/three/:four/:five` + */ +function explodeOptionalSegments(path) { + let segments = path.split("/"); + if (segments.length === 0) return []; + let [first, ...rest] = segments; + // Optional path segments are denoted by a trailing `?` + let isOptional = first.endsWith("?"); + // Compute the corresponding required segment: `foo?` -> `foo` + let required = first.replace(/\?$/, ""); + if (rest.length === 0) { + // Intepret empty string as omitting an optional segment + // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three` + return isOptional ? [required, ""] : [required]; + } + let restExploded = explodeOptionalSegments(rest.join("/")); + let result = []; + // All child paths with the prefix. Do this for all children before the + // optional version for all children, so we get consistent ordering where the + // parent optional aspect is preferred as required. Otherwise, we can get + // child sections interspersed where deeper optional segments are higher than + // parent optional segments, where for example, /:two would explode _earlier_ + // then /:one. By always including the parent as required _for all children_ + // first, we avoid this issue + result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/"))); + // Then, if this is an optional value, add all child versions without + if (isOptional) { + result.push(...restExploded); + } + // for absolute paths, ensure `/` instead of empty segment + return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded); +} +function rankRouteBranches(branches) { + branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first + : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex))); +} +const paramRe = /^:[\w-]+$/; +const dynamicSegmentValue = 3; +const indexRouteValue = 2; +const emptySegmentValue = 1; +const staticSegmentValue = 10; +const splatPenalty = -2; +const isSplat = s => s === "*"; +function computeScore(path, index) { + let segments = path.split("/"); + let initialScore = segments.length; + if (segments.some(isSplat)) { + initialScore += splatPenalty; + } + if (index) { + initialScore += indexRouteValue; + } + return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore); +} +function compareIndexes(a, b) { + let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]); + return siblings ? + // If two routes are siblings, we should try to match the earlier sibling + // first. This allows people to have fine-grained control over the matching + // behavior by simply putting routes with identical paths in the order they + // want them tried. + a[a.length - 1] - b[b.length - 1] : + // Otherwise, it doesn't really make sense to rank non-siblings by index, + // so they sort equally. + 0; +} +function matchRouteBranch(branch, pathname) { + 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/utils/generate-path + */ +function generatePath(originalPath, params) { + if (params === void 0) { + params = {}; + } + let path = originalPath; + if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) { + warning(false, "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); + path = path.replace(/\*$/, "/*"); + } + // ensure `/` is added at the beginning if the path is absolute + const prefix = path.startsWith("/") ? "/" : ""; + const stringify = p => p == null ? "" : typeof p === "string" ? p : String(p); + const segments = path.split(/\/+/).map((segment, index, array) => { + const isLastSegment = index === array.length - 1; + // only apply the splat if it's the last segment + if (isLastSegment && segment === "*") { + const star = "*"; + // Apply the splat + return stringify(params[star]); + } + const keyMatch = segment.match(/^:([\w-]+)(\??)$/); + if (keyMatch) { + const [, key, optional] = keyMatch; + let param = params[key]; + invariant(optional === "?" || param != null, "Missing \":" + key + "\" param"); + return stringify(param); + } + // Remove any optional markers from optional static segments + return segment.replace(/\?$/g, ""); + }) + // Remove empty segments + .filter(segment => !!segment); + return prefix + segments.join("/"); +} +/** + * Performs pattern matching on a URL pathname and returns information about + * the match. + * + * @see https://reactrouter.com/utils/match-path + */ +function matchPath(pattern, pathname) { + if (typeof pattern === "string") { + pattern = { + path: pattern, + caseSensitive: false, + end: true + }; + } + let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end); + let match = pathname.match(matcher); + if (!match) return null; + let matchedPathname = match[0]; + let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1"); + let captureGroups = match.slice(1); + let params = compiledParams.reduce((memo, _ref, index) => { + let { + paramName, + isOptional + } = _ref; + // We need to compute the pathnameBase here using the raw splat value + // instead of using params["*"] later because it will be decoded then + if (paramName === "*") { + let splatValue = captureGroups[index] || ""; + pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1"); + } + const value = captureGroups[index]; + if (isOptional && !value) { + memo[paramName] = undefined; + } else { + memo[paramName] = safelyDecodeURIComponent(value || "", paramName); + } + return memo; + }, {}); + return { + params, + pathname: matchedPathname, + pathnameBase, + pattern + }; +} +function compilePath(path, caseSensitive, end) { + if (caseSensitive === void 0) { + caseSensitive = false; + } + if (end === void 0) { + end = true; + } + warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); + let params = []; + let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below + .replace(/^\/*/, "/") // Make sure it has a leading / + .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars + .replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => { + params.push({ + paramName, + isOptional: isOptional != null + }); + return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)"; + }); + if (path.endsWith("*")) { + params.push({ + paramName: "*" + }); + regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest + : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"] + } else if (end) { + // When matching to the end, ignore trailing slashes + regexpSource += "\\/*$"; + } else if (path !== "" && path !== "/") { + // If our path is non-empty and contains anything beyond an initial slash, + // then we have _some_ form of path in our regex, so we should expect to + // match only if we find the end of this path segment. Look for an optional + // non-captured trailing slash (to match a portion of the URL) or the end + // of the path (if we've matched to the end). We used to do this with a + // word boundary but that gives false positives on routes like + // /user-preferences since `-` counts as a word boundary. + regexpSource += "(?:(?=\\/|$))"; + } else ; + let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i"); + return [matcher, params]; +} +function safelyDecodeURI(value) { + try { + return decodeURI(value); + } catch (error) { + warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ").")); + return value; + } +} +function safelyDecodeURIComponent(value, paramName) { + try { + return decodeURIComponent(value); + } catch (error) { + warning(false, "The value for the URL param \"" + paramName + "\" will not be decoded because" + (" the string \"" + value + "\" is a malformed URL segment. This is probably") + (" due to a bad percent encoding (" + error + ").")); + return value; + } +} +/** + * @private + */ +function stripBasename(pathname, basename) { + if (basename === "/") return pathname; + if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) { + return null; + } + // We want to leave trailing slash behavior in the user's control, so if they + // specify a basename with a trailing slash, we should support it + let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length; + let nextChar = pathname.charAt(startIndex); + if (nextChar && nextChar !== "/") { + // pathname does not start with basename/ + return null; + } + return pathname.slice(startIndex) || "/"; +} +/** + * Returns a resolved path object relative to the given pathname. + * + * @see https://reactrouter.com/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 + * + * When processing relative navigation we want to ignore ancestor routes that + * do not contribute to the path, such that index/pathless layout routes don't + * interfere. + * + * For example, when moving a route element into an index route and/or a + * pathless layout route, relative link behavior contained within should stay + * the same. Both of the following examples should link back to the root: + * + * + * + * + * + * + * + * }> // <-- Does not contribute + * // <-- Does not contribute + * + * + */ +function getPathContributingMatches(matches) { + return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0); +} +// Return the array of pathnames for the current route matches - used to +// generate the routePathnames input for resolveTo() +function getResolveToMatches(matches, v7_relativeSplatPath) { + let pathMatches = getPathContributingMatches(matches); + // When v7_relativeSplatPath is enabled, use the full pathname for the leaf + // match so we include splat values for "." links. See: + // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329 + if (v7_relativeSplatPath) { + return pathMatches.map((match, idx) => idx === matches.length - 1 ? match.pathname : match.pathnameBase); + } + return pathMatches.map(match => match.pathnameBase); +} +/** + * @private + */ +function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) { + if (isPathRelative === void 0) { + isPathRelative = false; + } + let to; + if (typeof toArg === "string") { + to = parsePath(toArg); + } else { + to = _extends({}, toArg); + invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to)); + invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to)); + invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to)); + } + let isEmptyPath = toArg === "" || to.pathname === ""; + let toPathname = isEmptyPath ? "/" : to.pathname; + let from; + // Routing is relative to the current pathname if explicitly requested. + // + // If a pathname is explicitly provided in `to`, it should be relative to the + // route context. This is explained in `Note on `` values` in our + // migration guide from v5 as a means of disambiguation between `to` values + // that begin with `/` and those that do not. However, this is problematic for + // `to` values that do not provide a pathname. `to` can simply be a search or + // hash string, in which case we should assume that the navigation is relative + // to the current location's pathname and *not* the route pathname. + if (toPathname == null) { + from = locationPathname; + } else { + let routePathnameIndex = routePathnames.length - 1; + // With relative="route" (the default), each leading .. segment means + // "go up one route" instead of "go up one URL segment". This is a key + // difference from how works and a major reason we call this a + // "to" value instead of a "href". + if (!isPathRelative && toPathname.startsWith("..")) { + let toSegments = toPathname.split("/"); + while (toSegments[0] === "..") { + toSegments.shift(); + routePathnameIndex -= 1; + } + to.pathname = toSegments.join("/"); + } + from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/"; + } + let path = resolvePath(to, from); + // Ensure the pathname has a trailing slash if the original "to" had one + let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); + // Or if this was a link to the current path which has a trailing slash + let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/"); + if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) { + path.pathname += "/"; + } + return path; +} +/** + * @private + */ +function getToPathname(to) { + // Empty strings should be treated the same as / paths + return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname; +} +/** + * @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, responseInit) { + this.pendingKeysSet = new Set(); + this.subscribers = new Set(); + this.deferredKeys = []; + invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects"); + // Set up an AbortController + Promise we can race against to exit early + // cancellation + let reject; + this.abortPromise = new Promise((_, r) => reject = r); + this.controller = new AbortController(); + let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted")); + this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort); + this.controller.signal.addEventListener("abort", onAbort); + this.data = Object.entries(data).reduce((acc, _ref2) => { + let [key, value] = _ref2; + return Object.assign(acc, { + [key]: this.trackPromise(key, value) + }); + }, {}); + if (this.done) { + // All incoming values were resolved + this.unlistenAbortSignal(); + } + this.init = responseInit; + } + trackPromise(key, value) { + if (!(value instanceof Promise)) { + return value; + } + this.deferredKeys.push(key); + this.pendingKeysSet.add(key); + // We store a little wrapper promise that will be extended with + // _data/_error props upon resolve/reject + let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error)); + // Register rejection listeners to avoid uncaught promise rejections on + // errors or aborted deferred values + promise.catch(() => {}); + Object.defineProperty(promise, "_tracked", { + get: () => true + }); + return promise; + } + onSettle(promise, key, error, data) { + if (this.controller.signal.aborted && error instanceof AbortedDeferredError) { + this.unlistenAbortSignal(); + Object.defineProperty(promise, "_error", { + get: () => error + }); + return Promise.reject(error); + } + this.pendingKeysSet.delete(key); + if (this.done) { + // Nothing left to abort! + this.unlistenAbortSignal(); + } + // If the promise was resolved/rejected with undefined, we'll throw an error as you + // should always resolve with a value or null + if (error === undefined && data === undefined) { + let undefinedError = new Error("Deferred data for key \"" + key + "\" resolved/rejected with `undefined`, " + "you must resolve/reject with a value or `null`."); + Object.defineProperty(promise, "_error", { + get: () => undefinedError + }); + this.emit(false, key); + return Promise.reject(undefinedError); + } + if (data === undefined) { + Object.defineProperty(promise, "_error", { + get: () => error + }); + this.emit(false, key); + return Promise.reject(error); + } + Object.defineProperty(promise, "_data", { + get: () => data + }); + this.emit(false, key); + return data; + } + emit(aborted, settledKey) { + this.subscribers.forEach(subscriber => subscriber(aborted, settledKey)); + } + subscribe(fn) { + this.subscribers.add(fn); + return () => this.subscribers.delete(fn); + } + cancel() { + this.controller.abort(); + this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k)); + this.emit(true); + } + async resolveData(signal) { + let aborted = false; + if (!this.done) { + let onAbort = () => this.cancel(); + signal.addEventListener("abort", onAbort); + aborted = await new Promise(resolve => { + this.subscribe(aborted => { + signal.removeEventListener("abort", onAbort); + if (aborted || this.done) { + resolve(aborted); + } + }); + }); + } + return aborted; + } + get done() { + return this.pendingKeysSet.size === 0; + } + get unwrappedData() { + invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds"); + return Object.entries(this.data).reduce((acc, _ref3) => { + let [key, value] = _ref3; + return Object.assign(acc, { + [key]: unwrapTrackedPromise(value) + }); + }, {}); + } + get pendingKeys() { + return Array.from(this.pendingKeysSet); + } +} +function isTrackedPromise(value) { + return value instanceof Promise && value._tracked === true; +} +function unwrapTrackedPromise(value) { + if (!isTrackedPromise(value)) { + return value; + } + if (value._error) { + throw value._error; + } + return value._data; +} +const defer = function defer(data, init) { + if (init === void 0) { + init = {}; + } + let responseInit = typeof init === "number" ? { + status: init + } : init; + return new DeferredData(data, responseInit); +}; +/** + * A redirect response. Sets the status code and the `Location` header. + * Defaults to "302 Found". + */ +const redirect = function redirect(url, init) { + if (init === void 0) { + init = 302; + } + let responseInit = init; + if (typeof responseInit === "number") { + responseInit = { + status: responseInit + }; + } else if (typeof responseInit.status === "undefined") { + responseInit.status = 302; + } + let headers = new Headers(responseInit.headers); + headers.set("Location", url); + return new Response(null, _extends({}, responseInit, { + headers + })); +}; +/** + * A redirect response that will force a document reload to the new location. + * Sets the status code and the `Location` header. + * Defaults to "302 Found". + */ +const redirectDocument = (url, init) => { + let response = redirect(url, init); + response.headers.set("X-Remix-Reload-Document", "true"); + return response; +}; +/** + * @private + * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies + * + * We don't export the class for public use since it's an implementation + * detail, but we export the interface above so folks can build their own + * abstractions around instances via isRouteErrorResponse() + */ +class ErrorResponseImpl { + constructor(status, statusText, data, internal) { + if (internal === void 0) { + internal = false; + } + this.status = status; + this.statusText = statusText || ""; + this.internal = internal; + if (data instanceof Error) { + this.data = data.toString(); + this.error = data; + } else { + this.data = data; + } + } +} +/** + * Check if the given error is an ErrorResponse generated from a 4xx/5xx + * Response thrown from an action/loader + */ +function isRouteErrorResponse(error) { + return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error; +} + +const validMutationMethodsArr = ["post", "put", "patch", "delete"]; +const validMutationMethods = new Set(validMutationMethodsArr); +const validRequestMethodsArr = ["get", ...validMutationMethodsArr]; +const validRequestMethods = new Set(validRequestMethodsArr); +const redirectStatusCodes = new Set([301, 302, 303, 307, 308]); +const redirectPreserveMethodStatusCodes = new Set([307, 308]); +const IDLE_NAVIGATION = { + state: "idle", + location: undefined, + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined +}; +const IDLE_FETCHER = { + state: "idle", + data: undefined, + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined +}; +const IDLE_BLOCKER = { + state: "unblocked", + proceed: undefined, + reset: undefined, + location: undefined +}; +const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; +const defaultMapRouteProperties = route => ({ + hasErrorBoundary: Boolean(route.hasErrorBoundary) +}); +const TRANSITIONS_STORAGE_KEY = "remix-router-transitions"; +//#endregion +//////////////////////////////////////////////////////////////////////////////// +//#region createRouter +//////////////////////////////////////////////////////////////////////////////// +/** + * Create a router and listen to history POP navigations + */ +function createRouter(init) { + const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined; + const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined"; + const isServer = !isBrowser; + invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter"); + let mapRouteProperties; + if (init.mapRouteProperties) { + mapRouteProperties = init.mapRouteProperties; + } else if (init.detectErrorBoundary) { + // If they are still using the deprecated version, wrap it with the new API + let detectErrorBoundary = init.detectErrorBoundary; + mapRouteProperties = route => ({ + hasErrorBoundary: detectErrorBoundary(route) + }); + } else { + mapRouteProperties = defaultMapRouteProperties; + } + // Routes keyed by ID + let manifest = {}; + // Routes in tree format for matching + let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest); + let inFlightDataRoutes; + let basename = init.basename || "/"; + // Config driven behavior flags + let future = _extends({ + v7_fetcherPersist: false, + v7_normalizeFormMethod: false, + v7_partialHydration: false, + v7_prependBasename: false, + v7_relativeSplatPath: false + }, init.future); + // Cleanup function for history + let unlistenHistory = null; + // Externally-provided functions to call on all state changes + let subscribers = new Set(); + // Externally-provided object to hold scroll restoration locations during routing + let savedScrollPositions = null; + // Externally-provided function to get scroll restoration keys + let getScrollRestorationKey = null; + // Externally-provided function to get current scroll position + let getScrollPosition = null; + // One-time flag to control the initial hydration scroll restoration. Because + // we don't get the saved positions from until _after_ + // the initial render, we need to manually trigger a separate updateState to + // send along the restoreScrollPosition + // Set to true if we have `hydrationData` since we assume we were SSR'd and that + // SSR did the initial scroll restoration. + let initialScrollRestored = init.hydrationData != null; + let initialMatches = matchRoutes(dataRoutes, init.history.location, basename); + let 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 error = getInternalRouterError(404, { + pathname: init.history.location.pathname + }); + let { + matches, + route + } = getShortCircuitMatches(dataRoutes); + initialMatches = matches; + initialErrors = { + [route.id]: error + }; + } + let initialized; + let hasLazyRoutes = initialMatches.some(m => m.route.lazy); + let hasLoaders = initialMatches.some(m => m.route.loader); + if (hasLazyRoutes) { + // All initialMatches need to be loaded before we're ready. If we have lazy + // functions around still then we'll need to run them in initialize() + initialized = false; + } else if (!hasLoaders) { + // If we've got no loaders to run, then we're good to go + initialized = true; + } else if (future.v7_partialHydration) { + // If partial hydration is enabled, we're initialized so long as we were + // provided with hydrationData for every route with a loader, and no loaders + // were marked for explicit hydration + let loaderData = init.hydrationData ? init.hydrationData.loaderData : null; + let errors = init.hydrationData ? init.hydrationData.errors : null; + initialized = initialMatches.every(m => m.route.loader && m.route.loader.hydrate !== true && (loaderData && loaderData[m.route.id] !== undefined || errors && errors[m.route.id] !== undefined)); + } else { + // Without partial hydration - we're initialized if we were provided any + // hydrationData - which is expected to be complete + initialized = init.hydrationData != null; + } + let router; + let state = { + historyAction: init.history.action, + location: init.history.location, + matches: initialMatches, + initialized, + navigation: IDLE_NAVIGATION, + // Don't restore on initial updateState() if we were SSR'd + restoreScrollPosition: init.hydrationData != null ? false : null, + preventScrollReset: false, + revalidation: "idle", + loaderData: init.hydrationData && init.hydrationData.loaderData || {}, + actionData: init.hydrationData && init.hydrationData.actionData || null, + errors: init.hydrationData && init.hydrationData.errors || initialErrors, + fetchers: new Map(), + blockers: new Map() + }; + // -- Stateful internal variables to manage navigations -- + // Current navigation in progress (to be committed in completeNavigation) + let pendingAction = Action.Pop; + // Should the current navigation prevent the scroll reset if scroll cannot + // be restored? + let pendingPreventScrollReset = false; + // AbortController for the active navigation + let pendingNavigationController; + // Should the current navigation enable document.startViewTransition? + let pendingViewTransitionEnabled = false; + // Store applied view transitions so we can apply them on POP + let appliedViewTransitions = new Map(); + // Cleanup function for persisting applied transitions to sessionStorage + let removePageHideEventListener = null; + // We use this to avoid touching history in completeNavigation if a + // revalidation is entirely uninterrupted + let isUninterruptedRevalidation = false; + // Use this internal flag to force revalidation of all loaders: + // - submissions (completed or interrupted) + // - useRevalidator() + // - X-Remix-Revalidate (from redirect) + let isRevalidationRequired = false; + // Use this internal array to capture routes that require revalidation due + // to a cancelled deferred on action submission + let cancelledDeferredRoutes = []; + // Use this internal array to capture fetcher loads that were cancelled by an + // action navigation and require revalidation + let cancelledFetcherLoads = []; + // AbortControllers for any in-flight fetchers + let fetchControllers = new Map(); + // Track loads based on the order in which they started + let incrementingLoadId = 0; + // Track the outstanding pending navigation data load to be compared against + // the globally incrementing load when a fetcher load lands after a completed + // navigation + let pendingNavigationLoadId = -1; + // Fetchers that triggered data reloads as a result of their actions + let fetchReloadIds = new Map(); + // Fetchers that triggered redirect navigations + let fetchRedirectIds = new Set(); + // Most recent href/match for fetcher.load calls for fetchers + let fetchLoadMatches = new Map(); + // Ref-count mounted fetchers so we know when it's ok to clean them up + let activeFetchers = new Map(); + // Fetchers that have requested a delete when using v7_fetcherPersist, + // they'll be officially removed after they return to idle + let deletedFetchers = new Set(); + // Store DeferredData instances for active route matches. When a + // route loader returns defer() we stick one in here. Then, when a nested + // promise resolves we update loaderData. If a new navigation starts we + // cancel active deferreds for eliminated routes. + let activeDeferreds = new Map(); + // Store blocker functions in a separate Map outside of router state since + // we don't need to update UI state if they change + let blockerFunctions = new Map(); + // Flag to ignore the next history update, so we can revert the URL change on + // a POP navigation that was blocked by the user without touching router state + let ignoreNextHistoryUpdate = false; + // Initialize the router, all side effects should be kicked off from here. + // Implemented as a Fluent API for ease of: + // let router = createRouter(init).initialize(); + function initialize() { + // If history informs us of a POP navigation, start the navigation but do not update + // state. We'll update our own state once the navigation completes + unlistenHistory = init.history.listen(_ref => { + let { + action: historyAction, + location, + delta + } = _ref; + // Ignore this event if it was just us resetting the URL from a + // blocked POP navigation + if (ignoreNextHistoryUpdate) { + ignoreNextHistoryUpdate = false; + return; + } + warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location " + "that was not created by @remix-run/router. This will fail silently in " + "production. This can happen if you are navigating outside the router " + "via `window.history.pushState`/`window.location.hash` instead of using " + "router navigation APIs. This can also happen if you are using " + "createHashRouter and the user manually changes the URL."); + let blockerKey = shouldBlockNavigation({ + currentLocation: state.location, + nextLocation: location, + historyAction + }); + if (blockerKey && delta != null) { + // Restore the URL to match the current UI, but don't update router state + ignoreNextHistoryUpdate = true; + init.history.go(delta * -1); + // Put the blocker into a blocked state + updateBlocker(blockerKey, { + state: "blocked", + location, + proceed() { + updateBlocker(blockerKey, { + state: "proceeding", + proceed: undefined, + reset: undefined, + location + }); + // Re-do the same POP navigation we just blocked + init.history.go(delta); + }, + reset() { + let blockers = new Map(state.blockers); + blockers.set(blockerKey, IDLE_BLOCKER); + updateState({ + blockers + }); + } + }); + return; + } + return startNavigation(historyAction, location); + }); + if (isBrowser) { + // FIXME: This feels gross. How can we cleanup the lines between + // scrollRestoration/appliedTransitions persistance? + restoreAppliedTransitions(routerWindow, appliedViewTransitions); + let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions); + routerWindow.addEventListener("pagehide", _saveAppliedTransitions); + removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions); + } + // Kick off initial data load if needed. Use Pop to avoid modifying history + // Note we don't do any handling of lazy here. For SPA's it'll get handled + // in the normal navigation flow. For SSR it's expected that lazy modules are + // resolved prior to router creation since we can't go into a fallbackElement + // UI for SSR'd apps + if (!state.initialized) { + startNavigation(Action.Pop, state.location, { + initialHydration: true + }); + } + return router; + } + // Clean up a router and it's side effects + function dispose() { + if (unlistenHistory) { + unlistenHistory(); + } + if (removePageHideEventListener) { + removePageHideEventListener(); + } + subscribers.clear(); + pendingNavigationController && pendingNavigationController.abort(); + state.fetchers.forEach((_, key) => deleteFetcher(key)); + state.blockers.forEach((_, key) => deleteBlocker(key)); + } + // Subscribe to state updates for the router + function subscribe(fn) { + subscribers.add(fn); + return () => subscribers.delete(fn); + } + // Update our state and notify the calling context of the change + function updateState(newState, opts) { + if (opts === void 0) { + opts = {}; + } + state = _extends({}, state, newState); + // Prep fetcher cleanup so we can tell the UI which fetcher data entries + // can be removed + let completedFetchers = []; + let deletedFetchersKeys = []; + if (future.v7_fetcherPersist) { + state.fetchers.forEach((fetcher, key) => { + if (fetcher.state === "idle") { + if (deletedFetchers.has(key)) { + // Unmounted from the UI and can be totally removed + deletedFetchersKeys.push(key); + } else { + // Returned to idle but still mounted in the UI, so semi-remains for + // revalidations and such + completedFetchers.push(key); + } + } + }); + } + // Iterate over a local copy so that if flushSync is used and we end up + // removing and adding a new subscriber due to the useCallback dependencies, + // we don't get ourselves into a loop calling the new subscriber immediately + [...subscribers].forEach(subscriber => subscriber(state, { + deletedFetchers: deletedFetchersKeys, + unstable_viewTransitionOpts: opts.viewTransitionOpts, + unstable_flushSync: opts.flushSync === true + })); + // Remove idle fetchers from state since we only care about in-flight fetchers. + if (future.v7_fetcherPersist) { + completedFetchers.forEach(key => state.fetchers.delete(key)); + deletedFetchersKeys.forEach(key => deleteFetcher(key)); + } + } + // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION + // and setting state.[historyAction/location/matches] to the new route. + // - Location is a required param + // - Navigation will always be set to IDLE_NAVIGATION + // - Can pass any other state in newState + function completeNavigation(location, newState, _temp) { + var _location$state, _location$state2; + let { + flushSync + } = _temp === void 0 ? {} : _temp; + // Deduce if we're in a loading/actionReload state: + // - We have committed actionData in the store + // - The current navigation was a mutation submission + // - We're past the submitting state and into the loading state + // - The location being loaded is not the result of a redirect + let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true; + let actionData; + if (newState.actionData) { + if (Object.keys(newState.actionData).length > 0) { + actionData = newState.actionData; + } else { + // Empty actionData -> clear prior actionData due to an action error + actionData = null; + } + } else if (isActionReload) { + // Keep the current data if we're wrapping up the action reload + actionData = state.actionData; + } else { + // Clear actionData on any other completed navigations + actionData = null; + } + // Always preserve any existing loaderData from re-used routes + let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData; + // On a successful navigation we can assume we got through all blockers + // so we can start fresh + let blockers = state.blockers; + if (blockers.size > 0) { + blockers = new Map(blockers); + blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER)); + } + // Always respect the user flag. Otherwise don't reset on mutation + // submission navigations unless they redirect + let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true; + if (inFlightDataRoutes) { + dataRoutes = inFlightDataRoutes; + inFlightDataRoutes = undefined; + } + if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) { + init.history.push(location, location.state); + } else if (pendingAction === Action.Replace) { + init.history.replace(location, location.state); + } + let viewTransitionOpts; + // On POP, enable transitions if they were enabled on the original navigation + if (pendingAction === Action.Pop) { + // Forward takes precedence so they behave like the original navigation + let priorPaths = appliedViewTransitions.get(state.location.pathname); + if (priorPaths && priorPaths.has(location.pathname)) { + viewTransitionOpts = { + currentLocation: state.location, + nextLocation: location + }; + } else if (appliedViewTransitions.has(location.pathname)) { + // If we don't have a previous forward nav, assume we're popping back to + // the new location and enable if that location previously enabled + viewTransitionOpts = { + currentLocation: location, + nextLocation: state.location + }; + } + } else if (pendingViewTransitionEnabled) { + // Store the applied transition on PUSH/REPLACE + let toPaths = appliedViewTransitions.get(state.location.pathname); + if (toPaths) { + toPaths.add(location.pathname); + } else { + toPaths = new Set([location.pathname]); + appliedViewTransitions.set(state.location.pathname, toPaths); + } + viewTransitionOpts = { + currentLocation: state.location, + nextLocation: location + }; + } + updateState(_extends({}, newState, { + actionData, + loaderData, + historyAction: pendingAction, + location, + initialized: true, + navigation: IDLE_NAVIGATION, + revalidation: "idle", + restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches), + preventScrollReset, + blockers + }), { + viewTransitionOpts, + flushSync: flushSync === true + }); + // Reset stateful navigation vars + pendingAction = Action.Pop; + pendingPreventScrollReset = false; + pendingViewTransitionEnabled = false; + isUninterruptedRevalidation = false; + isRevalidationRequired = false; + cancelledDeferredRoutes = []; + 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 normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative); + let { + path, + submission, + error + } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts); + let currentLocation = state.location; + let nextLocation = createLocation(state.location, path, opts && opts.state); + // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded + // URL from window.location, so we need to encode it here so the behavior + // remains the same as POP and non-data-router usages. new URL() does all + // the same encoding we'd get from a history.pushState/window.location read + // without having to touch history + nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation)); + let userReplace = opts && opts.replace != null ? opts.replace : undefined; + let historyAction = Action.Push; + if (userReplace === true) { + historyAction = Action.Replace; + } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) { + // By default on submissions to the current location we REPLACE so that + // users don't have to double-click the back button to get to the prior + // location. If the user redirects to a different location from the + // action/loader this will be ignored and the redirect will be a PUSH + historyAction = Action.Replace; + } + let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined; + let flushSync = (opts && opts.unstable_flushSync) === true; + let blockerKey = shouldBlockNavigation({ + currentLocation, + nextLocation, + historyAction + }); + if (blockerKey) { + // Put the blocker into a blocked state + updateBlocker(blockerKey, { + state: "blocked", + location: nextLocation, + proceed() { + updateBlocker(blockerKey, { + state: "proceeding", + proceed: undefined, + reset: undefined, + location: nextLocation + }); + // Send the same navigation through + navigate(to, opts); + }, + reset() { + let blockers = new Map(state.blockers); + blockers.set(blockerKey, IDLE_BLOCKER); + updateState({ + blockers + }); + } + }); + return; + } + return await startNavigation(historyAction, nextLocation, { + submission, + // Send through the formData serialization error if we have one so we can + // render at the right error boundary after we match routes + pendingError: error, + preventScrollReset, + replace: opts && opts.replace, + enableViewTransition: opts && opts.unstable_viewTransition, + flushSync + }); + } + // Revalidate all current loaders. If a navigation is in progress or if this + // is interrupted by a navigation, allow this to "succeed" by calling all + // loaders during the next loader round + function revalidate() { + interruptActiveLoads(); + updateState({ + revalidation: "loading" + }); + // If we're currently submitting an action, we don't need to start a new + // navigation, we'll just let the follow up loader execution call all loaders + if (state.navigation.state === "submitting") { + return; + } + // If we're currently in an idle state, start a new navigation for the current + // action/location and mark it as uninterrupted, which will skip the history + // update in completeNavigation + if (state.navigation.state === "idle") { + startNavigation(state.historyAction, state.location, { + startUninterruptedRevalidation: true + }); + return; + } + // Otherwise, if we're currently in a loading state, just start a new + // navigation to the navigation.location but do not trigger an uninterrupted + // revalidation so that history correctly updates once the navigation completes + startNavigation(pendingAction || state.historyAction, state.navigation.location, { + overrideNavigation: state.navigation + }); + } + // Start a navigation to the given action/location. Can optionally provide a + // overrideNavigation which will override the normalLoad in the case of a redirect + // navigation + async function startNavigation(historyAction, location, opts) { + // Abort any in-progress navigations and start a new one. Unset any ongoing + // uninterrupted revalidations unless told otherwise, since we want this + // new navigation to update history normally + pendingNavigationController && pendingNavigationController.abort(); + pendingNavigationController = null; + pendingAction = historyAction; + isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; + // Save the current scroll position every time we start a new navigation, + // and track whether we should reset scroll on completion + saveScrollPosition(state.location, state.matches); + pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; + pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true; + let routesToUse = inFlightDataRoutes || dataRoutes; + let loadingNavigation = opts && opts.overrideNavigation; + let matches = matchRoutes(routesToUse, location, basename); + let flushSync = (opts && opts.flushSync) === true; + // Short circuit with a 404 on the root error boundary if we match nothing + if (!matches) { + let error = getInternalRouterError(404, { + pathname: location.pathname + }); + let { + matches: notFoundMatches, + route + } = getShortCircuitMatches(routesToUse); + // Cancel all pending deferred on 404s since we don't keep any routes + cancelActiveDeferreds(); + completeNavigation(location, { + matches: notFoundMatches, + loaderData: {}, + errors: { + [route.id]: error + } + }, { + flushSync + }); + return; + } + // Short circuit if it's only a hash change and not a revalidation or + // mutation submission. + // + // Ignore on initial page loads because since the initial load will always + // be "same hash". For example, on /page#hash and submit a + // which will default to a navigation to /page + if (state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) { + completeNavigation(location, { + matches + }, { + flushSync + }); + return; + } + // Create a controller/Request for this navigation + pendingNavigationController = new AbortController(); + let request = createClientSideRequest(init.history, 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 && isMutationMethod(opts.submission.formMethod)) { + // Call action if we received an action submission + let actionOutput = await handleAction(request, location, opts.submission, matches, { + replace: opts.replace, + flushSync + }); + if (actionOutput.shortCircuited) { + return; + } + pendingActionData = actionOutput.pendingActionData; + pendingError = actionOutput.pendingActionError; + loadingNavigation = getLoadingNavigation(location, opts.submission); + flushSync = false; + // Create a GET request for the loaders + request = new Request(request.url, { + signal: request.signal + }); + } + // Call loaders + let { + shortCircuited, + loaderData, + errors + } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionData, pendingError); + if (shortCircuited) { + return; + } + // Clean up now that the action/loaders have completed. Don't clean up if + // we short circuited because pendingNavigationController will have already + // been assigned to a new controller for the next navigation + pendingNavigationController = null; + completeNavigation(location, _extends({ + matches + }, pendingActionData ? { + actionData: pendingActionData + } : {}, { + 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) { + if (opts === void 0) { + opts = {}; + } + interruptActiveLoads(); + // Put us in a submitting state + let navigation = getSubmittingNavigation(location, submission); + updateState({ + navigation + }, { + flushSync: opts.flushSync === true + }); + // Call our action and get the result + let result; + let actionMatch = getTargetMatch(matches, location); + if (!actionMatch.route.action && !actionMatch.route.lazy) { + result = { + type: ResultType.error, + error: getInternalRouterError(405, { + method: request.method, + pathname: location.pathname, + routeId: actionMatch.route.id + }) + }; + } else { + result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); + if (request.signal.aborted) { + return { + shortCircuited: true + }; + } + } + if (isRedirectResult(result)) { + let replace; + if (opts && opts.replace != null) { + replace = opts.replace; + } else { + // If the user didn't explicity indicate replace behavior, replace if + // we redirected to the exact same location we're currently at to avoid + // double back-buttons + replace = result.location === state.location.pathname + state.location.search; + } + await startRedirectNavigation(state, result, { + submission, + 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 { + // Send back an empty object we can use to clear out any prior actionData + pendingActionData: {}, + pendingActionError: { + [boundaryMatch.route.id]: result.error + } + }; + } + if (isDeferredResult(result)) { + throw getInternalRouterError(400, { + type: "defer-action" + }); + } + return { + pendingActionData: { + [actionMatch.route.id]: result.data + } + }; + } + // Call all applicable loaders for the given matches, handling redirects, + // errors, etc. + async function handleLoaders(request, location, matches, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionData, pendingError) { + // Figure out the right navigation we want to use for data loading + let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission); + // If this was a redirect from an action we don't have a "submission" but + // we have it on the loading navigation so use that if available + let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation); + let routesToUse = inFlightDataRoutes || dataRoutes; + let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError); + // Cancel pending deferreds for no-longer-matched routes or routes we're + // about to reload. Note that if this is an action reload we would have + // already cancelled all pending deferreds so this would be a no-op + cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); + pendingNavigationLoadId = ++incrementingLoadId; + // Short circuit if we have no loaders to run + if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) { + let updatedFetchers = markFetchRedirectsDone(); + completeNavigation(location, _extends({ + matches, + loaderData: {}, + // Commit pending error if we're short circuiting + errors: pendingError || null + }, pendingActionData ? { + actionData: pendingActionData + } : {}, updatedFetchers ? { + fetchers: new Map(state.fetchers) + } : {}), { + flushSync + }); + 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 we have partialHydration enabled, then don't update the state for the + // initial data load since iot's not a "navigation" + if (!isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration)) { + revalidatingFetchers.forEach(rf => { + let fetcher = state.fetchers.get(rf.key); + let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined); + state.fetchers.set(rf.key, revalidatingFetcher); + }); + let actionData = pendingActionData || state.actionData; + updateState(_extends({ + navigation: loadingNavigation + }, actionData ? Object.keys(actionData).length === 0 ? { + actionData: null + } : { + actionData + } : {}, revalidatingFetchers.length > 0 ? { + fetchers: new Map(state.fetchers) + } : {}), { + flushSync + }); + } + revalidatingFetchers.forEach(rf => { + if (fetchControllers.has(rf.key)) { + abortFetcher(rf.key); + } + if (rf.controller) { + // Fetchers use an independent AbortController so that aborting a fetcher + // (via deleteFetcher) does not abort the triggering navigation that + // triggered the revalidation + fetchControllers.set(rf.key, rf.controller); + } + }); + // Proxy navigation abort through to revalidation fetchers + let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key)); + if (pendingNavigationController) { + pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations); + } + let { + results, + loaderResults, + fetcherResults + } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request); + if (request.signal.aborted) { + return { + shortCircuited: true + }; + } + // Clean up _after_ loaders have completed. Don't clean up if we short + // circuited because fetchControllers would have been aborted and + // reassigned to new controllers for the next navigation + if (pendingNavigationController) { + pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations); + } + revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key)); + // If any loaders returned a redirect Response, start a new REPLACE navigation + let redirect = findRedirect(results); + if (redirect) { + if (redirect.idx >= matchesToLoad.length) { + // If this redirect came from a fetcher make sure we mark it in + // fetchRedirectIds so it doesn't get revalidated on the next set of + // loader executions + let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; + fetchRedirectIds.add(fetcherKey); + } + await startRedirectNavigation(state, redirect.result, { + 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); + } + }); + }); + let updatedFetchers = markFetchRedirectsDone(); + let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); + let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0; + return _extends({ + loaderData, + errors + }, shouldUpdateFetchers ? { + fetchers: new Map(state.fetchers) + } : {}); + } + // Trigger a fetcher load/submit for the given fetcher key + function fetch(key, routeId, href, opts) { + if (isServer) { + throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback."); + } + if (fetchControllers.has(key)) abortFetcher(key); + let flushSync = (opts && opts.unstable_flushSync) === true; + let routesToUse = inFlightDataRoutes || dataRoutes; + let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative); + let matches = matchRoutes(routesToUse, normalizedPath, basename); + if (!matches) { + setFetcherError(key, routeId, getInternalRouterError(404, { + pathname: normalizedPath + }), { + flushSync + }); + return; + } + let { + path, + submission, + error + } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts); + if (error) { + setFetcherError(key, routeId, error, { + flushSync + }); + return; + } + let match = getTargetMatch(matches, path); + pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; + if (submission && isMutationMethod(submission.formMethod)) { + handleFetcherAction(key, routeId, path, match, matches, flushSync, submission); + return; + } + // Store off the match so we can call it's shouldRevalidate on subsequent + // revalidations + fetchLoadMatches.set(key, { + routeId, + path + }); + handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission); + } + // Call the action for the matched fetcher.submit(), and then handle redirects, + // errors, and revalidation + async function handleFetcherAction(key, routeId, path, match, requestMatches, flushSync, submission) { + interruptActiveLoads(); + fetchLoadMatches.delete(key); + if (!match.route.action && !match.route.lazy) { + let error = getInternalRouterError(405, { + method: submission.formMethod, + pathname: path, + routeId: routeId + }); + setFetcherError(key, routeId, error, { + flushSync + }); + return; + } + // Put this fetcher into it's submitting state + let existingFetcher = state.fetchers.get(key); + updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), { + flushSync + }); + // Call the action for the fetcher + let abortController = new AbortController(); + let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission); + fetchControllers.set(key, abortController); + let originatingLoadId = incrementingLoadId; + let actionResult = await callLoaderOrAction("action", fetchRequest, match, requestMatches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); + if (fetchRequest.signal.aborted) { + // We can delete this so long as we weren't aborted by our own fetcher + // re-submit which would have put _new_ controller is in fetchControllers + if (fetchControllers.get(key) === abortController) { + fetchControllers.delete(key); + } + return; + } + // When using v7_fetcherPersist, we don't want errors bubbling up to the UI + // or redirects processed for unmounted fetchers so we just revert them to + // idle + if (future.v7_fetcherPersist && deletedFetchers.has(key)) { + if (isRedirectResult(actionResult) || isErrorResult(actionResult)) { + updateFetcherState(key, getDoneFetcher(undefined)); + return; + } + // Let SuccessResult's fall through for revalidation + } else { + if (isRedirectResult(actionResult)) { + fetchControllers.delete(key); + if (pendingNavigationLoadId > originatingLoadId) { + // A new navigation was kicked off after our action started, so that + // should take precedence over this redirect navigation. We already + // set isRevalidationRequired so all loaders for the new route should + // fire unless opted out via shouldRevalidate + updateFetcherState(key, getDoneFetcher(undefined)); + return; + } else { + fetchRedirectIds.add(key); + updateFetcherState(key, getLoadingFetcher(submission)); + return startRedirectNavigation(state, actionResult, { + fetcherSubmission: submission + }); + } + } + // Process any non-redirect errors thrown + if (isErrorResult(actionResult)) { + setFetcherError(key, routeId, actionResult.error); + return; + } + } + if (isDeferredResult(actionResult)) { + throw getInternalRouterError(400, { + type: "defer-action" + }); + } + // Start the data load for current matches, or the next location if we're + // in the middle of a navigation + let nextLocation = state.navigation.location || state.location; + let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal); + let routesToUse = inFlightDataRoutes || dataRoutes; + let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches; + invariant(matches, "Didn't find any matches after fetcher action"); + let loadId = ++incrementingLoadId; + fetchReloadIds.set(key, loadId); + let loadFetcher = getLoadingFetcher(submission, actionResult.data); + state.fetchers.set(key, loadFetcher); + let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, { + [match.route.id]: actionResult.data + }, undefined // No need to send through errors since we short circuit above + ); + // Put all revalidating fetchers into the loading state, except for the + // current fetcher which we want to keep in it's current loading state which + // contains it's action submission info + action data + revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => { + let staleKey = rf.key; + let existingFetcher = state.fetchers.get(staleKey); + let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined); + state.fetchers.set(staleKey, revalidatingFetcher); + if (fetchControllers.has(staleKey)) { + abortFetcher(staleKey); + } + if (rf.controller) { + fetchControllers.set(staleKey, rf.controller); + } + }); + updateState({ + fetchers: new Map(state.fetchers) + }); + let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key)); + abortController.signal.addEventListener("abort", abortPendingFetchRevalidations); + let { + results, + loaderResults, + fetcherResults + } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest); + if (abortController.signal.aborted) { + return; + } + abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations); + fetchReloadIds.delete(key); + fetchControllers.delete(key); + revalidatingFetchers.forEach(r => fetchControllers.delete(r.key)); + let redirect = findRedirect(results); + if (redirect) { + if (redirect.idx >= matchesToLoad.length) { + // If this redirect came from a fetcher make sure we mark it in + // fetchRedirectIds so it doesn't get revalidated on the next set of + // loader executions + let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; + fetchRedirectIds.add(fetcherKey); + } + return startRedirectNavigation(state, redirect.result); + } + // Process and commit output from loaders + let { + loaderData, + errors + } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds); + // Since we let revalidations complete even if the submitting fetcher was + // deleted, only put it back to idle if it hasn't been deleted + if (state.fetchers.has(key)) { + let doneFetcher = getDoneFetcher(actionResult.data); + state.fetchers.set(key, doneFetcher); + } + abortStaleFetchLoads(loadId); + // If we are currently in a navigation loading state and this fetcher is + // more recent than the navigation, we want the newer data so abort the + // navigation and complete it with the fetcher data + if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) { + invariant(pendingAction, "Expected pending action"); + pendingNavigationController && pendingNavigationController.abort(); + completeNavigation(state.navigation.location, { + matches, + loaderData, + errors, + fetchers: new Map(state.fetchers) + }); + } else { + // otherwise just update with the fetcher data, preserving any existing + // loaderData for loaders that did not need to reload. We have to + // manually merge here since we aren't going through completeNavigation + updateState({ + errors, + loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors), + fetchers: new Map(state.fetchers) + }); + isRevalidationRequired = false; + } + } + // Call the matched loader for fetcher.load(), handling redirects, errors, etc. + async function handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission) { + let existingFetcher = state.fetchers.get(key); + updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), { + flushSync + }); + // Call the loader for this fetcher route match + let abortController = new AbortController(); + let fetchRequest = createClientSideRequest(init.history, path, abortController.signal); + fetchControllers.set(key, abortController); + let originatingLoadId = incrementingLoadId; + let result = await callLoaderOrAction("loader", fetchRequest, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); + // Deferred isn't supported for fetcher loads, await everything and treat it + // as a normal load. resolveDeferredData will return undefined if this + // fetcher gets aborted, so we just leave result untouched and short circuit + // below if that happens + if (isDeferredResult(result)) { + result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result; + } + // We can delete this so long as we weren't aborted by our our own fetcher + // re-load which would have put _new_ controller is in fetchControllers + if (fetchControllers.get(key) === abortController) { + fetchControllers.delete(key); + } + if (fetchRequest.signal.aborted) { + return; + } + // We don't want errors bubbling up or redirects followed for unmounted + // fetchers, so short circuit here if it was removed from the UI + if (deletedFetchers.has(key)) { + updateFetcherState(key, getDoneFetcher(undefined)); + return; + } + // If the loader threw a redirect Response, start a new REPLACE navigation + if (isRedirectResult(result)) { + if (pendingNavigationLoadId > originatingLoadId) { + // A new navigation was kicked off after our loader started, so that + // should take precedence over this redirect navigation + updateFetcherState(key, getDoneFetcher(undefined)); + return; + } else { + fetchRedirectIds.add(key); + await startRedirectNavigation(state, result); + return; + } + } + // Process any non-redirect errors thrown + if (isErrorResult(result)) { + setFetcherError(key, routeId, result.error); + return; + } + invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); + // Put the fetcher back into an idle state + updateFetcherState(key, getDoneFetcher(result.data)); + } + /** + * Utility function to handle redirects returned from an action or loader. + * Normally, a redirect "replaces" the navigation that triggered it. So, for + * example: + * + * - user is on /a + * - user clicks a link to /b + * - loader for /b redirects to /c + * + * In a non-JS app the browser would track the in-flight navigation to /b and + * then replace it with /c when it encountered the redirect response. In + * the end it would only ever update the URL bar with /c. + * + * In client-side routing using pushState/replaceState, we aim to emulate + * this behavior and we also do not update history until the end of the + * navigation (including processed redirects). This means that we never + * actually touch history until we've processed redirects, so we just use + * the history action from the original navigation (PUSH or REPLACE). + */ + async function startRedirectNavigation(state, redirect, _temp2) { + let { + submission, + fetcherSubmission, + replace + } = _temp2 === void 0 ? {} : _temp2; + if (redirect.revalidate) { + isRevalidationRequired = true; + } + let redirectLocation = createLocation(state.location, redirect.location, { + _isRedirect: true + }); + invariant(redirectLocation, "Expected a location on the redirect navigation"); + if (isBrowser) { + let isDocumentReload = false; + if (redirect.reloadDocument) { + // Hard reload if the response contained X-Remix-Reload-Document + isDocumentReload = true; + } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) { + const url = init.history.createURL(redirect.location); + isDocumentReload = + // Hard reload if it's an absolute URL to a new origin + url.origin !== routerWindow.location.origin || + // Hard reload if it's an absolute URL that does not match our basename + stripBasename(url.pathname, basename) == null; + } + if (isDocumentReload) { + if (replace) { + routerWindow.location.replace(redirect.location); + } else { + routerWindow.location.assign(redirect.location); + } + return; + } + } + // There's no need to abort on redirects, since we don't detect the + // redirect until the action/loaders have settled + pendingNavigationController = null; + let redirectHistoryAction = replace === true ? Action.Replace : Action.Push; + // Use the incoming submission if provided, fallback on the active one in + // state.navigation + let { + formMethod, + formAction, + formEncType + } = state.navigation; + if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) { + submission = getSubmissionFromNavigation(state.navigation); + } + // If this was a 307/308 submission we want to preserve the HTTP method and + // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the + // redirected location + let activeSubmission = submission || fetcherSubmission; + if (redirectPreserveMethodStatusCodes.has(redirect.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) { + await startNavigation(redirectHistoryAction, redirectLocation, { + submission: _extends({}, activeSubmission, { + formAction: redirect.location + }), + // Preserve this flag across redirects + preventScrollReset: pendingPreventScrollReset + }); + } else { + // If we have a navigation submission, we will preserve it through the + // redirect navigation + let overrideNavigation = getLoadingNavigation(redirectLocation, submission); + await startNavigation(redirectHistoryAction, redirectLocation, { + overrideNavigation, + // Send fetcher submissions through for shouldRevalidate + fetcherSubmission, + // Preserve this flag across redirects + preventScrollReset: pendingPreventScrollReset + }); + } + } + async function callLoadersAndMaybeResolveData(currentMatches, matches, 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(match => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath)), ...fetchersToLoad.map(f => { + if (f.matches && f.match && f.controller) { + return callLoaderOrAction("loader", createClientSideRequest(init.history, f.path, f.controller.signal), f.match, f.matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); + } else { + let error = { + type: ResultType.error, + error: getInternalRouterError(404, { + pathname: f.path + }) + }; + return error; + } + })]); + let loaderResults = results.slice(0, matchesToLoad.length); + let fetcherResults = results.slice(matchesToLoad.length); + await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, loaderResults.map(() => request.signal), false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(f => f.match), fetcherResults, fetchersToLoad.map(f => f.controller ? f.controller.signal : null), 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 updateFetcherState(key, fetcher, opts) { + if (opts === void 0) { + opts = {}; + } + state.fetchers.set(key, fetcher); + updateState({ + fetchers: new Map(state.fetchers) + }, { + flushSync: (opts && opts.flushSync) === true + }); + } + function setFetcherError(key, routeId, error, opts) { + if (opts === void 0) { + opts = {}; + } + let boundaryMatch = findNearestBoundary(state.matches, routeId); + deleteFetcher(key); + updateState({ + errors: { + [boundaryMatch.route.id]: error + }, + fetchers: new Map(state.fetchers) + }, { + flushSync: (opts && opts.flushSync) === true + }); + } + function getFetcher(key) { + if (future.v7_fetcherPersist) { + activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1); + // If this fetcher was previously marked for deletion, unmark it since we + // have a new instance + if (deletedFetchers.has(key)) { + deletedFetchers.delete(key); + } + } + return state.fetchers.get(key) || IDLE_FETCHER; + } + function deleteFetcher(key) { + let fetcher = state.fetchers.get(key); + // Don't abort the controller if this is a deletion of a fetcher.submit() + // in it's loading phase since - we don't want to abort the corresponding + // revalidation and want them to complete and land + if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) { + abortFetcher(key); + } + fetchLoadMatches.delete(key); + fetchReloadIds.delete(key); + fetchRedirectIds.delete(key); + deletedFetchers.delete(key); + state.fetchers.delete(key); + } + function deleteFetcherAndUpdateState(key) { + if (future.v7_fetcherPersist) { + let count = (activeFetchers.get(key) || 0) - 1; + if (count <= 0) { + activeFetchers.delete(key); + deletedFetchers.add(key); + } else { + activeFetchers.set(key, count); + } + } else { + deleteFetcher(key); + } + updateState({ + fetchers: new Map(state.fetchers) + }); + } + function abortFetcher(key) { + let controller = fetchControllers.get(key); + invariant(controller, "Expected fetch controller: " + key); + controller.abort(); + fetchControllers.delete(key); + } + function markFetchersDone(keys) { + for (let key of keys) { + let fetcher = getFetcher(key); + let doneFetcher = getDoneFetcher(fetcher.data); + state.fetchers.set(key, doneFetcher); + } + } + function markFetchRedirectsDone() { + let doneKeys = []; + let updatedFetchers = false; + for (let key of fetchRedirectIds) { + let fetcher = state.fetchers.get(key); + invariant(fetcher, "Expected fetcher: " + key); + if (fetcher.state === "loading") { + fetchRedirectIds.delete(key); + doneKeys.push(key); + updatedFetchers = true; + } + } + markFetchersDone(doneKeys); + return updatedFetchers; + } + function abortStaleFetchLoads(landedId) { + let yeetedKeys = []; + for (let [key, id] of fetchReloadIds) { + if (id < landedId) { + let fetcher = state.fetchers.get(key); + invariant(fetcher, "Expected fetcher: " + key); + if (fetcher.state === "loading") { + abortFetcher(key); + fetchReloadIds.delete(key); + yeetedKeys.push(key); + } + } + } + markFetchersDone(yeetedKeys); + return yeetedKeys.length > 0; + } + function getBlocker(key, fn) { + let blocker = state.blockers.get(key) || IDLE_BLOCKER; + if (blockerFunctions.get(key) !== fn) { + blockerFunctions.set(key, fn); + } + return blocker; + } + function deleteBlocker(key) { + state.blockers.delete(key); + blockerFunctions.delete(key); + } + // Utility function to update blockers, ensuring valid state transitions + function updateBlocker(key, newBlocker) { + let blocker = state.blockers.get(key) || IDLE_BLOCKER; + // Poor mans state machine :) + // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM + invariant(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state); + let blockers = new Map(state.blockers); + blockers.set(key, newBlocker); + updateState({ + blockers + }); + } + function shouldBlockNavigation(_ref2) { + let { + currentLocation, + nextLocation, + historyAction + } = _ref2; + if (blockerFunctions.size === 0) { + return; + } + // We ony support a single active blocker at the moment since we don't have + // any compelling use cases for multi-blocker yet + if (blockerFunctions.size > 1) { + warning(false, "A router only supports one blocker at a time"); + } + let entries = Array.from(blockerFunctions.entries()); + let [blockerKey, blockerFunction] = entries[entries.length - 1]; + let blocker = state.blockers.get(blockerKey); + if (blocker && blocker.state === "proceeding") { + // If the blocker is currently proceeding, we don't need to re-check + // it and can let this navigation continue + return; + } + // At this point, we know we're unblocked/blocked so we need to check the + // user-provided blocker function + if (blockerFunction({ + currentLocation, + nextLocation, + historyAction + })) { + return blockerKey; + } + } + function 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 || null; + // 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 getScrollKey(location, matches) { + if (getScrollRestorationKey) { + let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData))); + return key || location.key; + } + return location.key; + } + function saveScrollPosition(location, matches) { + if (savedScrollPositions && getScrollPosition) { + let key = getScrollKey(location, matches); + savedScrollPositions[key] = getScrollPosition(); + } + } + function getSavedScrollPosition(location, matches) { + if (savedScrollPositions) { + let key = getScrollKey(location, matches); + let y = savedScrollPositions[key]; + if (typeof y === "number") { + return y; + } + } + return null; + } + function _internalSetRoutes(newRoutes) { + manifest = {}; + inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest); + } + router = { + get basename() { + return basename; + }, + get future() { + return future; + }, + get state() { + return state; + }, + get routes() { + return dataRoutes; + }, + get window() { + return routerWindow; + }, + initialize, + subscribe, + enableScrollRestoration, + navigate, + fetch, + revalidate, + // Passthrough to history-aware createHref used by useHref so we get proper + // hash-aware URLs in DOM paths + createHref: to => init.history.createHref(to), + encodeLocation: to => init.history.encodeLocation(to), + getFetcher, + deleteFetcher: deleteFetcherAndUpdateState, + dispose, + getBlocker, + deleteBlocker, + _internalFetchControllers: fetchControllers, + _internalActiveDeferreds: activeDeferreds, + // TODO: Remove setRoutes, it's temporary to avoid dealing with + // updating the tree while validating the update algorithm. + _internalSetRoutes + }; + return router; +} +//#endregion +//////////////////////////////////////////////////////////////////////////////// +//#region createStaticHandler +//////////////////////////////////////////////////////////////////////////////// +const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred"); +function createStaticHandler(routes, opts) { + invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler"); + let manifest = {}; + let basename = (opts ? opts.basename : null) || "/"; + let mapRouteProperties; + if (opts != null && opts.mapRouteProperties) { + mapRouteProperties = opts.mapRouteProperties; + } else if (opts != null && opts.detectErrorBoundary) { + // If they are still using the deprecated version, wrap it with the new API + let detectErrorBoundary = opts.detectErrorBoundary; + mapRouteProperties = route => ({ + hasErrorBoundary: detectErrorBoundary(route) + }); + } else { + mapRouteProperties = defaultMapRouteProperties; + } + // Config driven behavior flags + let future = _extends({ + v7_relativeSplatPath: false + }, opts ? opts.future : null); + let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest); + /** + * The query() method is intended for document requests, in which we want to + * call an optional action and potentially multiple loaders for all nested + * routes. It returns a StaticHandlerContext object, which is very similar + * to the router state (location, loaderData, actionData, errors, etc.) and + * also adds SSR-specific information such as the statusCode and headers + * from action/loaders Responses. + * + * It _should_ never throw and should report all errors through the + * returned context.errors object, properly associating errors to their error + * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be + * used to emulate React error boundaries during SSr by performing a second + * pass only down to the boundaryId. + * + * The one exception where we do not return a StaticHandlerContext is when a + * redirect response is returned or thrown from any action/loader. We + * propagate that out and return the raw Response so the HTTP server can + * return it directly. + */ + async function query(request, _temp3) { + let { + requestContext + } = _temp3 === void 0 ? {} : _temp3; + let url = new URL(request.url); + let method = request.method; + let location = createLocation("", createPath(url), null, "default"); + let matches = matchRoutes(dataRoutes, location, basename); + // SSR supports HEAD requests while SPA doesn't + if (!isValidMethod(method) && method !== "HEAD") { + let error = getInternalRouterError(405, { + method + }); + let { + matches: methodNotAllowedMatches, + route + } = getShortCircuitMatches(dataRoutes); + return { + basename, + location, + matches: methodNotAllowedMatches, + loaderData: {}, + actionData: null, + errors: { + [route.id]: error + }, + statusCode: error.status, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } else if (!matches) { + let error = getInternalRouterError(404, { + pathname: location.pathname + }); + let { + matches: notFoundMatches, + route + } = getShortCircuitMatches(dataRoutes); + return { + basename, + location, + matches: notFoundMatches, + loaderData: {}, + actionData: null, + errors: { + [route.id]: error + }, + statusCode: error.status, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } + let result = await queryImpl(request, location, matches, requestContext); + if (isResponse(result)) { + return result; + } + // When returning StaticHandlerContext, we patch back in the location here + // since we need it for React Context. But this helps keep our submit and + // loadRouteData operating on a Request instead of a Location + return _extends({ + location, + basename + }, result); + } + /** + * The queryRoute() method is intended for targeted route requests, either + * for fetch ?_data requests or resource route requests. In this case, we + * are only ever calling a single action or loader, and we are returning the + * returned value directly. In most cases, this will be a Response returned + * from the action/loader, but it may be a primitive or other value as well - + * and in such cases the calling context should handle that accordingly. + * + * We do respect the throw/return differentiation, so if an action/loader + * throws, then this method will throw the value. This is important so we + * can do proper boundary identification in Remix where a thrown Response + * must go to the Catch Boundary but a returned Response is happy-path. + * + * One thing to note is that any Router-initiated Errors that make sense + * to associate with a status code will be thrown as an ErrorResponse + * instance which include the raw Error, such that the calling context can + * serialize the error as they see fit while including the proper response + * code. Examples here are 404 and 405 errors that occur prior to reaching + * any user-defined loaders. + */ + async function queryRoute(request, _temp4) { + let { + routeId, + requestContext + } = _temp4 === void 0 ? {} : _temp4; + let url = new URL(request.url); + let method = request.method; + let location = createLocation("", createPath(url), null, "default"); + let matches = matchRoutes(dataRoutes, location, basename); + // SSR supports HEAD requests while SPA doesn't + if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") { + throw getInternalRouterError(405, { + method + }); + } else if (!matches) { + throw getInternalRouterError(404, { + pathname: location.pathname + }); + } + let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location); + if (routeId && !match) { + throw getInternalRouterError(403, { + pathname: location.pathname, + routeId + }); + } else if (!match) { + // This should never hit I don't think? + throw getInternalRouterError(404, { + pathname: location.pathname + }); + } + let result = await queryImpl(request, location, matches, requestContext, match); + if (isResponse(result)) { + return result; + } + let error = result.errors ? Object.values(result.errors)[0] : undefined; + if (error !== undefined) { + // If we got back result.errors, that means the loader/action threw + // _something_ that wasn't a Response, but it's not guaranteed/required + // to be an `instanceof Error` either, so we have to use throw here to + // preserve the "error" state outside of queryImpl. + throw error; + } + // Pick off the right state value to return + if (result.actionData) { + return Object.values(result.actionData)[0]; + } + if (result.loaderData) { + var _result$activeDeferre; + let data = Object.values(result.loaderData)[0]; + if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) { + data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id]; + } + return data; + } + return undefined; + } + async function queryImpl(request, location, matches, requestContext, routeMatch) { + invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal"); + try { + if (isMutationMethod(request.method.toLowerCase())) { + let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, routeMatch != null); + return result; + } + let result = await loadRouteData(request, matches, requestContext, routeMatch); + return isResponse(result) ? result : _extends({}, result, { + actionData: null, + actionHeaders: {} + }); + } catch (e) { + // If the user threw/returned a Response in callLoaderOrAction, we throw + // it to bail out and then return or throw here based on whether the user + // returned or threw + if (isQueryRouteResponse(e)) { + if (e.type === ResultType.error) { + throw e.response; + } + return e.response; + } + // Redirects are always returned since they don't propagate to catch + // boundaries + if (isRedirectResponse(e)) { + return e; + } + throw e; + } + } + async function submit(request, matches, actionMatch, requestContext, isRouteRequest) { + let result; + if (!actionMatch.route.action && !actionMatch.route.lazy) { + let error = getInternalRouterError(405, { + method: request.method, + pathname: new URL(request.url).pathname, + routeId: actionMatch.route.id + }); + if (isRouteRequest) { + throw error; + } + result = { + type: ResultType.error, + error + }; + } else { + result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath, { + isStaticRequest: true, + isRouteRequest, + requestContext + }); + if (request.signal.aborted) { + let method = isRouteRequest ? "queryRoute" : "query"; + throw new Error(method + "() call aborted: " + request.method + " " + request.url); + } + } + if (isRedirectResult(result)) { + // Uhhhh - this should never happen, we should always throw these from + // callLoaderOrAction, but the type narrowing here keeps TS happy and we + // can get back on the "throw all redirect responses" train here should + // this ever happen :/ + throw new Response(null, { + status: result.status, + headers: { + Location: result.location + } + }); + } + if (isDeferredResult(result)) { + let error = getInternalRouterError(400, { + type: "defer-action" + }); + if (isRouteRequest) { + throw error; + } + result = { + type: ResultType.error, + error + }; + } + if (isRouteRequest) { + // Note: This should only be non-Response values if we get here, since + // isRouteRequest should throw any Response received in callLoaderOrAction + if (isErrorResult(result)) { + throw result.error; + } + return { + matches: [actionMatch], + loaderData: {}, + actionData: { + [actionMatch.route.id]: result.data + }, + errors: null, + // Note: statusCode + headers are unused here since queryRoute will + // return the raw Response or value + statusCode: 200, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } + 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, requestContext, undefined, { + [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 + } : {}) + }); + } + // Create a GET request for the loaders + let loaderRequest = new Request(request.url, { + headers: request.headers, + redirect: request.redirect, + signal: request.signal + }); + let context = await loadRouteData(loaderRequest, matches, requestContext); + return _extends({}, context, result.statusCode ? { + statusCode: result.statusCode + } : {}, { + actionData: { + [actionMatch.route.id]: result.data + }, + actionHeaders: _extends({}, result.headers ? { + [actionMatch.route.id]: result.headers + } : {}) + }); + } + async function loadRouteData(request, matches, requestContext, routeMatch, pendingActionError) { + let isRouteRequest = routeMatch != null; + // Short circuit if we have no loaders to run (queryRoute()) + if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) { + throw getInternalRouterError(400, { + method: request.method, + pathname: new URL(request.url).pathname, + routeId: routeMatch == null ? void 0 : routeMatch.route.id + }); + } + let requestMatches = routeMatch ? [routeMatch] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]); + let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy); + // Short circuit if we have no loaders to run (query()) + if (matchesToLoad.length === 0) { + return { + matches, + // Add a null for all matched routes for proper revalidation on the client + loaderData: matches.reduce((acc, m) => Object.assign(acc, { + [m.route.id]: null + }), {}), + errors: pendingActionError || null, + statusCode: 200, + loaderHeaders: {}, + activeDeferreds: null + }; + } + let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath, { + isStaticRequest: true, + isRouteRequest, + requestContext + }))]); + if (request.signal.aborted) { + let method = isRouteRequest ? "queryRoute" : "query"; + throw new Error(method + "() call aborted: " + request.method + " " + request.url); + } + // Process and commit output from loaders + let activeDeferreds = new Map(); + let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError, activeDeferreds); + // Add a null for any non-loader matches for proper revalidation on the client + let executedLoaders = new Set(matchesToLoad.map(match => match.route.id)); + matches.forEach(match => { + if (!executedLoaders.has(match.route.id)) { + context.loaderData[match.route.id] = null; + } + }); + return _extends({}, context, { + matches, + activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null + }); + } + 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; +} +function isSubmissionNavigation(opts) { + return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== undefined); +} +function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) { + let contextualMatches; + let activeRouteMatch; + if (fromRouteId) { + // Grab matches up to the calling route so our route-relative logic is + // relative to the correct source route + contextualMatches = []; + for (let match of matches) { + contextualMatches.push(match); + if (match.route.id === fromRouteId) { + activeRouteMatch = match; + break; + } + } + } else { + contextualMatches = matches; + activeRouteMatch = matches[matches.length - 1]; + } + // Resolve the relative path + let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path"); + // When `to` is not specified we inherit search/hash from the current + // location, unlike when to="." and we just inherit the path. + // See https://github.com/remix-run/remix/issues/927 + if (to == null) { + path.search = location.search; + path.hash = location.hash; + } + // Add an ?index param for matched index routes if we don't already have one + if ((to == null || to === "" || to === ".") && activeRouteMatch && activeRouteMatch.route.index && !hasNakedIndexQuery(path.search)) { + path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index"; + } + // If we're operating within a basename, prepend it to the pathname. If + // this is a root navigation, then just use the raw basename which allows + // the basename to have full control over the presence of a trailing slash + // on root actions + if (prependBasename && basename !== "/") { + path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]); + } + return createPath(path); +} +// Normalize navigation options by converting formMethod=GET formData objects to +// URLSearchParams so they behave identically to links with query params +function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) { + // Return location verbatim on non-submission navigations + if (!opts || !isSubmissionNavigation(opts)) { + return { + path + }; + } + if (opts.formMethod && !isValidMethod(opts.formMethod)) { + return { + path, + error: getInternalRouterError(405, { + method: opts.formMethod + }) + }; + } + let getInvalidBodyError = () => ({ + path, + error: getInternalRouterError(400, { + type: "invalid-body" + }) + }); + // Create a Submission on non-GET navigations + let rawFormMethod = opts.formMethod || "get"; + let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase(); + let formAction = stripHashFromPath(path); + if (opts.body !== undefined) { + if (opts.formEncType === "text/plain") { + // text only support POST/PUT/PATCH/DELETE submissions + if (!isMutationMethod(formMethod)) { + return getInvalidBodyError(); + } + let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? + // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data + Array.from(opts.body.entries()).reduce((acc, _ref3) => { + let [name, value] = _ref3; + return "" + acc + name + "=" + value + "\n"; + }, "") : String(opts.body); + return { + path, + submission: { + formMethod, + formAction, + formEncType: opts.formEncType, + formData: undefined, + json: undefined, + text + } + }; + } else if (opts.formEncType === "application/json") { + // json only supports POST/PUT/PATCH/DELETE submissions + if (!isMutationMethod(formMethod)) { + return getInvalidBodyError(); + } + try { + let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body; + return { + path, + submission: { + formMethod, + formAction, + formEncType: opts.formEncType, + formData: undefined, + json, + text: undefined + } + }; + } catch (e) { + return getInvalidBodyError(); + } + } + } + invariant(typeof FormData === "function", "FormData is not available in this environment"); + let searchParams; + let formData; + if (opts.formData) { + searchParams = convertFormDataToSearchParams(opts.formData); + formData = opts.formData; + } else if (opts.body instanceof FormData) { + searchParams = convertFormDataToSearchParams(opts.body); + formData = opts.body; + } else if (opts.body instanceof URLSearchParams) { + searchParams = opts.body; + formData = convertSearchParamsToFormData(searchParams); + } else if (opts.body == null) { + searchParams = new URLSearchParams(); + formData = new FormData(); + } else { + try { + searchParams = new URLSearchParams(opts.body); + formData = convertSearchParamsToFormData(searchParams); + } catch (e) { + return getInvalidBodyError(); + } + } + let submission = { + formMethod, + formAction, + formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded", + formData, + json: undefined, + text: undefined + }; + if (isMutationMethod(submission.formMethod)) { + return { + path, + submission + }; + } + // Flatten submission onto URLSearchParams for GET submissions + let parsedPath = parsePath(path); + // On GET navigation submissions we can drop the ?index param from the + // resulting location since all loaders will run. But fetcher GET submissions + // only run a single loader so we need to preserve any incoming ?index params + if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) { + searchParams.append("index", ""); + } + parsedPath.search = "?" + searchParams; + return { + path: createPath(parsedPath), + submission + }; +} +// Filter out all routes 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(history, state, matches, submission, location, isInitialLoad, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError) { + let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : undefined; + let currentUrl = history.createURL(state.location); + let nextUrl = history.createURL(location); + // 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) => { + let { + route + } = match; + if (route.lazy) { + // We haven't loaded this route yet so we don't know if it's got a loader! + return true; + } + if (route.loader == null) { + return false; + } + if (isInitialLoad) { + if (route.loader.hydrate) { + return true; + } + return state.loaderData[route.id] === undefined && ( + // Don't re-run if the loader ran and threw an error + !state.errors || state.errors[route.id] === undefined); + } + // Always call the loader on new route instances and pending defer cancellations + if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) { + return true; + } + // This is the default implementation for when we revalidate. If the route + // provides it's own implementation, then we give them full control but + // provide this value so they can leverage it if needed after they check + // their own specific use cases + let currentRouteMatch = state.matches[index]; + let nextRouteMatch = match; + return shouldRevalidateLoader(match, _extends({ + currentUrl, + currentParams: currentRouteMatch.params, + nextUrl, + nextParams: nextRouteMatch.params + }, submission, { + actionResult, + defaultShouldRevalidate: + // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate + isRevalidationRequired || + // Clicked the same link, resubmitted a GET form + currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || + // Search params affect all loaders + currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch) + })); + }); + // Pick fetcher.loads that need to be revalidated + let revalidatingFetchers = []; + fetchLoadMatches.forEach((f, key) => { + // Don't revalidate: + // - on initial load (shouldn't be any fetchers then anyway) + // - if fetcher won't be present in the subsequent render + // - no longer matches the URL (v7_fetcherPersist=false) + // - was unmounted but persisted due to v7_fetcherPersist=true + if (isInitialLoad || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) { + return; + } + let fetcherMatches = matchRoutes(routesToUse, f.path, basename); + // If the fetcher path no longer matches, push it in with null matches so + // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is + // currently only a use-case for Remix HMR where the route tree can change + // at runtime and remove a route previously loaded via a fetcher + if (!fetcherMatches) { + revalidatingFetchers.push({ + key, + routeId: f.routeId, + path: f.path, + matches: null, + match: null, + controller: null + }); + return; + } + // Revalidating fetchers are decoupled from the route matches since they + // load from a static href. They revalidate based on explicit revalidation + // (submission, useRevalidator, or X-Remix-Revalidate) + let fetcher = state.fetchers.get(key); + let fetcherMatch = getTargetMatch(fetcherMatches, f.path); + let shouldRevalidate = false; + if (fetchRedirectIds.has(key)) { + // Never trigger a revalidation of an actively redirecting fetcher + shouldRevalidate = false; + } else if (cancelledFetcherLoads.includes(key)) { + // Always revalidate if the fetcher was cancelled + shouldRevalidate = true; + } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) { + // If the fetcher hasn't ever completed loading yet, then this isn't a + // revalidation, it would just be a brand new load if an explicit + // revalidation is required + shouldRevalidate = isRevalidationRequired; + } else { + // Otherwise fall back on any user-defined shouldRevalidate, defaulting + // to explicit revalidations only + shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({ + currentUrl, + currentParams: state.matches[state.matches.length - 1].params, + nextUrl, + nextParams: matches[matches.length - 1].params + }, submission, { + actionResult, + defaultShouldRevalidate: isRevalidationRequired + })); + } + if (shouldRevalidate) { + revalidatingFetchers.push({ + key, + routeId: f.routeId, + path: f.path, + matches: fetcherMatches, + match: fetcherMatch, + controller: new AbortController() + }); + } + }); + return [navigationMatches, revalidatingFetchers]; +} +function isNewLoader(currentLoaderData, currentMatch, match) { + let isNew = + // [a] -> [a, b] + !currentMatch || + // [a, b] -> [a, c] + match.route.id !== currentMatch.route.id; + // Handle the case that we don't have data for a re-used route, potentially + // from a prior error or from a cancelled pending deferred + let isMissingData = currentLoaderData[match.route.id] === undefined; + // Always load if this is a net-new route or we don't yet have data + return isNew || isMissingData; +} +function isNewRouteInstance(currentMatch, match) { + let currentPath = currentMatch.route.path; + return ( + // param change for this match, /users/123 -> /users/456 + currentMatch.pathname !== match.pathname || + // splat param changed, which is not present in match.path + // e.g. /files/images/avatar.jpg -> files/finances.xls + currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"] + ); +} +function shouldRevalidateLoader(loaderMatch, arg) { + if (loaderMatch.route.shouldRevalidate) { + let routeChoice = loaderMatch.route.shouldRevalidate(arg); + if (typeof routeChoice === "boolean") { + return routeChoice; + } + } + return arg.defaultShouldRevalidate; +} +/** + * Execute route.lazy() methods to lazily load route modules (loader, action, + * shouldRevalidate) and update the routeManifest in place which shares objects + * with dataRoutes so those get updated as well. + */ +async function loadLazyRouteModule(route, mapRouteProperties, manifest) { + if (!route.lazy) { + return; + } + let lazyRoute = await route.lazy(); + // If the lazy route function was executed and removed by another parallel + // call then we can return - first lazy() to finish wins because the return + // value of lazy is expected to be static + if (!route.lazy) { + return; + } + let routeToUpdate = manifest[route.id]; + invariant(routeToUpdate, "No route found in manifest"); + // Update the route in place. This should be safe because there's no way + // we could yet be sitting on this route as we can't get there without + // resolving lazy() first. + // + // This is different than the HMR "update" use-case where we may actively be + // on the route being updated. The main concern boils down to "does this + // mutation affect any ongoing navigations or any current state.matches + // values?". If not, it should be safe to update in place. + let routeUpdates = {}; + for (let lazyRouteProperty in lazyRoute) { + let staticRouteValue = routeToUpdate[lazyRouteProperty]; + let isPropertyStaticallyDefined = staticRouteValue !== undefined && + // This property isn't static since it should always be updated based + // on the route updates + lazyRouteProperty !== "hasErrorBoundary"; + warning(!isPropertyStaticallyDefined, "Route \"" + routeToUpdate.id + "\" has a static property \"" + lazyRouteProperty + "\" " + "defined but its lazy function is also returning a value for this property. " + ("The lazy route property \"" + lazyRouteProperty + "\" will be ignored.")); + if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) { + routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty]; + } + } + // Mutate the route with the provided updates. Do this first so we pass + // the updated version to mapRouteProperties + Object.assign(routeToUpdate, routeUpdates); + // Mutate the `hasErrorBoundary` property on the route based on the route + // updates and remove the `lazy` function so we don't resolve the lazy + // route again. + Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), { + lazy: undefined + })); +} +async function callLoaderOrAction(type, request, match, matches, manifest, mapRouteProperties, basename, v7_relativeSplatPath, opts) { + if (opts === void 0) { + opts = {}; + } + let resultType; + let result; + let onReject; + let runHandler = handler => { + // Setup a promise we can race against so that abort signals short circuit + let reject; + let abortPromise = new Promise((_, r) => reject = r); + onReject = () => reject(); + request.signal.addEventListener("abort", onReject); + return Promise.race([handler({ + request, + params: match.params, + context: opts.requestContext + }), abortPromise]); + }; + try { + let handler = match.route[type]; + if (match.route.lazy) { + if (handler) { + // Run statically defined handler in parallel with lazy() + let handlerError; + let values = await Promise.all([ + // If the handler throws, don't let it immediately bubble out, + // since we need to let the lazy() execution finish so we know if this + // route has a boundary that can handle the error + runHandler(handler).catch(e => { + handlerError = e; + }), loadLazyRouteModule(match.route, mapRouteProperties, manifest)]); + if (handlerError) { + throw handlerError; + } + result = values[0]; + } else { + // Load lazy route module, then run any returned handler + await loadLazyRouteModule(match.route, mapRouteProperties, manifest); + handler = match.route[type]; + if (handler) { + // Handler still run even if we got interrupted to maintain consistency + // with un-abortable behavior of handler execution on non-lazy or + // previously-lazy-loaded routes + result = await runHandler(handler); + } else if (type === "action") { + let url = new URL(request.url); + let pathname = url.pathname + url.search; + throw getInternalRouterError(405, { + method: request.method, + pathname, + routeId: match.route.id + }); + } else { + // lazy() route has no loader to run. Short circuit here so we don't + // hit the invariant below that errors on returning undefined. + return { + type: ResultType.data, + data: undefined + }; + } + } + } else if (!handler) { + let url = new URL(request.url); + let pathname = url.pathname + url.search; + throw getInternalRouterError(404, { + pathname + }); + } else { + result = await runHandler(handler); + } + invariant(result !== undefined, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ("\"" + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`."); + } catch (e) { + resultType = ResultType.error; + result = e; + } finally { + if (onReject) { + request.signal.removeEventListener("abort", onReject); + } + } + if (isResponse(result)) { + let status = result.status; + // Process redirects + if (redirectStatusCodes.has(status)) { + let location = result.headers.get("Location"); + invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header"); + // Support relative routing in internal redirects + if (!ABSOLUTE_URL_REGEX.test(location)) { + location = normalizeTo(new URL(request.url), matches.slice(0, matches.indexOf(match) + 1), basename, true, location, v7_relativeSplatPath); + } else if (!opts.isStaticRequest) { + // Strip off the protocol+origin for same-origin + same-basename absolute + // redirects. If this is a static request, we can let it go back to the + // browser as-is + let currentUrl = new URL(request.url); + let url = location.startsWith("//") ? new URL(currentUrl.protocol + location) : new URL(location); + let isSameBasename = stripBasename(url.pathname, basename) != null; + if (url.origin === currentUrl.origin && isSameBasename) { + location = url.pathname + url.search + url.hash; + } + } + // Don't process redirects in the router during static requests requests. + // Instead, throw the Response and let the server handle it with an HTTP + // redirect. We also update the Location header in place in this flow so + // basename and relative routing is taken into account + if (opts.isStaticRequest) { + result.headers.set("Location", location); + throw result; + } + return { + type: ResultType.redirect, + status, + location, + revalidate: result.headers.get("X-Remix-Revalidate") !== null, + reloadDocument: result.headers.get("X-Remix-Reload-Document") !== null + }; + } + // For SSR single-route requests, we want to hand Responses back directly + // without unwrapping. We do this with the QueryRouteResponse wrapper + // interface so we can know whether it was returned or thrown + if (opts.isRouteRequest) { + let queryRouteResponse = { + type: resultType === ResultType.error ? ResultType.error : ResultType.data, + response: result + }; + throw queryRouteResponse; + } + let data; + try { + let contentType = result.headers.get("Content-Type"); + // Check between word boundaries instead of startsWith() due to the last + // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type + if (contentType && /\bapplication\/json\b/.test(contentType)) { + if (result.body == null) { + data = null; + } else { + data = await result.json(); + } + } else { + data = await result.text(); + } + } catch (e) { + return { + type: ResultType.error, + error: e + }; + } + if (resultType === ResultType.error) { + return { + type: resultType, + error: new ErrorResponseImpl(status, result.statusText, data), + headers: result.headers + }; + } + return { + type: ResultType.data, + data, + statusCode: result.status, + headers: result.headers + }; + } + if (resultType === ResultType.error) { + return { + type: resultType, + error: result + }; + } + if (isDeferredData(result)) { + var _result$init, _result$init2; + return { + type: ResultType.deferred, + deferredData: result, + statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status, + headers: ((_result$init2 = result.init) == null ? void 0 : _result$init2.headers) && new Headers(result.init.headers) + }; + } + return { + type: ResultType.data, + data: result + }; +} +// Utility method for creating the Request instances for loaders/actions during +// client-side navigations and fetches. During SSR we will always have a +// Request instance from the static handler (query/queryRoute) +function createClientSideRequest(history, location, signal, submission) { + let url = history.createURL(stripHashFromPath(location)).toString(); + let init = { + signal + }; + if (submission && isMutationMethod(submission.formMethod)) { + let { + formMethod, + formEncType + } = submission; + // Didn't think we needed this but it turns out unlike other methods, patch + // won't be properly normalized to uppercase and results in a 405 error. + // See: https://fetch.spec.whatwg.org/#concept-method + init.method = formMethod.toUpperCase(); + if (formEncType === "application/json") { + init.headers = new Headers({ + "Content-Type": formEncType + }); + init.body = JSON.stringify(submission.json); + } else if (formEncType === "text/plain") { + // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) + init.body = submission.text; + } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) { + // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) + init.body = convertFormDataToSearchParams(submission.formData); + } else { + // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) + init.body = submission.formData; + } + } + return new Request(url, init); +} +function convertFormDataToSearchParams(formData) { + let searchParams = new URLSearchParams(); + for (let [key, value] of formData.entries()) { + // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs + searchParams.append(key, typeof value === "string" ? value : value.name); + } + return searchParams; +} +function convertSearchParamsToFormData(searchParams) { + let formData = new FormData(); + for (let [key, value] of searchParams.entries()) { + formData.append(key, value); + } + return formData; +} +function processRouteLoaderData(matches, 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 = errors || {}; + // Prefer higher error values if lower errors bubble to the same boundary + if (errors[boundaryMatch.route.id] == null) { + errors[boundaryMatch.route.id] = error; + } + // Clear our any prior loaderData for the throwing route + loaderData[id] = undefined; + // Once we find our first (highest) error, we set the status code and + // prevent deeper status codes from overriding + if (!foundError) { + foundError = true; + statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500; + } + if (result.headers) { + loaderHeaders[id] = result.headers; + } + } else { + if (isDeferredResult(result)) { + activeDeferreds.set(id, result.deferredData); + loaderData[id] = result.deferredData.data; + } 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. Also clear out any loaderData for the + // throwing route + if (pendingError) { + errors = pendingError; + loaderData[Object.keys(pendingError)[0]] = undefined; + } + 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, + controller + } = revalidatingFetchers[index]; + invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result"); + let result = fetcherResults[index]; + // Process fetcher non-redirect errors + if (controller && controller.signal.aborted) { + // Nothing to do for aborted fetchers + continue; + } else if (isErrorResult(result)) { + let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id); + if (!(errors && errors[boundaryMatch.route.id])) { + errors = _extends({}, errors, { + [boundaryMatch.route.id]: result.error + }); + } + state.fetchers.delete(key); + } else if (isRedirectResult(result)) { + // Should never get here, redirects should get processed above, but we + // keep this to type narrow to a success result in the else + invariant(false, "Unhandled fetcher revalidation redirect"); + } else if (isDeferredResult(result)) { + // Should never get here, deferred data should be awaited for fetchers + // in resolveDeferredResults + invariant(false, "Unhandled fetcher deferred data"); + } else { + let doneFetcher = getDoneFetcher(result.data); + state.fetchers.set(key, doneFetcher); + } + } + return { + loaderData, + errors + }; +} +function mergeLoaderData(loaderData, newLoaderData, matches, errors) { + let mergedLoaderData = _extends({}, newLoaderData); + for (let match of matches) { + let id = match.route.id; + if (newLoaderData.hasOwnProperty(id)) { + if (newLoaderData[id] !== undefined) { + mergedLoaderData[id] = newLoaderData[id]; + } + } else if (loaderData[id] !== undefined && match.route.loader) { + // Preserve existing keys not included in newLoaderData and where a loader + // wasn't removed by HMR + mergedLoaderData[id] = loaderData[id]; + } + if (errors && errors.hasOwnProperty(id)) { + // Don't keep any loader data below the boundary + break; + } + } + return mergedLoaderData; +} +// Find the nearest error boundary, looking upwards from the leaf route (or the +// route specified by routeId) for the closest ancestor error boundary, +// defaulting to the root match +function findNearestBoundary(matches, routeId) { + let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches]; + return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0]; +} +function getShortCircuitMatches(routes) { + // Prefer a root layout route if present, otherwise shim in a route object + let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || { + id: "__shim-error-route__" + }; + return { + matches: [{ + params: {}, + pathname: "", + pathnameBase: "", + route + }], + route + }; +} +function getInternalRouterError(status, _temp5) { + let { + pathname, + routeId, + method, + type + } = _temp5 === void 0 ? {} : _temp5; + let statusText = "Unknown Server Error"; + let errorMessage = "Unknown @remix-run/router error"; + if (status === 400) { + statusText = "Bad Request"; + if (method && pathname && routeId) { + errorMessage = "You made a " + method + " request to \"" + pathname + "\" but " + ("did not provide a `loader` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; + } else if (type === "defer-action") { + errorMessage = "defer() is not supported in actions"; + } else if (type === "invalid-body") { + errorMessage = "Unable to encode submission body"; + } + } else if (status === 403) { + statusText = "Forbidden"; + errorMessage = "Route \"" + routeId + "\" does not match URL \"" + pathname + "\""; + } else if (status === 404) { + statusText = "Not Found"; + errorMessage = "No route matches URL \"" + pathname + "\""; + } else if (status === 405) { + statusText = "Method Not Allowed"; + if (method && pathname && routeId) { + errorMessage = "You made a " + method.toUpperCase() + " request to \"" + pathname + "\" but " + ("did not provide an `action` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; + } else if (method) { + errorMessage = "Invalid request method \"" + method.toUpperCase() + "\""; + } + } + return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true); +} +// Find any returned redirect errors, starting from the lowest match +function findRedirect(results) { + for (let i = results.length - 1; i >= 0; i--) { + let result = results[i]; + if (isRedirectResult(result)) { + return { + result, + idx: i + }; + } + } +} +function stripHashFromPath(path) { + let parsedPath = typeof path === "string" ? parsePath(path) : path; + return createPath(_extends({}, parsedPath, { + hash: "" + })); +} +function isHashChangeOnly(a, b) { + if (a.pathname !== b.pathname || a.search !== b.search) { + return false; + } + if (a.hash === "") { + // /page -> /page#hash + return b.hash !== ""; + } else if (a.hash === b.hash) { + // /page#hash -> /page#hash + return true; + } else if (b.hash !== "") { + // /page#hash -> /page#other + return true; + } + // If the hash is removed the browser will re-perform a request to the server + // /page#hash -> /page + return false; +} +function isDeferredResult(result) { + return result.type === ResultType.deferred; +} +function isErrorResult(result) { + return result.type === ResultType.error; +} +function isRedirectResult(result) { + return (result && result.type) === ResultType.redirect; +} +function isDeferredData(value) { + let deferred = value; + return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function"; +} +function isResponse(value) { + return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined"; +} +function isRedirectResponse(result) { + if (!isResponse(result)) { + return false; + } + let status = result.status; + let location = result.headers.get("Location"); + return status >= 300 && status <= 399 && location != null; +} +function isQueryRouteResponse(obj) { + return obj && isResponse(obj.response) && (obj.type === ResultType.data || obj.type === ResultType.error); +} +function isValidMethod(method) { + return validRequestMethods.has(method.toLowerCase()); +} +function isMutationMethod(method) { + return validMutationMethods.has(method.toLowerCase()); +} +async function resolveDeferredResults(currentMatches, matchesToLoad, results, signals, isFetcher, currentLoaderData) { + for (let index = 0; index < results.length; index++) { + let result = results[index]; + let match = matchesToLoad[index]; + // If we don't have a match, then we can have a deferred result to do + // anything with. This is for revalidating fetchers where the route was + // removed during HMR + if (!match) { + continue; + } + let currentMatch = currentMatches.find(m => m.route.id === match.route.id); + let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined; + if (isDeferredResult(result) && (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 + let signal = signals[index]; + invariant(signal, "Expected an AbortSignal for revalidating fetcher deferred result"); + 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 === ""); +} +function getTargetMatch(matches, location) { + let search = typeof location === "string" ? parsePath(location).search : location.search; + if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) { + // Return the leaf index route when index is present + return matches[matches.length - 1]; + } + // Otherwise grab the deepest "path contributing" match (ignoring index and + // pathless layout routes) + let pathMatches = getPathContributingMatches(matches); + return pathMatches[pathMatches.length - 1]; +} +function getSubmissionFromNavigation(navigation) { + let { + formMethod, + formAction, + formEncType, + text, + formData, + json + } = navigation; + if (!formMethod || !formAction || !formEncType) { + return; + } + if (text != null) { + return { + formMethod, + formAction, + formEncType, + formData: undefined, + json: undefined, + text + }; + } else if (formData != null) { + return { + formMethod, + formAction, + formEncType, + formData, + json: undefined, + text: undefined + }; + } else if (json !== undefined) { + return { + formMethod, + formAction, + formEncType, + formData: undefined, + json, + text: undefined + }; + } +} +function getLoadingNavigation(location, submission) { + if (submission) { + let navigation = { + state: "loading", + location, + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text + }; + return navigation; + } else { + let navigation = { + state: "loading", + location, + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined + }; + return navigation; + } +} +function getSubmittingNavigation(location, submission) { + let navigation = { + state: "submitting", + location, + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text + }; + return navigation; +} +function getLoadingFetcher(submission, data) { + if (submission) { + let fetcher = { + state: "loading", + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text, + data + }; + return fetcher; + } else { + let fetcher = { + state: "loading", + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined, + data + }; + return fetcher; + } +} +function getSubmittingFetcher(submission, existingFetcher) { + let fetcher = { + state: "submitting", + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text, + data: existingFetcher ? existingFetcher.data : undefined + }; + return fetcher; +} +function getDoneFetcher(data) { + let fetcher = { + state: "idle", + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined, + data + }; + return fetcher; +} +function restoreAppliedTransitions(_window, transitions) { + try { + let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY); + if (sessionPositions) { + let json = JSON.parse(sessionPositions); + for (let [k, v] of Object.entries(json || {})) { + if (v && Array.isArray(v)) { + transitions.set(k, new Set(v || [])); + } + } + } + } catch (e) { + // no-op, use default empty object + } +} +function persistAppliedTransitions(_window, transitions) { + if (transitions.size > 0) { + let json = {}; + for (let [k, v] of transitions) { + json[k] = [...v]; + } + try { + _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json)); + } catch (error) { + warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ")."); + } + } +} +//#endregion + +export { AbortedDeferredError, Action, IDLE_BLOCKER, IDLE_FETCHER, IDLE_NAVIGATION, UNSAFE_DEFERRED_SYMBOL, DeferredData as UNSAFE_DeferredData, ErrorResponseImpl as UNSAFE_ErrorResponseImpl, convertRouteMatchToUiMatch as UNSAFE_convertRouteMatchToUiMatch, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, getResolveToMatches as UNSAFE_getResolveToMatches, invariant as UNSAFE_invariant, warning as UNSAFE_warning, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, createRouter, createStaticHandler, defer, generatePath, getStaticContextFromError, getToPathname, isDeferredData, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, parsePath, redirect, redirectDocument, resolvePath, resolveTo, stripBasename }; +//# 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 new file mode 100644 index 0000000..5a8c843 --- /dev/null +++ b/node_modules/@remix-run/router/dist/router.js.map @@ -0,0 +1 @@ +{"version":3,"file":"router.js","sources":["../history.ts","../utils.ts","../router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\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 * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly {\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 let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: 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 statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n status: number;\n location: string;\n revalidate: boolean;\n reloadDocument?: 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\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on ``,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable | null;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (args: LoaderFunctionArgs):\n | Promise\n | DataFunctionValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (args: ActionFunctionArgs):\n | Promise\n | DataFunctionValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction {\n (): Promise>>;\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 lazy?: LazyRouteFunction;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record;\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 `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam =\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 you 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 mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: number[] = [],\n manifest: RouteManifest = {}\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 !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/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(\n branches[i],\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n safelyDecodeURI(pathname)\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch,\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/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\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/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, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = safelyDecodeURIComponent(value || \"\", paramName);\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(\n /\\/:([\\w-]+)(\\?)?/g,\n (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n }\n );\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nfunction safelyDecodeURI(value: string) {\n try {\n return decodeURI(value);\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\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 * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/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 *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === matches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial;\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 (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\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 pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n ActionFunction,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n AgnosticRouteObject,\n DataResult,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n ImmutableRouteKey,\n LoaderFunction,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(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 * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\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 * Map of current blockers\n */\n blockers: 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 * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record;\n actionHeaders: Record;\n activeDeferreds: Record | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: { requestContext?: unknown }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: { routeId?: string; requestContext?: unknown }\n ): Promise;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n unstable_viewTransitionOpts?: ViewTransitionOpts;\n unstable_flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\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 * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\n/**\n * Wrapper object to allow us to throw any response out from callLoaderOrAction\n * for queryRouter while preserving whether or not it was thrown or returned\n * from the loader/action\n */\ninterface QueryRouteResponse {\n type: ResultType.data | ResultType.error;\n response: Response;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\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 // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let 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 error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized: boolean;\n let hasLazyRoutes = initialMatches.some((m) => m.route.lazy);\n let hasLoaders = initialMatches.some((m) => m.route.loader);\n if (hasLazyRoutes) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!hasLoaders) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n initialized = initialMatches.every(\n (m) =>\n m.route.loader &&\n m.route.loader.hydrate !== true &&\n ((loaderData && loaderData[m.route.id] !== undefined) ||\n (errors && errors[m.route.id] !== undefined))\n );\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map> = new Map<\n string,\n Set\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location, {\n initialHydration: true,\n });\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n }\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 { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n 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 | null,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.unstable_viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n { 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 initialHydration?: boolean;\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a \n // which will default to a navigation to /page\n if (\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let 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 (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\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, flushSync }\n );\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n\n // Create a GET request for the loaders\n request = new Request(request.url, { signal: request.signal });\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.fetcherSubmission,\n opts && opts.replace,\n opts && opts.initialHydration === true,\n flushSync,\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 ...(pendingActionData ? { actionData: pendingActionData } : {}),\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; flushSync?: boolean } = {}\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n replace =\n result.location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(state, result, { submission, replace });\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 // Send back an empty object we can use to clear out any prior actionData\n pendingActionData: {},\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\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 fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: 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 =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionData,\n pendingError\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\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 we have partialHydration enabled, then don't update the state for the\n // initial data load since iot's not a \"navigation\"\n if (\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration)\n ) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n let actionData = pendingActionData || state.actionData;\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData\n ? Object.keys(actionData).length === 0\n ? { actionData: null }\n : { actionData }\n : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(state, redirect.result, { 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 let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResult = await callLoaderOrAction(\n \"action\",\n fetchRequest,\n match,\n requestMatches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(state, actionResult, {\n fetcherSubmission: submission,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n false,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n { [match.route.id]: actionResult.data },\n undefined // No need to send through errors since we short circuit above\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(state, redirect.result);\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 // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(state, result);\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n state: RouterState,\n redirect: RedirectResult,\n {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n\n let redirectLocation = createLocation(state.location, redirect.location, {\n _isRedirect: true,\n });\n invariant(\n redirectLocation,\n \"Expected a location on the redirect navigation\"\n );\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.reloadDocument) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) {\n const url = init.history.createURL(redirect.location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(redirect.location);\n } else {\n routerWindow.location.assign(redirect.location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: redirect.location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: 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((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n )\n ),\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n return callLoaderOrAction(\n \"loader\",\n createClientSideRequest(init.history, f.path, f.controller.signal),\n f.match,\n f.matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n } else {\n let error: ErrorResult = {\n type: ResultType.error,\n error: getInternalRouterError(404, { pathname: f.path }),\n };\n return error;\n }\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 loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\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 updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher(key: string): Fetcher {\n if (future.v7_fetcherPersist) {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({ fetchers: new Map(state.fetchers) });\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 = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function 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 || null;\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 getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n ...(opts ? opts.future : null),\n };\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n */\n async function query(\n request: Request,\n { requestContext }: { requestContext?: unknown } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(request, location, matches, requestContext);\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n }: { requestContext?: unknown; routeId?: string } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n match\n );\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction, we throw\n // it to bail out and then return or throw here based on whether the user\n // returned or threw\n if (isQueryRouteResponse(e)) {\n if (e.type === ResultType.error) {\n throw e.response;\n }\n return e.response;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath,\n { isStaticRequest: true, isRouteRequest, requestContext }\n );\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.status,\n headers: {\n Location: result.location,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n 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(\n request,\n matches,\n requestContext,\n undefined,\n {\n [boundaryMatch.route.id]: result.error,\n }\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 // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n let context = await loadRouteData(loaderRequest, matches, requestContext);\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 requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch,\n pendingActionError?: RouteData\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n );\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath,\n { isStaticRequest: true, isRouteRequest, requestContext }\n )\n ),\n ]);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError,\n activeDeferreds\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n 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\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes 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 history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isInitialLoad: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : undefined;\n\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let { route } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n\n if (route.loader == null) {\n return false;\n }\n\n if (isInitialLoad) {\n if (route.loader.hydrate) {\n return true;\n }\n return (\n state.loaderData[route.id] === undefined &&\n // Don't re-run if the loader ran and threw an error\n (!state.errors || state.errors[route.id] === undefined)\n );\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n defaultShouldRevalidate:\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial load (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (\n isInitialLoad ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.includes(key)) {\n // Always revalidate if the fetcher was cancelled\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n defaultShouldRevalidate: isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n basename: string,\n v7_relativeSplatPath: boolean,\n opts: {\n isStaticRequest?: boolean;\n isRouteRequest?: boolean;\n requestContext?: unknown;\n } = {}\n): Promise {\n let resultType;\n let result;\n let onReject: (() => void) | undefined;\n\n let runHandler = (handler: ActionFunction | LoaderFunction) => {\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 onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n return Promise.race([\n handler({\n request,\n params: match.params,\n context: opts.requestContext,\n }),\n abortPromise,\n ]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let values = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadLazyRouteModule(match.route, mapRouteProperties, manifest),\n ]);\n if (handlerError) {\n throw handlerError;\n }\n result = values[0];\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n\n handler = match.route[type];\n if (handler) {\n // Handler still run even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, data: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n if (isResponse(result)) {\n let status = result.status;\n\n // Process redirects\n if (redirectStatusCodes.has(status)) {\n let location = result.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n // Support relative routing in internal redirects\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n location = normalizeTo(\n new URL(request.url),\n matches.slice(0, matches.indexOf(match) + 1),\n basename,\n true,\n location,\n v7_relativeSplatPath\n );\n } else if (!opts.isStaticRequest) {\n // Strip off the protocol+origin for same-origin + same-basename absolute\n // redirects. If this is a static request, we can let it go back to the\n // browser as-is\n let currentUrl = new URL(request.url);\n let url = location.startsWith(\"//\")\n ? new URL(currentUrl.protocol + location)\n : new URL(location);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n location = url.pathname + url.search + url.hash;\n }\n }\n\n // Don't process redirects in the router during static requests requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect. We also update the Location header in place in this flow so\n // basename and relative routing is taken into account\n if (opts.isStaticRequest) {\n result.headers.set(\"Location\", location);\n throw result;\n }\n\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n reloadDocument: result.headers.get(\"X-Remix-Reload-Document\") !== null,\n };\n }\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping. We do this with the QueryRouteResponse wrapper\n // interface so we can know whether it was returned or thrown\n if (opts.isRouteRequest) {\n let queryRouteResponse: QueryRouteResponse = {\n type:\n resultType === ResultType.error ? ResultType.error : ResultType.data,\n response: result,\n };\n throw queryRouteResponse;\n }\n\n let data: any;\n\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return { type: ResultType.error, error: e };\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponseImpl(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 (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n 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\n errors = errors || {};\n\n // Prefer higher error values if lower errors bubble to the same boundary\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n } else {\n loaderData[id] = result.data;\n }\n\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. Also clear out any loaderData for the\n // throwing route\n if (pendingError) {\n errors = pendingError;\n loaderData[Object.keys(pendingError)[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n 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, controller } = 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 (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isQueryRouteResponse(obj: any): obj is QueryRouteResponse {\n return (\n obj &&\n isResponse(obj.response) &&\n (obj.type === ResultType.data || obj.type === ResultType.error)\n );\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\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 // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (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 let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\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\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n\n//#endregion\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","createHref","createPath","history","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","substr","startsWith","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","invariant","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","idx","current","_extends","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","getIndex","replaceState","handlePop","historyState","pushState","error","DOMException","name","assign","origin","addEventListener","removeEventListener","ResultType","immutableRouteKeys","Set","isIndexRoute","route","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","treePath","id","join","children","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","i","matchRouteBranch","safelyDecodeURI","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","joinPaths","routesMeta","concat","score","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","String","array","isLastSegment","star","keyMatch","optional","param","pattern","matcher","compiledParams","compilePath","captureGroups","memo","paramName","splatValue","safelyDecodeURIComponent","regexpSource","_","RegExp","decodeURI","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","resolvePathname","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","init","responseInit","status","headers","Headers","has","set","Response","AbortedDeferredError","DeferredData","constructor","pendingKeysSet","subscribers","deferredKeys","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","v","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","isTrackedPromise","_tracked","_error","_data","defer","redirect","redirectDocument","response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","dataRoutes","inFlightDataRoutes","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialErrors","getInternalRouterError","getShortCircuitMatches","initialized","hasLazyRoutes","m","lazy","hasLoaders","loader","errors","hydrate","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","deletedFetchers","activeDeferreds","blockerFunctions","ignoreNextHistoryUpdate","initialize","blockerKey","shouldBlockNavigation","currentLocation","updateBlocker","updateState","startNavigation","restoreAppliedTransitions","_saveAppliedTransitions","persistAppliedTransitions","initialHydration","dispose","clear","deleteFetcher","deleteBlocker","newState","opts","completedFetchers","deletedFetchersKeys","fetcher","unstable_viewTransitionOpts","viewTransitionOpts","unstable_flushSync","flushSync","completeNavigation","_temp","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","toPaths","getSavedScrollPosition","navigate","normalizedPath","normalizeTo","fromRouteId","relative","submission","normalizeNavigateOptions","userReplace","pendingError","enableViewTransition","unstable_viewTransition","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","routesToUse","loadingNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","request","createClientSideRequest","pendingActionData","findNearestBoundary","actionOutput","handleAction","shortCircuited","pendingActionError","getLoadingNavigation","Request","handleLoaders","fetcherSubmission","getSubmittingNavigation","actionMatch","getTargetMatch","type","method","routeId","callLoaderOrAction","isRedirectResult","startRedirectNavigation","isErrorResult","boundaryMatch","isDeferredResult","activeSubmission","getSubmissionFromNavigation","matchesToLoad","revalidatingFetchers","getMatchesToLoad","updatedFetchers","markFetchRedirectsDone","rf","revalidatingFetcher","getLoadingFetcher","abortFetcher","abortPendingFetchRevalidations","f","results","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","fetcherKey","processLoaderData","deferredData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","fetch","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","existingFetcher","updateFetcherState","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResult","getDoneFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","_temp2","redirectLocation","isDocumentReload","reloadDocument","redirectHistoryAction","currentMatches","fetchersToLoad","all","resolveDeferredResults","getFetcher","deleteFetcherAndUpdateState","count","markFetchersDone","doneKeys","landedId","yeetedKeys","getBlocker","blocker","newBlocker","blockerFunction","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","getScrollKey","_internalSetRoutes","newRoutes","_internalFetchControllers","_internalActiveDeferreds","UNSAFE_DEFERRED_SYMBOL","Symbol","createStaticHandler","query","_temp3","requestContext","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp4","find","values","_result$activeDeferre","routeMatch","submit","loadRouteData","isQueryRouteResponse","isRedirectResponse","isRouteRequest","isStaticRequest","Location","context","loaderRequest","getLoaderMatchesUntilBoundary","processRouteLoaderData","executedLoaders","fromEntries","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","isSubmissionNavigation","body","prependBasename","contextualMatches","activeRouteMatch","hasNakedIndexQuery","normalizeFormMethod","isFetcher","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","URLSearchParams","parse","searchParams","convertFormDataToSearchParams","convertSearchParamsToFormData","append","boundaryId","boundaryMatches","findIndex","isInitialLoad","currentUrl","nextUrl","navigationMatches","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","currentLoaderData","currentMatch","isNew","isMissingData","currentPath","loaderMatch","arg","routeChoice","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","staticRouteValue","isPropertyStaticallyDefined","resultType","onReject","runHandler","handler","handlerError","protocol","isSameBasename","queryRouteResponse","contentType","isDeferredData","_result$init","_result$init2","deferred","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","_temp5","errorMessage","obj","signals","isRevalidatingLoader","unwrap","getAll","_window","transitions","sessionPositions","sessionStorage","getItem","setItem"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AACA;AAEA;;AAEG;IACSA,OAsBX;AAtBD,CAAA,UAAYA,MAAM,EAAA;AAChB;;;;;;AAMG;AACHA,EAAAA,MAAA,CAAA,KAAA,CAAA,GAAA,KAAW,CAAA;AAEX;;;;AAIG;AACHA,EAAAA,MAAA,CAAA,MAAA,CAAA,GAAA,MAAa,CAAA;AAEb;;;AAGG;AACHA,EAAAA,MAAA,CAAA,SAAA,CAAA,GAAA,SAAmB,CAAA;AACrB,CAAC,EAtBWA,MAAM,KAANA,MAAM,GAsBjB,EAAA,CAAA,CAAA,CAAA;AAqKD,MAAMC,iBAAiB,GAAG,UAAU,CAAA;AA+BpC;;;AAGG;AACa,SAAAC,mBAAmBA,CACjCC,OAAA,EAAkC;AAAA,EAAA,IAAlCA,OAAA,KAAA,KAAA,CAAA,EAAA;IAAAA,OAAA,GAAgC,EAAE,CAAA;AAAA,GAAA;EAElC,IAAI;IAAEC,cAAc,GAAG,CAAC,GAAG,CAAC;IAAEC,YAAY;AAAEC,IAAAA,QAAQ,GAAG,KAAA;AAAO,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ACF,CAAC,OAAOzJ,KAAK,EAAE;AACdzE,MAAAA,OAAO,CACL,KAAK,EACyDyE,6DAAAA,GAAAA,KAAK,OAAI,CACxE,CAAA;AACF,KAAA;AACF,GAAA;AACH,CAAA;AAEA;;;;"} \ No newline at end of file diff --git a/node_modules/@remix-run/router/dist/router.umd.js b/node_modules/@remix-run/router/dist/router.umd.js new file mode 100644 index 0000000..e4e0063 --- /dev/null +++ b/node_modules/@remix-run/router/dist/router.umd.js @@ -0,0 +1,4846 @@ +/** + * @remix-run/router v1.14.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 (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.RemixRouter = {})); +})(this, (function (exports) { 'use strict'; + + function _extends() { + _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. + */ + let Action = /*#__PURE__*/function (Action) { + Action["Pop"] = "POP"; + Action["Push"] = "PUSH"; + Action["Replace"] = "REPLACE"; + return Action; + }({}); + + /** + * The pathname, search, and hash values of a URL. + */ + + // TODO: (v7) Change the Location generic default from `any` to `unknown` and + // remove Remix `useLocation` wrapper. + /** + * An entry in a history stack. A location contains information about the + * URL path, as well as possibly some arbitrary state and a key. + */ + /** + * A change to the current location. + */ + /** + * A function that receives notifications about location changes. + */ + /** + * Describes a location that is the destination of some navigation, either via + * `history.push` or `history.replace`. This may be either a URL or the pieces + * of a URL path. + */ + /** + * A history is an interface to the navigation stack. The history serves as the + * source of truth for the current location, as well as provides a set of + * methods that may be used to change it. + * + * It is similar to the DOM's `window.history` object, but with a smaller, more + * focused API. + */ + const PopStateEventType = "popstate"; + //#endregion + + //////////////////////////////////////////////////////////////////////////////// + //#region Memory History + //////////////////////////////////////////////////////////////////////////////// + + /** + * A user-supplied object that describes a location. Used when providing + * entries to `createMemoryHistory` via its `initialEntries` option. + */ + /** + * A memory history stores locations in memory. This is useful in stateful + * environments where there is no web browser, such as node tests or React + * Native. + */ + /** + * Memory history stores the current location in memory. It is designed for use + * in stateful non-browser environments like tests and React Native. + */ + function createMemoryHistory(options) { + if (options === void 0) { + options = {}; + } + let { + initialEntries = ["/"], + initialIndex, + v5Compat = false + } = options; + let entries; // Declare so we can access from createMemoryLocation + entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined)); + let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex); + let action = Action.Pop; + let listener = null; + function clampIndex(n) { + return Math.min(Math.max(n, 0), entries.length - 1); + } + function getCurrentLocation() { + return entries[index]; + } + function createMemoryLocation(to, state, key) { + if (state === void 0) { + state = null; + } + let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key); + warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to)); + return location; + } + function createHref(to) { + return typeof to === "string" ? to : createPath(to); + } + let history = { + get index() { + return index; + }, + get action() { + return action; + }, + get location() { + return getCurrentLocation(); + }, + createHref, + createURL(to) { + return new URL(createHref(to), "http://localhost"); + }, + encodeLocation(to) { + let path = typeof to === "string" ? parsePath(to) : to; + return { + pathname: path.pathname || "", + search: path.search || "", + hash: path.hash || "" + }; + }, + push(to, state) { + action = Action.Push; + let nextLocation = createMemoryLocation(to, state); + index += 1; + entries.splice(index, entries.length, nextLocation); + if (v5Compat && listener) { + listener({ + action, + location: nextLocation, + delta: 1 + }); + } + }, + replace(to, state) { + action = Action.Replace; + let nextLocation = createMemoryLocation(to, state); + entries[index] = nextLocation; + if (v5Compat && listener) { + listener({ + action, + location: nextLocation, + delta: 0 + }); + } + }, + go(delta) { + action = Action.Pop; + let nextIndex = clampIndex(index + delta); + let nextLocation = entries[nextIndex]; + index = nextIndex; + if (listener) { + listener({ + action, + location: nextLocation, + delta + }); + } + }, + listen(fn) { + listener = fn; + return () => { + listener = null; + }; + } + }; + return history; + } + //#endregion + + //////////////////////////////////////////////////////////////////////////////// + //#region Browser History + //////////////////////////////////////////////////////////////////////////////// + + /** + * A browser history stores the current location in regular URLs in a web + * browser environment. This is the standard for most web apps and provides the + * cleanest URLs the browser's address bar. + * + * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory + */ + /** + * Browser history stores the location in regular URLs. This is the standard for + * most web apps, but it requires some configuration on the server to ensure you + * serve the same app at multiple URLs. + * + * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory + */ + function createBrowserHistory(options) { + if (options === void 0) { + options = {}; + } + function createBrowserLocation(window, globalHistory) { + let { + pathname, + search, + hash + } = window.location; + return createLocation("", { + pathname, + search, + hash + }, + // state defaults to `null` because `window.history.state` does + globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); + } + function createBrowserHref(window, to) { + return typeof to === "string" ? to : createPath(to); + } + return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options); + } + //#endregion + + //////////////////////////////////////////////////////////////////////////////// + //#region Hash History + //////////////////////////////////////////////////////////////////////////////// + + /** + * A hash history stores the current location in the fragment identifier portion + * of the URL in a web browser environment. + * + * This is ideal for apps that do not control the server for some reason + * (because the fragment identifier is never sent to the server), including some + * shared hosting environments that do not provide fine-grained controls over + * which pages are served at which URLs. + * + * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory + */ + /** + * Hash history stores the location in window.location.hash. This makes it ideal + * for situations where you don't want to send the location to the server for + * some reason, either because you do cannot configure it or the URL space is + * reserved for something else. + * + * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory + */ + function createHashHistory(options) { + if (options === void 0) { + options = {}; + } + function createHashLocation(window, globalHistory) { + let { + pathname = "/", + search = "", + hash = "" + } = parsePath(window.location.hash.substr(1)); + + // Hash URL should always have a leading / just like window.location.pathname + // does, so if an app ends up at a route like /#something then we add a + // leading slash so all of our path-matching behaves the same as if it would + // in a browser router. This is particularly important when there exists a + // root splat route () since that matches internally against + // "/*" and we'd expect /#something to 404 in a hash router app. + if (!pathname.startsWith("/") && !pathname.startsWith(".")) { + pathname = "/" + pathname; + } + return createLocation("", { + pathname, + search, + hash + }, + // state defaults to `null` because `window.history.state` does + globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default"); + } + function createHashHref(window, to) { + let base = window.document.querySelector("base"); + let href = ""; + if (base && base.getAttribute("href")) { + let url = window.location.href; + let hashIndex = url.indexOf("#"); + href = hashIndex === -1 ? url : url.slice(0, hashIndex); + } + return href + "#" + (typeof to === "string" ? to : createPath(to)); + } + function validateHashLocation(location, to) { + warning(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")"); + } + return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options); + } + //#endregion + + //////////////////////////////////////////////////////////////////////////////// + //#region UTILS + //////////////////////////////////////////////////////////////////////////////// + + /** + * @private + */ + function invariant(value, message) { + if (value === false || value === null || typeof value === "undefined") { + throw new Error(message); + } + } + function warning(cond, message) { + if (!cond) { + // eslint-disable-next-line no-console + if (typeof console !== "undefined") console.warn(message); + try { + // Welcome to debugging history! + // + // This error is thrown as a convenience, so you can more easily + // find the source for a warning that appears in the console by + // enabling "pause on exceptions" in your JavaScript debugger. + throw new Error(message); + // eslint-disable-next-line no-empty + } catch (e) {} + } + } + function createKey() { + return Math.random().toString(36).substr(2, 8); + } + + /** + * For browser-based histories, we combine the state and key into an object + */ + function getHistoryState(location, index) { + return { + usr: location.state, + key: location.key, + idx: index + }; + } + + /** + * Creates a Location object with a unique key from the given Path + */ + function createLocation(current, to, state, key) { + if (state === void 0) { + state = null; + } + let location = _extends({ + pathname: typeof current === "string" ? current : current.pathname, + search: "", + hash: "" + }, typeof to === "string" ? parsePath(to) : to, { + state, + // TODO: This could be cleaned up. push/replace should probably just take + // full Locations now and avoid the need to run through this flow at all + // But that's a pretty big refactor to the current test suite so going to + // keep as is for the time being and just let any incoming keys take precedence + key: to && to.key || key || createKey() + }); + return location; + } + + /** + * Creates a string URL path from the given pathname, search, and hash components. + */ + function createPath(_ref) { + let { + pathname = "/", + search = "", + hash = "" + } = _ref; + if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search; + if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash; + return pathname; + } + + /** + * Parses a string URL path into its separate pathname, search, and hash components. + */ + function parsePath(path) { + let parsedPath = {}; + if (path) { + let hashIndex = path.indexOf("#"); + if (hashIndex >= 0) { + parsedPath.hash = path.substr(hashIndex); + path = path.substr(0, hashIndex); + } + let searchIndex = path.indexOf("?"); + if (searchIndex >= 0) { + parsedPath.search = path.substr(searchIndex); + path = path.substr(0, searchIndex); + } + if (path) { + parsedPath.pathname = path; + } + } + return parsedPath; + } + function getUrlBasedHistory(getLocation, createHref, validateLocation, options) { + if (options === void 0) { + options = {}; + } + let { + window = document.defaultView, + v5Compat = false + } = options; + let globalHistory = window.history; + let action = Action.Pop; + let listener = null; + let index = getIndex(); + // Index should only be null when we initialize. If not, it's because the + // user called history.pushState or history.replaceState directly, in which + // case we should log a warning as it will result in bugs. + if (index == null) { + index = 0; + globalHistory.replaceState(_extends({}, globalHistory.state, { + idx: index + }), ""); + } + function getIndex() { + let state = globalHistory.state || { + idx: null + }; + return state.idx; + } + function handlePop() { + action = Action.Pop; + let nextIndex = getIndex(); + let delta = nextIndex == null ? null : nextIndex - index; + index = nextIndex; + if (listener) { + listener({ + action, + location: history.location, + delta + }); + } + } + function push(to, state) { + action = Action.Push; + let location = createLocation(history.location, to, state); + if (validateLocation) validateLocation(location, to); + index = getIndex() + 1; + let historyState = getHistoryState(location, index); + let url = history.createHref(location); + + // try...catch because iOS limits us to 100 pushState calls :/ + try { + globalHistory.pushState(historyState, "", url); + } catch (error) { + // If the exception is because `state` can't be serialized, let that throw + // outwards just like a replace call would so the dev knows the cause + // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps + // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal + if (error instanceof DOMException && error.name === "DataCloneError") { + throw error; + } + // They are going to lose state here, but there is no real + // way to warn them about it since the page will refresh... + window.location.assign(url); + } + if (v5Compat && listener) { + listener({ + action, + location: history.location, + delta: 1 + }); + } + } + function replace(to, state) { + action = Action.Replace; + let location = createLocation(history.location, to, state); + if (validateLocation) validateLocation(location, to); + index = getIndex(); + let historyState = getHistoryState(location, index); + let url = history.createHref(location); + globalHistory.replaceState(historyState, "", url); + if (v5Compat && listener) { + listener({ + action, + location: history.location, + delta: 0 + }); + } + } + function createURL(to) { + // window.location.origin is "null" (the literal string value) in Firefox + // under certain conditions, notably when serving from a local HTML file + // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297 + let base = window.location.origin !== "null" ? window.location.origin : window.location.href; + let href = typeof to === "string" ? to : createPath(to); + invariant(base, "No window.location.(origin|href) available to create URL for href: " + href); + return new URL(href, base); + } + let history = { + get action() { + return action; + }, + get location() { + return getLocation(window, globalHistory); + }, + listen(fn) { + if (listener) { + throw new Error("A history only accepts one active listener"); + } + window.addEventListener(PopStateEventType, handlePop); + listener = fn; + return () => { + window.removeEventListener(PopStateEventType, handlePop); + listener = null; + }; + }, + createHref(to) { + return createHref(window, to); + }, + createURL, + encodeLocation(to) { + // Encode a Location the same way window.location would + let url = createURL(to); + return { + pathname: url.pathname, + search: url.search, + hash: url.hash + }; + }, + push, + replace, + go(n) { + return globalHistory.go(n); + } + }; + return history; + } + + //#endregion + + /** + * Map of routeId -> data returned from a loader/action/error + */ + + let ResultType = /*#__PURE__*/function (ResultType) { + ResultType["data"] = "data"; + ResultType["deferred"] = "deferred"; + ResultType["redirect"] = "redirect"; + ResultType["error"] = "error"; + return ResultType; + }({}); + + /** + * Successful result from a loader or action + */ + + /** + * Successful defer() result from a loader or action + */ + + /** + * Redirect result from a loader or action + */ + + /** + * Unsuccessful result from a loader or action + */ + + /** + * Result from a loader or action - potentially successful or unsuccessful + */ + + /** + * Users can specify either lowercase or uppercase form methods on ``, + * useSubmit(), ``, etc. + */ + + /** + * Active navigation/fetcher form methods are exposed in lowercase on the + * RouterState + */ + + /** + * In v7, active navigation/fetcher form methods are exposed in uppercase on the + * RouterState. This is to align with the normalization done via fetch(). + */ + + // Thanks https://github.com/sindresorhus/type-fest! + + /** + * @private + * Internal interface to pass around for action submissions, not intended for + * external consumption + */ + + /** + * @private + * Arguments passed to route loader/action functions. Same for now but we keep + * this as a private implementation detail in case they diverge in the future. + */ + + // TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers: + // ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs + // Also, make them a type alias instead of an interface + /** + * Arguments passed to loader functions + */ + /** + * Arguments passed to action functions + */ + /** + * Loaders and actions can return anything except `undefined` (`null` is a + * valid return value if there is no data to return). Responses are preferred + * and will ease any future migration to Remix + */ + /** + * Route loader function signature + */ + /** + * Route action function signature + */ + /** + * Arguments passed to shouldRevalidate function + */ + /** + * Route shouldRevalidate function signature. This runs after any submission + * (navigation or fetcher), so we flatten the navigation/fetcher submission + * onto the arguments. It shouldn't matter whether it came from a navigation + * or a fetcher, what really matters is the URLs and the formData since loaders + * have to re-run based on the data models that were potentially mutated. + */ + /** + * Function provided by the framework-aware layers to set `hasErrorBoundary` + * from the framework-aware `errorElement` prop + * + * @deprecated Use `mapRouteProperties` instead + */ + /** + * Function provided by the framework-aware layers to set any framework-specific + * properties from framework-agnostic properties + */ + /** + * Keys we cannot change from within a lazy() function. We spread all other keys + * onto the route. Either they're meaningful to the router, or they'll get + * ignored. + */ + const immutableRouteKeys = new Set(["lazy", "caseSensitive", "path", "id", "index", "children"]); + + /** + * lazy() function to load a route definition, which can add non-matching + * related properties to a route + */ + + /** + * Base RouteObject with common props shared by all types of routes + */ + + /** + * Index routes must not have children + */ + + /** + * Non-index routes may have children, but cannot have index + */ + + /** + * A route object represents a logical route, with (optionally) its child + * routes organized in a tree-like structure. + */ + + /** + * A data route object, which is just a RouteObject with a required unique ID + */ + + // Recursive helper for finding path parameters in the absence of wildcards + + /** + * Examples: + * "/a/b/*" -> "*" + * ":a" -> "a" + * "/a/:b" -> "b" + * "/a/blahblahblah:b" -> "b" + * "/:a/:b" -> "a" | "b" + * "/:a/b/:c/*" -> "a" | "c" | "*" + */ + + // Attempt to parse the given string segment. If it fails, then just return the + // plain string type as a default fallback. Otherwise, return the union of the + // parsed string literals that were referenced as dynamic segments in the route. + /** + * The parameters that were parsed from the URL path. + */ + /** + * A RouteMatch contains info about how a route matched a URL. + */ + function isIndexRoute(route) { + return route.index === true; + } + + // Walk the route tree generating unique IDs where necessary, so we are working + // solely with AgnosticDataRouteObject's within the Router + function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) { + if (parentPath === void 0) { + parentPath = []; + } + if (manifest === void 0) { + manifest = {}; + } + return routes.map((route, index) => { + let treePath = [...parentPath, index]; + let id = typeof route.id === "string" ? route.id : treePath.join("-"); + invariant(route.index !== true || !route.children, "Cannot specify children on an index route"); + invariant(!manifest[id], "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages"); + if (isIndexRoute(route)) { + let indexRoute = _extends({}, route, mapRouteProperties(route), { + id + }); + manifest[id] = indexRoute; + return indexRoute; + } else { + let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), { + id, + children: undefined + }); + manifest[id] = pathOrLayoutRoute; + if (route.children) { + pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest); + } + return pathOrLayoutRoute; + } + }); + } + + /** + * Matches the given routes to a location and returns the match data. + * + * @see https://reactrouter.com/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], + // Incoming pathnames are generally encoded from either window.location + // or from router.navigate, but we want to match against the unencoded + // paths in the route definitions. Memory router locations won't be + // encoded here but there also shouldn't be anything to decode so this + // should be a safe operation. This avoids needing matchRoutes to be + // history-aware. + safelyDecodeURI(pathname)); + } + return matches; + } + function convertRouteMatchToUiMatch(match, loaderData) { + let { + route, + pathname, + params + } = match; + return { + id: route.id, + pathname, + params, + data: loaderData[route.id], + handle: route.handle + }; + } + function flattenRoutes(routes, branches, parentsMeta, parentPath) { + if (branches === void 0) { + branches = []; + } + if (parentsMeta === void 0) { + parentsMeta = []; + } + if (parentPath === void 0) { + parentPath = ""; + } + let flattenRoute = (route, index, relativePath) => { + let meta = { + relativePath: relativePath === undefined ? route.path || "" : relativePath, + caseSensitive: route.caseSensitive === true, + childrenIndex: index, + route + }; + if (meta.relativePath.startsWith("/")) { + invariant(meta.relativePath.startsWith(parentPath), "Absolute route path \"" + meta.relativePath + "\" nested under path " + ("\"" + parentPath + "\" is not valid. An absolute child route path ") + "must start with the combined path of all its parent routes."); + meta.relativePath = meta.relativePath.slice(parentPath.length); + } + let path = joinPaths([parentPath, meta.relativePath]); + let routesMeta = parentsMeta.concat(meta); + + // Add the children before adding this route to the array, so we traverse the + // route tree depth-first and child routes appear before their parents in + // the "flattened" version. + if (route.children && route.children.length > 0) { + invariant( + // Our types know better, but runtime JS may not! + // @ts-expect-error + route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\".")); + flattenRoutes(route.children, branches, routesMeta, path); + } + + // Routes without a path shouldn't ever match by themselves unless they are + // index routes, so don't add them to the list of possible branches. + if (route.path == null && !route.index) { + return; + } + branches.push({ + path, + score: computeScore(path, route.index), + routesMeta + }); + }; + routes.forEach((route, index) => { + var _route$path; + // coarse-grain check for optional params + if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) { + flattenRoute(route, index); + } else { + for (let exploded of explodeOptionalSegments(route.path)) { + flattenRoute(route, index, exploded); + } + } + }); + return branches; + } + + /** + * Computes all combinations of optional path segments for a given path, + * excluding combinations that are ambiguous and of lower priority. + * + * For example, `/one/:two?/three/:four?/:five?` explodes to: + * - `/one/three` + * - `/one/:two/three` + * - `/one/three/:four` + * - `/one/three/:five` + * - `/one/:two/three/:four` + * - `/one/:two/three/:five` + * - `/one/three/:four/:five` + * - `/one/:two/three/:four/:five` + */ + function explodeOptionalSegments(path) { + let segments = path.split("/"); + if (segments.length === 0) return []; + let [first, ...rest] = segments; + + // Optional path segments are denoted by a trailing `?` + let isOptional = first.endsWith("?"); + // Compute the corresponding required segment: `foo?` -> `foo` + let required = first.replace(/\?$/, ""); + if (rest.length === 0) { + // Intepret empty string as omitting an optional segment + // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three` + return isOptional ? [required, ""] : [required]; + } + let restExploded = explodeOptionalSegments(rest.join("/")); + let result = []; + + // All child paths with the prefix. Do this for all children before the + // optional version for all children, so we get consistent ordering where the + // parent optional aspect is preferred as required. Otherwise, we can get + // child sections interspersed where deeper optional segments are higher than + // parent optional segments, where for example, /:two would explode _earlier_ + // then /:one. By always including the parent as required _for all children_ + // first, we avoid this issue + result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/"))); + + // Then, if this is an optional value, add all child versions without + if (isOptional) { + result.push(...restExploded); + } + + // for absolute paths, ensure `/` instead of empty segment + return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded); + } + function rankRouteBranches(branches) { + branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first + : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex))); + } + const paramRe = /^:[\w-]+$/; + const dynamicSegmentValue = 3; + const indexRouteValue = 2; + const emptySegmentValue = 1; + const staticSegmentValue = 10; + const splatPenalty = -2; + const isSplat = s => s === "*"; + function computeScore(path, index) { + let segments = path.split("/"); + let initialScore = segments.length; + if (segments.some(isSplat)) { + initialScore += splatPenalty; + } + if (index) { + initialScore += indexRouteValue; + } + return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore); + } + function compareIndexes(a, b) { + let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]); + return siblings ? + // If two routes are siblings, we should try to match the earlier sibling + // first. This allows people to have fine-grained control over the matching + // behavior by simply putting routes with identical paths in the order they + // want them tried. + a[a.length - 1] - b[b.length - 1] : + // Otherwise, it doesn't really make sense to rank non-siblings by index, + // so they sort equally. + 0; + } + function matchRouteBranch(branch, pathname) { + 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/utils/generate-path + */ + function generatePath(originalPath, params) { + if (params === void 0) { + params = {}; + } + let path = originalPath; + if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) { + warning(false, "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); + path = path.replace(/\*$/, "/*"); + } + + // ensure `/` is added at the beginning if the path is absolute + const prefix = path.startsWith("/") ? "/" : ""; + const stringify = p => p == null ? "" : typeof p === "string" ? p : String(p); + const segments = path.split(/\/+/).map((segment, index, array) => { + const isLastSegment = index === array.length - 1; + + // only apply the splat if it's the last segment + if (isLastSegment && segment === "*") { + const star = "*"; + // Apply the splat + return stringify(params[star]); + } + const keyMatch = segment.match(/^:([\w-]+)(\??)$/); + if (keyMatch) { + const [, key, optional] = keyMatch; + let param = params[key]; + invariant(optional === "?" || param != null, "Missing \":" + key + "\" param"); + return stringify(param); + } + + // Remove any optional markers from optional static segments + return segment.replace(/\?$/g, ""); + }) + // Remove empty segments + .filter(segment => !!segment); + return prefix + segments.join("/"); + } + + /** + * A PathPattern is used to match on some portion of a URL pathname. + */ + + /** + * A PathMatch contains info about how a PathPattern matched on a URL pathname. + */ + + /** + * Performs pattern matching on a URL pathname and returns information about + * the match. + * + * @see https://reactrouter.com/utils/match-path + */ + function matchPath(pattern, pathname) { + if (typeof pattern === "string") { + pattern = { + path: pattern, + caseSensitive: false, + end: true + }; + } + let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end); + let match = pathname.match(matcher); + if (!match) return null; + let matchedPathname = match[0]; + let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1"); + let captureGroups = match.slice(1); + let params = compiledParams.reduce((memo, _ref, index) => { + let { + paramName, + isOptional + } = _ref; + // We need to compute the pathnameBase here using the raw splat value + // instead of using params["*"] later because it will be decoded then + if (paramName === "*") { + let splatValue = captureGroups[index] || ""; + pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1"); + } + const value = captureGroups[index]; + if (isOptional && !value) { + memo[paramName] = undefined; + } else { + memo[paramName] = safelyDecodeURIComponent(value || "", paramName); + } + return memo; + }, {}); + return { + params, + pathname: matchedPathname, + pathnameBase, + pattern + }; + } + function compilePath(path, caseSensitive, end) { + if (caseSensitive === void 0) { + caseSensitive = false; + } + if (end === void 0) { + end = true; + } + warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "Route path \"" + path + "\" will be treated as if it were " + ("\"" + path.replace(/\*$/, "/*") + "\" because the `*` character must ") + "always follow a `/` in the pattern. To get rid of this warning, " + ("please change the route path to \"" + path.replace(/\*$/, "/*") + "\".")); + let params = []; + let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below + .replace(/^\/*/, "/") // Make sure it has a leading / + .replace(/[\\.*+^${}|()[\]]/g, "\\$&") // Escape special regex chars + .replace(/\/:([\w-]+)(\?)?/g, (_, paramName, isOptional) => { + params.push({ + paramName, + isOptional: isOptional != null + }); + return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)"; + }); + if (path.endsWith("*")) { + params.push({ + paramName: "*" + }); + regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest + : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"] + } else if (end) { + // When matching to the end, ignore trailing slashes + regexpSource += "\\/*$"; + } else if (path !== "" && path !== "/") { + // If our path is non-empty and contains anything beyond an initial slash, + // then we have _some_ form of path in our regex, so we should expect to + // match only if we find the end of this path segment. Look for an optional + // non-captured trailing slash (to match a portion of the URL) or the end + // of the path (if we've matched to the end). We used to do this with a + // word boundary but that gives false positives on routes like + // /user-preferences since `-` counts as a word boundary. + regexpSource += "(?:(?=\\/|$))"; + } else ; + let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i"); + return [matcher, params]; + } + function safelyDecodeURI(value) { + try { + return decodeURI(value); + } catch (error) { + warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ").")); + return value; + } + } + function safelyDecodeURIComponent(value, paramName) { + try { + return decodeURIComponent(value); + } catch (error) { + warning(false, "The value for the URL param \"" + paramName + "\" will not be decoded because" + (" the string \"" + value + "\" is a malformed URL segment. This is probably") + (" due to a bad percent encoding (" + error + ").")); + return value; + } + } + + /** + * @private + */ + function stripBasename(pathname, basename) { + if (basename === "/") return pathname; + if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) { + return null; + } + + // We want to leave trailing slash behavior in the user's control, so if they + // specify a basename with a trailing slash, we should support it + let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length; + let nextChar = pathname.charAt(startIndex); + if (nextChar && nextChar !== "/") { + // pathname does not start with basename/ + return null; + } + return pathname.slice(startIndex) || "/"; + } + + /** + * Returns a resolved path object relative to the given pathname. + * + * @see https://reactrouter.com/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 + * + * When processing relative navigation we want to ignore ancestor routes that + * do not contribute to the path, such that index/pathless layout routes don't + * interfere. + * + * For example, when moving a route element into an index route and/or a + * pathless layout route, relative link behavior contained within should stay + * the same. Both of the following examples should link back to the root: + * + * + * + * + * + * + * + * }> // <-- Does not contribute + * // <-- Does not contribute + * + * + */ + function getPathContributingMatches(matches) { + return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0); + } + + // Return the array of pathnames for the current route matches - used to + // generate the routePathnames input for resolveTo() + function getResolveToMatches(matches, v7_relativeSplatPath) { + let pathMatches = getPathContributingMatches(matches); + + // When v7_relativeSplatPath is enabled, use the full pathname for the leaf + // match so we include splat values for "." links. See: + // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329 + if (v7_relativeSplatPath) { + return pathMatches.map((match, idx) => idx === matches.length - 1 ? match.pathname : match.pathnameBase); + } + return pathMatches.map(match => match.pathnameBase); + } + + /** + * @private + */ + function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) { + if (isPathRelative === void 0) { + isPathRelative = false; + } + let to; + if (typeof toArg === "string") { + to = parsePath(toArg); + } else { + to = _extends({}, toArg); + invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to)); + invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to)); + invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to)); + } + let isEmptyPath = toArg === "" || to.pathname === ""; + let toPathname = isEmptyPath ? "/" : to.pathname; + let from; + + // Routing is relative to the current pathname if explicitly requested. + // + // If a pathname is explicitly provided in `to`, it should be relative to the + // route context. This is explained in `Note on `` values` in our + // migration guide from v5 as a means of disambiguation between `to` values + // that begin with `/` and those that do not. However, this is problematic for + // `to` values that do not provide a pathname. `to` can simply be a search or + // hash string, in which case we should assume that the navigation is relative + // to the current location's pathname and *not* the route pathname. + if (toPathname == null) { + from = locationPathname; + } else { + let routePathnameIndex = routePathnames.length - 1; + + // With relative="route" (the default), each leading .. segment means + // "go up one route" instead of "go up one URL segment". This is a key + // difference from how works and a major reason we call this a + // "to" value instead of a "href". + if (!isPathRelative && toPathname.startsWith("..")) { + let toSegments = toPathname.split("/"); + while (toSegments[0] === "..") { + toSegments.shift(); + routePathnameIndex -= 1; + } + to.pathname = toSegments.join("/"); + } + from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/"; + } + let path = resolvePath(to, from); + + // Ensure the pathname has a trailing slash if the original "to" had one + let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); + // Or if this was a link to the current path which has a trailing slash + let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/"); + if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) { + path.pathname += "/"; + } + return path; + } + + /** + * @private + */ + function getToPathname(to) { + // Empty strings should be treated the same as / paths + return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname; + } + + /** + * @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, responseInit) { + this.pendingKeysSet = new Set(); + this.subscribers = new Set(); + this.deferredKeys = []; + invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects"); + + // Set up an AbortController + Promise we can race against to exit early + // cancellation + let reject; + this.abortPromise = new Promise((_, r) => reject = r); + this.controller = new AbortController(); + let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted")); + this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort); + this.controller.signal.addEventListener("abort", onAbort); + this.data = Object.entries(data).reduce((acc, _ref2) => { + let [key, value] = _ref2; + return Object.assign(acc, { + [key]: this.trackPromise(key, value) + }); + }, {}); + if (this.done) { + // All incoming values were resolved + this.unlistenAbortSignal(); + } + this.init = responseInit; + } + trackPromise(key, value) { + if (!(value instanceof Promise)) { + return value; + } + this.deferredKeys.push(key); + this.pendingKeysSet.add(key); + + // We store a little wrapper promise that will be extended with + // _data/_error props upon resolve/reject + let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error)); + + // Register rejection listeners to avoid uncaught promise rejections on + // errors or aborted deferred values + promise.catch(() => {}); + Object.defineProperty(promise, "_tracked", { + get: () => true + }); + return promise; + } + onSettle(promise, key, error, data) { + if (this.controller.signal.aborted && error instanceof AbortedDeferredError) { + this.unlistenAbortSignal(); + Object.defineProperty(promise, "_error", { + get: () => error + }); + return Promise.reject(error); + } + this.pendingKeysSet.delete(key); + if (this.done) { + // Nothing left to abort! + this.unlistenAbortSignal(); + } + + // If the promise was resolved/rejected with undefined, we'll throw an error as you + // should always resolve with a value or null + if (error === undefined && data === undefined) { + let undefinedError = new Error("Deferred data for key \"" + key + "\" resolved/rejected with `undefined`, " + "you must resolve/reject with a value or `null`."); + Object.defineProperty(promise, "_error", { + get: () => undefinedError + }); + this.emit(false, key); + return Promise.reject(undefinedError); + } + if (data === undefined) { + Object.defineProperty(promise, "_error", { + get: () => error + }); + this.emit(false, key); + return Promise.reject(error); + } + Object.defineProperty(promise, "_data", { + get: () => data + }); + this.emit(false, key); + return data; + } + emit(aborted, settledKey) { + this.subscribers.forEach(subscriber => subscriber(aborted, settledKey)); + } + subscribe(fn) { + this.subscribers.add(fn); + return () => this.subscribers.delete(fn); + } + cancel() { + this.controller.abort(); + this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k)); + this.emit(true); + } + async resolveData(signal) { + let aborted = false; + if (!this.done) { + let onAbort = () => this.cancel(); + signal.addEventListener("abort", onAbort); + aborted = await new Promise(resolve => { + this.subscribe(aborted => { + signal.removeEventListener("abort", onAbort); + if (aborted || this.done) { + resolve(aborted); + } + }); + }); + } + return aborted; + } + get done() { + return this.pendingKeysSet.size === 0; + } + get unwrappedData() { + invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds"); + return Object.entries(this.data).reduce((acc, _ref3) => { + let [key, value] = _ref3; + return Object.assign(acc, { + [key]: unwrapTrackedPromise(value) + }); + }, {}); + } + get pendingKeys() { + return Array.from(this.pendingKeysSet); + } + } + function isTrackedPromise(value) { + return value instanceof Promise && value._tracked === true; + } + function unwrapTrackedPromise(value) { + if (!isTrackedPromise(value)) { + return value; + } + if (value._error) { + throw value._error; + } + return value._data; + } + const defer = function defer(data, init) { + if (init === void 0) { + init = {}; + } + let responseInit = typeof init === "number" ? { + status: init + } : init; + return new DeferredData(data, responseInit); + }; + /** + * A redirect response. Sets the status code and the `Location` header. + * Defaults to "302 Found". + */ + const redirect = function redirect(url, init) { + if (init === void 0) { + init = 302; + } + let responseInit = init; + if (typeof responseInit === "number") { + responseInit = { + status: responseInit + }; + } else if (typeof responseInit.status === "undefined") { + responseInit.status = 302; + } + let headers = new Headers(responseInit.headers); + headers.set("Location", url); + return new Response(null, _extends({}, responseInit, { + headers + })); + }; + + /** + * A redirect response that will force a document reload to the new location. + * Sets the status code and the `Location` header. + * Defaults to "302 Found". + */ + const redirectDocument = (url, init) => { + let response = redirect(url, init); + response.headers.set("X-Remix-Reload-Document", "true"); + return response; + }; + /** + * @private + * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies + * + * We don't export the class for public use since it's an implementation + * detail, but we export the interface above so folks can build their own + * abstractions around instances via isRouteErrorResponse() + */ + class ErrorResponseImpl { + constructor(status, statusText, data, internal) { + if (internal === void 0) { + internal = false; + } + this.status = status; + this.statusText = statusText || ""; + this.internal = internal; + if (data instanceof Error) { + this.data = data.toString(); + this.error = data; + } else { + this.data = data; + } + } + } + + /** + * Check if the given error is an ErrorResponse generated from a 4xx/5xx + * Response thrown from an action/loader + */ + function isRouteErrorResponse(error) { + return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error; + } + + //////////////////////////////////////////////////////////////////////////////// + //#region Types and Constants + //////////////////////////////////////////////////////////////////////////////// + + /** + * A Router instance manages all navigation and data loading/mutations + */ + /** + * State maintained internally by the router. During a navigation, all states + * reflect the the "old" location unless otherwise noted. + */ + /** + * Data that can be passed into hydrate a Router from SSR + */ + /** + * Future flags to toggle new feature behavior + */ + /** + * Initialization options for createRouter + */ + /** + * State returned from a server-side query() call + */ + /** + * A StaticHandler instance manages a singular SSR navigation/fetch event + */ + /** + * Subscriber function signature for changes to router state + */ + /** + * Function signature for determining the key to be used in scroll restoration + * for a given location + */ + /** + * Function signature for determining the current scroll position + */ + // Allowed for any navigation or fetch + // Only allowed for navigations + // Only allowed for submission navigations + /** + * Options for a navigate() call for a normal (non-submission) navigation + */ + /** + * Options for a navigate() call for a submission navigation + */ + /** + * Options to pass to navigate() for a navigation + */ + /** + * Options for a fetch() load + */ + /** + * Options for a fetch() submission + */ + /** + * Options to pass to fetch() + */ + /** + * Potential states for state.navigation + */ + /** + * Potential states for fetchers + */ + /** + * Cached info for active fetcher.load() instances so they can participate + * in revalidation + */ + /** + * Identified fetcher.load() calls that need to be revalidated + */ + /** + * Wrapper object to allow us to throw any response out from callLoaderOrAction + * for queryRouter while preserving whether or not it was thrown or returned + * from the loader/action + */ + const validMutationMethodsArr = ["post", "put", "patch", "delete"]; + const validMutationMethods = new Set(validMutationMethodsArr); + const validRequestMethodsArr = ["get", ...validMutationMethodsArr]; + const validRequestMethods = new Set(validRequestMethodsArr); + const redirectStatusCodes = new Set([301, 302, 303, 307, 308]); + const redirectPreserveMethodStatusCodes = new Set([307, 308]); + const IDLE_NAVIGATION = { + state: "idle", + location: undefined, + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined + }; + const IDLE_FETCHER = { + state: "idle", + data: undefined, + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined + }; + const IDLE_BLOCKER = { + state: "unblocked", + proceed: undefined, + reset: undefined, + location: undefined + }; + const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i; + const defaultMapRouteProperties = route => ({ + hasErrorBoundary: Boolean(route.hasErrorBoundary) + }); + const TRANSITIONS_STORAGE_KEY = "remix-router-transitions"; + + //#endregion + + //////////////////////////////////////////////////////////////////////////////// + //#region createRouter + //////////////////////////////////////////////////////////////////////////////// + + /** + * Create a router and listen to history POP navigations + */ + function createRouter(init) { + const routerWindow = init.window ? init.window : typeof window !== "undefined" ? window : undefined; + const isBrowser = typeof routerWindow !== "undefined" && typeof routerWindow.document !== "undefined" && typeof routerWindow.document.createElement !== "undefined"; + const isServer = !isBrowser; + invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter"); + let mapRouteProperties; + if (init.mapRouteProperties) { + mapRouteProperties = init.mapRouteProperties; + } else if (init.detectErrorBoundary) { + // If they are still using the deprecated version, wrap it with the new API + let detectErrorBoundary = init.detectErrorBoundary; + mapRouteProperties = route => ({ + hasErrorBoundary: detectErrorBoundary(route) + }); + } else { + mapRouteProperties = defaultMapRouteProperties; + } + + // Routes keyed by ID + let manifest = {}; + // Routes in tree format for matching + let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest); + let inFlightDataRoutes; + let basename = init.basename || "/"; + // Config driven behavior flags + let future = _extends({ + v7_fetcherPersist: false, + v7_normalizeFormMethod: false, + v7_partialHydration: false, + v7_prependBasename: false, + v7_relativeSplatPath: false + }, init.future); + // Cleanup function for history + let unlistenHistory = null; + // Externally-provided functions to call on all state changes + let subscribers = new Set(); + // Externally-provided object to hold scroll restoration locations during routing + let savedScrollPositions = null; + // Externally-provided function to get scroll restoration keys + let getScrollRestorationKey = null; + // Externally-provided function to get current scroll position + let getScrollPosition = null; + // One-time flag to control the initial hydration scroll restoration. Because + // we don't get the saved positions from until _after_ + // the initial render, we need to manually trigger a separate updateState to + // send along the restoreScrollPosition + // Set to true if we have `hydrationData` since we assume we were SSR'd and that + // SSR did the initial scroll restoration. + let initialScrollRestored = init.hydrationData != null; + let initialMatches = matchRoutes(dataRoutes, init.history.location, basename); + let 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 error = getInternalRouterError(404, { + pathname: init.history.location.pathname + }); + let { + matches, + route + } = getShortCircuitMatches(dataRoutes); + initialMatches = matches; + initialErrors = { + [route.id]: error + }; + } + let initialized; + let hasLazyRoutes = initialMatches.some(m => m.route.lazy); + let hasLoaders = initialMatches.some(m => m.route.loader); + if (hasLazyRoutes) { + // All initialMatches need to be loaded before we're ready. If we have lazy + // functions around still then we'll need to run them in initialize() + initialized = false; + } else if (!hasLoaders) { + // If we've got no loaders to run, then we're good to go + initialized = true; + } else if (future.v7_partialHydration) { + // If partial hydration is enabled, we're initialized so long as we were + // provided with hydrationData for every route with a loader, and no loaders + // were marked for explicit hydration + let loaderData = init.hydrationData ? init.hydrationData.loaderData : null; + let errors = init.hydrationData ? init.hydrationData.errors : null; + initialized = initialMatches.every(m => m.route.loader && m.route.loader.hydrate !== true && (loaderData && loaderData[m.route.id] !== undefined || errors && errors[m.route.id] !== undefined)); + } else { + // Without partial hydration - we're initialized if we were provided any + // hydrationData - which is expected to be complete + initialized = init.hydrationData != null; + } + let router; + let state = { + historyAction: init.history.action, + location: init.history.location, + matches: initialMatches, + initialized, + navigation: IDLE_NAVIGATION, + // Don't restore on initial updateState() if we were SSR'd + restoreScrollPosition: init.hydrationData != null ? false : null, + preventScrollReset: false, + revalidation: "idle", + loaderData: init.hydrationData && init.hydrationData.loaderData || {}, + actionData: init.hydrationData && init.hydrationData.actionData || null, + errors: init.hydrationData && init.hydrationData.errors || initialErrors, + fetchers: new Map(), + blockers: new Map() + }; + + // -- Stateful internal variables to manage navigations -- + // Current navigation in progress (to be committed in completeNavigation) + let pendingAction = Action.Pop; + + // Should the current navigation prevent the scroll reset if scroll cannot + // be restored? + let pendingPreventScrollReset = false; + + // AbortController for the active navigation + let pendingNavigationController; + + // Should the current navigation enable document.startViewTransition? + let pendingViewTransitionEnabled = false; + + // Store applied view transitions so we can apply them on POP + let appliedViewTransitions = new Map(); + + // Cleanup function for persisting applied transitions to sessionStorage + let removePageHideEventListener = null; + + // We use this to avoid touching history in completeNavigation if a + // revalidation is entirely uninterrupted + let isUninterruptedRevalidation = false; + + // Use this internal flag to force revalidation of all loaders: + // - submissions (completed or interrupted) + // - useRevalidator() + // - X-Remix-Revalidate (from redirect) + let isRevalidationRequired = false; + + // Use this internal array to capture routes that require revalidation due + // to a cancelled deferred on action submission + let cancelledDeferredRoutes = []; + + // Use this internal array to capture fetcher loads that were cancelled by an + // action navigation and require revalidation + let cancelledFetcherLoads = []; + + // AbortControllers for any in-flight fetchers + let fetchControllers = new Map(); + + // Track loads based on the order in which they started + let incrementingLoadId = 0; + + // Track the outstanding pending navigation data load to be compared against + // the globally incrementing load when a fetcher load lands after a completed + // navigation + let pendingNavigationLoadId = -1; + + // Fetchers that triggered data reloads as a result of their actions + let fetchReloadIds = new Map(); + + // Fetchers that triggered redirect navigations + let fetchRedirectIds = new Set(); + + // Most recent href/match for fetcher.load calls for fetchers + let fetchLoadMatches = new Map(); + + // Ref-count mounted fetchers so we know when it's ok to clean them up + let activeFetchers = new Map(); + + // Fetchers that have requested a delete when using v7_fetcherPersist, + // they'll be officially removed after they return to idle + let deletedFetchers = new Set(); + + // Store DeferredData instances for active route matches. When a + // route loader returns defer() we stick one in here. Then, when a nested + // promise resolves we update loaderData. If a new navigation starts we + // cancel active deferreds for eliminated routes. + let activeDeferreds = new Map(); + + // Store blocker functions in a separate Map outside of router state since + // we don't need to update UI state if they change + let blockerFunctions = new Map(); + + // Flag to ignore the next history update, so we can revert the URL change on + // a POP navigation that was blocked by the user without touching router state + let ignoreNextHistoryUpdate = false; + + // Initialize the router, all side effects should be kicked off from here. + // Implemented as a Fluent API for ease of: + // let router = createRouter(init).initialize(); + function initialize() { + // If history informs us of a POP navigation, start the navigation but do not update + // state. We'll update our own state once the navigation completes + unlistenHistory = init.history.listen(_ref => { + let { + action: historyAction, + location, + delta + } = _ref; + // Ignore this event if it was just us resetting the URL from a + // blocked POP navigation + if (ignoreNextHistoryUpdate) { + ignoreNextHistoryUpdate = false; + return; + } + warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location " + "that was not created by @remix-run/router. This will fail silently in " + "production. This can happen if you are navigating outside the router " + "via `window.history.pushState`/`window.location.hash` instead of using " + "router navigation APIs. This can also happen if you are using " + "createHashRouter and the user manually changes the URL."); + let blockerKey = shouldBlockNavigation({ + currentLocation: state.location, + nextLocation: location, + historyAction + }); + if (blockerKey && delta != null) { + // Restore the URL to match the current UI, but don't update router state + ignoreNextHistoryUpdate = true; + init.history.go(delta * -1); + + // Put the blocker into a blocked state + updateBlocker(blockerKey, { + state: "blocked", + location, + proceed() { + updateBlocker(blockerKey, { + state: "proceeding", + proceed: undefined, + reset: undefined, + location + }); + // Re-do the same POP navigation we just blocked + init.history.go(delta); + }, + reset() { + let blockers = new Map(state.blockers); + blockers.set(blockerKey, IDLE_BLOCKER); + updateState({ + blockers + }); + } + }); + return; + } + return startNavigation(historyAction, location); + }); + if (isBrowser) { + // FIXME: This feels gross. How can we cleanup the lines between + // scrollRestoration/appliedTransitions persistance? + restoreAppliedTransitions(routerWindow, appliedViewTransitions); + let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions); + routerWindow.addEventListener("pagehide", _saveAppliedTransitions); + removePageHideEventListener = () => routerWindow.removeEventListener("pagehide", _saveAppliedTransitions); + } + + // Kick off initial data load if needed. Use Pop to avoid modifying history + // Note we don't do any handling of lazy here. For SPA's it'll get handled + // in the normal navigation flow. For SSR it's expected that lazy modules are + // resolved prior to router creation since we can't go into a fallbackElement + // UI for SSR'd apps + if (!state.initialized) { + startNavigation(Action.Pop, state.location, { + initialHydration: true + }); + } + return router; + } + + // Clean up a router and it's side effects + function dispose() { + if (unlistenHistory) { + unlistenHistory(); + } + if (removePageHideEventListener) { + removePageHideEventListener(); + } + subscribers.clear(); + pendingNavigationController && pendingNavigationController.abort(); + state.fetchers.forEach((_, key) => deleteFetcher(key)); + state.blockers.forEach((_, key) => deleteBlocker(key)); + } + + // Subscribe to state updates for the router + function subscribe(fn) { + subscribers.add(fn); + return () => subscribers.delete(fn); + } + + // Update our state and notify the calling context of the change + function updateState(newState, opts) { + if (opts === void 0) { + opts = {}; + } + state = _extends({}, state, newState); + + // Prep fetcher cleanup so we can tell the UI which fetcher data entries + // can be removed + let completedFetchers = []; + let deletedFetchersKeys = []; + if (future.v7_fetcherPersist) { + state.fetchers.forEach((fetcher, key) => { + if (fetcher.state === "idle") { + if (deletedFetchers.has(key)) { + // Unmounted from the UI and can be totally removed + deletedFetchersKeys.push(key); + } else { + // Returned to idle but still mounted in the UI, so semi-remains for + // revalidations and such + completedFetchers.push(key); + } + } + }); + } + + // Iterate over a local copy so that if flushSync is used and we end up + // removing and adding a new subscriber due to the useCallback dependencies, + // we don't get ourselves into a loop calling the new subscriber immediately + [...subscribers].forEach(subscriber => subscriber(state, { + deletedFetchers: deletedFetchersKeys, + unstable_viewTransitionOpts: opts.viewTransitionOpts, + unstable_flushSync: opts.flushSync === true + })); + + // Remove idle fetchers from state since we only care about in-flight fetchers. + if (future.v7_fetcherPersist) { + completedFetchers.forEach(key => state.fetchers.delete(key)); + deletedFetchersKeys.forEach(key => deleteFetcher(key)); + } + } + + // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION + // and setting state.[historyAction/location/matches] to the new route. + // - Location is a required param + // - Navigation will always be set to IDLE_NAVIGATION + // - Can pass any other state in newState + function completeNavigation(location, newState, _temp) { + var _location$state, _location$state2; + let { + flushSync + } = _temp === void 0 ? {} : _temp; + // Deduce if we're in a loading/actionReload state: + // - We have committed actionData in the store + // - The current navigation was a mutation submission + // - We're past the submitting state and into the loading state + // - The location being loaded is not the result of a redirect + let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true; + let actionData; + if (newState.actionData) { + if (Object.keys(newState.actionData).length > 0) { + actionData = newState.actionData; + } else { + // Empty actionData -> clear prior actionData due to an action error + actionData = null; + } + } else if (isActionReload) { + // Keep the current data if we're wrapping up the action reload + actionData = state.actionData; + } else { + // Clear actionData on any other completed navigations + actionData = null; + } + + // Always preserve any existing loaderData from re-used routes + let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData; + + // On a successful navigation we can assume we got through all blockers + // so we can start fresh + let blockers = state.blockers; + if (blockers.size > 0) { + blockers = new Map(blockers); + blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER)); + } + + // Always respect the user flag. Otherwise don't reset on mutation + // submission navigations unless they redirect + let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true; + if (inFlightDataRoutes) { + dataRoutes = inFlightDataRoutes; + inFlightDataRoutes = undefined; + } + if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) { + init.history.push(location, location.state); + } else if (pendingAction === Action.Replace) { + init.history.replace(location, location.state); + } + let viewTransitionOpts; + + // On POP, enable transitions if they were enabled on the original navigation + if (pendingAction === Action.Pop) { + // Forward takes precedence so they behave like the original navigation + let priorPaths = appliedViewTransitions.get(state.location.pathname); + if (priorPaths && priorPaths.has(location.pathname)) { + viewTransitionOpts = { + currentLocation: state.location, + nextLocation: location + }; + } else if (appliedViewTransitions.has(location.pathname)) { + // If we don't have a previous forward nav, assume we're popping back to + // the new location and enable if that location previously enabled + viewTransitionOpts = { + currentLocation: location, + nextLocation: state.location + }; + } + } else if (pendingViewTransitionEnabled) { + // Store the applied transition on PUSH/REPLACE + let toPaths = appliedViewTransitions.get(state.location.pathname); + if (toPaths) { + toPaths.add(location.pathname); + } else { + toPaths = new Set([location.pathname]); + appliedViewTransitions.set(state.location.pathname, toPaths); + } + viewTransitionOpts = { + currentLocation: state.location, + nextLocation: location + }; + } + updateState(_extends({}, newState, { + // matches, errors, fetchers go through as-is + actionData, + loaderData, + historyAction: pendingAction, + location, + initialized: true, + navigation: IDLE_NAVIGATION, + revalidation: "idle", + restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches), + preventScrollReset, + blockers + }), { + viewTransitionOpts, + flushSync: flushSync === true + }); + + // Reset stateful navigation vars + pendingAction = Action.Pop; + pendingPreventScrollReset = false; + pendingViewTransitionEnabled = false; + isUninterruptedRevalidation = false; + isRevalidationRequired = false; + cancelledDeferredRoutes = []; + 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 normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative); + let { + path, + submission, + error + } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts); + let currentLocation = state.location; + let nextLocation = createLocation(state.location, path, opts && opts.state); + + // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded + // URL from window.location, so we need to encode it here so the behavior + // remains the same as POP and non-data-router usages. new URL() does all + // the same encoding we'd get from a history.pushState/window.location read + // without having to touch history + nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation)); + let userReplace = opts && opts.replace != null ? opts.replace : undefined; + let historyAction = Action.Push; + if (userReplace === true) { + historyAction = Action.Replace; + } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) { + // By default on submissions to the current location we REPLACE so that + // users don't have to double-click the back button to get to the prior + // location. If the user redirects to a different location from the + // action/loader this will be ignored and the redirect will be a PUSH + historyAction = Action.Replace; + } + let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined; + let flushSync = (opts && opts.unstable_flushSync) === true; + let blockerKey = shouldBlockNavigation({ + currentLocation, + nextLocation, + historyAction + }); + if (blockerKey) { + // Put the blocker into a blocked state + updateBlocker(blockerKey, { + state: "blocked", + location: nextLocation, + proceed() { + updateBlocker(blockerKey, { + state: "proceeding", + proceed: undefined, + reset: undefined, + location: nextLocation + }); + // Send the same navigation through + navigate(to, opts); + }, + reset() { + let blockers = new Map(state.blockers); + blockers.set(blockerKey, IDLE_BLOCKER); + updateState({ + blockers + }); + } + }); + return; + } + return await startNavigation(historyAction, nextLocation, { + submission, + // Send through the formData serialization error if we have one so we can + // render at the right error boundary after we match routes + pendingError: error, + preventScrollReset, + replace: opts && opts.replace, + enableViewTransition: opts && opts.unstable_viewTransition, + flushSync + }); + } + + // Revalidate all current loaders. If a navigation is in progress or if this + // is interrupted by a navigation, allow this to "succeed" by calling all + // loaders during the next loader round + function revalidate() { + interruptActiveLoads(); + updateState({ + revalidation: "loading" + }); + + // If we're currently submitting an action, we don't need to start a new + // navigation, we'll just let the follow up loader execution call all loaders + if (state.navigation.state === "submitting") { + return; + } + + // If we're currently in an idle state, start a new navigation for the current + // action/location and mark it as uninterrupted, which will skip the history + // update in completeNavigation + if (state.navigation.state === "idle") { + startNavigation(state.historyAction, state.location, { + startUninterruptedRevalidation: true + }); + return; + } + + // Otherwise, if we're currently in a loading state, just start a new + // navigation to the navigation.location but do not trigger an uninterrupted + // revalidation so that history correctly updates once the navigation completes + startNavigation(pendingAction || state.historyAction, state.navigation.location, { + overrideNavigation: state.navigation + }); + } + + // Start a navigation to the given action/location. Can optionally provide a + // overrideNavigation which will override the normalLoad in the case of a redirect + // navigation + async function startNavigation(historyAction, location, opts) { + // Abort any in-progress navigations and start a new one. Unset any ongoing + // uninterrupted revalidations unless told otherwise, since we want this + // new navigation to update history normally + pendingNavigationController && pendingNavigationController.abort(); + pendingNavigationController = null; + pendingAction = historyAction; + isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; + + // Save the current scroll position every time we start a new navigation, + // and track whether we should reset scroll on completion + saveScrollPosition(state.location, state.matches); + pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; + pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true; + let routesToUse = inFlightDataRoutes || dataRoutes; + let loadingNavigation = opts && opts.overrideNavigation; + let matches = matchRoutes(routesToUse, location, basename); + let flushSync = (opts && opts.flushSync) === true; + + // Short circuit with a 404 on the root error boundary if we match nothing + if (!matches) { + let error = getInternalRouterError(404, { + pathname: location.pathname + }); + let { + matches: notFoundMatches, + route + } = getShortCircuitMatches(routesToUse); + // Cancel all pending deferred on 404s since we don't keep any routes + cancelActiveDeferreds(); + completeNavigation(location, { + matches: notFoundMatches, + loaderData: {}, + errors: { + [route.id]: error + } + }, { + flushSync + }); + return; + } + + // Short circuit if it's only a hash change and not a revalidation or + // mutation submission. + // + // Ignore on initial page loads because since the initial load will always + // be "same hash". For example, on /page#hash and submit a + // which will default to a navigation to /page + if (state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) { + completeNavigation(location, { + matches + }, { + flushSync + }); + return; + } + + // Create a controller/Request for this navigation + pendingNavigationController = new AbortController(); + let request = createClientSideRequest(init.history, 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 && isMutationMethod(opts.submission.formMethod)) { + // Call action if we received an action submission + let actionOutput = await handleAction(request, location, opts.submission, matches, { + replace: opts.replace, + flushSync + }); + if (actionOutput.shortCircuited) { + return; + } + pendingActionData = actionOutput.pendingActionData; + pendingError = actionOutput.pendingActionError; + loadingNavigation = getLoadingNavigation(location, opts.submission); + flushSync = false; + + // Create a GET request for the loaders + request = new Request(request.url, { + signal: request.signal + }); + } + + // Call loaders + let { + shortCircuited, + loaderData, + errors + } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionData, pendingError); + if (shortCircuited) { + return; + } + + // Clean up now that the action/loaders have completed. Don't clean up if + // we short circuited because pendingNavigationController will have already + // been assigned to a new controller for the next navigation + pendingNavigationController = null; + completeNavigation(location, _extends({ + matches + }, pendingActionData ? { + actionData: pendingActionData + } : {}, { + 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) { + if (opts === void 0) { + opts = {}; + } + interruptActiveLoads(); + + // Put us in a submitting state + let navigation = getSubmittingNavigation(location, submission); + updateState({ + navigation + }, { + flushSync: opts.flushSync === true + }); + + // Call our action and get the result + let result; + let actionMatch = getTargetMatch(matches, location); + if (!actionMatch.route.action && !actionMatch.route.lazy) { + result = { + type: ResultType.error, + error: getInternalRouterError(405, { + method: request.method, + pathname: location.pathname, + routeId: actionMatch.route.id + }) + }; + } else { + result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); + if (request.signal.aborted) { + return { + shortCircuited: true + }; + } + } + if (isRedirectResult(result)) { + let replace; + if (opts && opts.replace != null) { + replace = opts.replace; + } else { + // If the user didn't explicity indicate replace behavior, replace if + // we redirected to the exact same location we're currently at to avoid + // double back-buttons + replace = result.location === state.location.pathname + state.location.search; + } + await startRedirectNavigation(state, result, { + submission, + 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 { + // Send back an empty object we can use to clear out any prior actionData + pendingActionData: {}, + pendingActionError: { + [boundaryMatch.route.id]: result.error + } + }; + } + if (isDeferredResult(result)) { + throw getInternalRouterError(400, { + type: "defer-action" + }); + } + return { + pendingActionData: { + [actionMatch.route.id]: result.data + } + }; + } + + // Call all applicable loaders for the given matches, handling redirects, + // errors, etc. + async function handleLoaders(request, location, matches, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionData, pendingError) { + // Figure out the right navigation we want to use for data loading + let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission); + + // If this was a redirect from an action we don't have a "submission" but + // we have it on the loading navigation so use that if available + let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation); + let routesToUse = inFlightDataRoutes || dataRoutes; + let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError); + + // Cancel pending deferreds for no-longer-matched routes or routes we're + // about to reload. Note that if this is an action reload we would have + // already cancelled all pending deferreds so this would be a no-op + cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); + pendingNavigationLoadId = ++incrementingLoadId; + + // Short circuit if we have no loaders to run + if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) { + let updatedFetchers = markFetchRedirectsDone(); + completeNavigation(location, _extends({ + matches, + loaderData: {}, + // Commit pending error if we're short circuiting + errors: pendingError || null + }, pendingActionData ? { + actionData: pendingActionData + } : {}, updatedFetchers ? { + fetchers: new Map(state.fetchers) + } : {}), { + flushSync + }); + 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 we have partialHydration enabled, then don't update the state for the + // initial data load since iot's not a "navigation" + if (!isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration)) { + revalidatingFetchers.forEach(rf => { + let fetcher = state.fetchers.get(rf.key); + let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined); + state.fetchers.set(rf.key, revalidatingFetcher); + }); + let actionData = pendingActionData || state.actionData; + updateState(_extends({ + navigation: loadingNavigation + }, actionData ? Object.keys(actionData).length === 0 ? { + actionData: null + } : { + actionData + } : {}, revalidatingFetchers.length > 0 ? { + fetchers: new Map(state.fetchers) + } : {}), { + flushSync + }); + } + revalidatingFetchers.forEach(rf => { + if (fetchControllers.has(rf.key)) { + abortFetcher(rf.key); + } + if (rf.controller) { + // Fetchers use an independent AbortController so that aborting a fetcher + // (via deleteFetcher) does not abort the triggering navigation that + // triggered the revalidation + fetchControllers.set(rf.key, rf.controller); + } + }); + + // Proxy navigation abort through to revalidation fetchers + let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key)); + if (pendingNavigationController) { + pendingNavigationController.signal.addEventListener("abort", abortPendingFetchRevalidations); + } + let { + results, + loaderResults, + fetcherResults + } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request); + if (request.signal.aborted) { + return { + shortCircuited: true + }; + } + + // Clean up _after_ loaders have completed. Don't clean up if we short + // circuited because fetchControllers would have been aborted and + // reassigned to new controllers for the next navigation + if (pendingNavigationController) { + pendingNavigationController.signal.removeEventListener("abort", abortPendingFetchRevalidations); + } + revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key)); + + // If any loaders returned a redirect Response, start a new REPLACE navigation + let redirect = findRedirect(results); + if (redirect) { + if (redirect.idx >= matchesToLoad.length) { + // If this redirect came from a fetcher make sure we mark it in + // fetchRedirectIds so it doesn't get revalidated on the next set of + // loader executions + let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; + fetchRedirectIds.add(fetcherKey); + } + await startRedirectNavigation(state, redirect.result, { + 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); + } + }); + }); + let updatedFetchers = markFetchRedirectsDone(); + let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId); + let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0; + return _extends({ + loaderData, + errors + }, shouldUpdateFetchers ? { + fetchers: new Map(state.fetchers) + } : {}); + } + + // Trigger a fetcher load/submit for the given fetcher key + function fetch(key, routeId, href, opts) { + if (isServer) { + throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback."); + } + if (fetchControllers.has(key)) abortFetcher(key); + let flushSync = (opts && opts.unstable_flushSync) === true; + let routesToUse = inFlightDataRoutes || dataRoutes; + let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative); + let matches = matchRoutes(routesToUse, normalizedPath, basename); + if (!matches) { + setFetcherError(key, routeId, getInternalRouterError(404, { + pathname: normalizedPath + }), { + flushSync + }); + return; + } + let { + path, + submission, + error + } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts); + if (error) { + setFetcherError(key, routeId, error, { + flushSync + }); + return; + } + let match = getTargetMatch(matches, path); + pendingPreventScrollReset = (opts && opts.preventScrollReset) === true; + if (submission && isMutationMethod(submission.formMethod)) { + handleFetcherAction(key, routeId, path, match, matches, flushSync, submission); + return; + } + + // Store off the match so we can call it's shouldRevalidate on subsequent + // revalidations + fetchLoadMatches.set(key, { + routeId, + path + }); + handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission); + } + + // Call the action for the matched fetcher.submit(), and then handle redirects, + // errors, and revalidation + async function handleFetcherAction(key, routeId, path, match, requestMatches, flushSync, submission) { + interruptActiveLoads(); + fetchLoadMatches.delete(key); + if (!match.route.action && !match.route.lazy) { + let error = getInternalRouterError(405, { + method: submission.formMethod, + pathname: path, + routeId: routeId + }); + setFetcherError(key, routeId, error, { + flushSync + }); + return; + } + + // Put this fetcher into it's submitting state + let existingFetcher = state.fetchers.get(key); + updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), { + flushSync + }); + + // Call the action for the fetcher + let abortController = new AbortController(); + let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission); + fetchControllers.set(key, abortController); + let originatingLoadId = incrementingLoadId; + let actionResult = await callLoaderOrAction("action", fetchRequest, match, requestMatches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); + if (fetchRequest.signal.aborted) { + // We can delete this so long as we weren't aborted by our own fetcher + // re-submit which would have put _new_ controller is in fetchControllers + if (fetchControllers.get(key) === abortController) { + fetchControllers.delete(key); + } + return; + } + + // When using v7_fetcherPersist, we don't want errors bubbling up to the UI + // or redirects processed for unmounted fetchers so we just revert them to + // idle + if (future.v7_fetcherPersist && deletedFetchers.has(key)) { + if (isRedirectResult(actionResult) || isErrorResult(actionResult)) { + updateFetcherState(key, getDoneFetcher(undefined)); + return; + } + // Let SuccessResult's fall through for revalidation + } else { + if (isRedirectResult(actionResult)) { + fetchControllers.delete(key); + if (pendingNavigationLoadId > originatingLoadId) { + // A new navigation was kicked off after our action started, so that + // should take precedence over this redirect navigation. We already + // set isRevalidationRequired so all loaders for the new route should + // fire unless opted out via shouldRevalidate + updateFetcherState(key, getDoneFetcher(undefined)); + return; + } else { + fetchRedirectIds.add(key); + updateFetcherState(key, getLoadingFetcher(submission)); + return startRedirectNavigation(state, actionResult, { + fetcherSubmission: submission + }); + } + } + + // Process any non-redirect errors thrown + if (isErrorResult(actionResult)) { + setFetcherError(key, routeId, actionResult.error); + return; + } + } + if (isDeferredResult(actionResult)) { + throw getInternalRouterError(400, { + type: "defer-action" + }); + } + + // Start the data load for current matches, or the next location if we're + // in the middle of a navigation + let nextLocation = state.navigation.location || state.location; + let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal); + let routesToUse = inFlightDataRoutes || dataRoutes; + let matches = state.navigation.state !== "idle" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches; + invariant(matches, "Didn't find any matches after fetcher action"); + let loadId = ++incrementingLoadId; + fetchReloadIds.set(key, loadId); + let loadFetcher = getLoadingFetcher(submission, actionResult.data); + state.fetchers.set(key, loadFetcher); + let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, { + [match.route.id]: actionResult.data + }, undefined // No need to send through errors since we short circuit above + ); + + // Put all revalidating fetchers into the loading state, except for the + // current fetcher which we want to keep in it's current loading state which + // contains it's action submission info + action data + revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => { + let staleKey = rf.key; + let existingFetcher = state.fetchers.get(staleKey); + let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined); + state.fetchers.set(staleKey, revalidatingFetcher); + if (fetchControllers.has(staleKey)) { + abortFetcher(staleKey); + } + if (rf.controller) { + fetchControllers.set(staleKey, rf.controller); + } + }); + updateState({ + fetchers: new Map(state.fetchers) + }); + let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key)); + abortController.signal.addEventListener("abort", abortPendingFetchRevalidations); + let { + results, + loaderResults, + fetcherResults + } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest); + if (abortController.signal.aborted) { + return; + } + abortController.signal.removeEventListener("abort", abortPendingFetchRevalidations); + fetchReloadIds.delete(key); + fetchControllers.delete(key); + revalidatingFetchers.forEach(r => fetchControllers.delete(r.key)); + let redirect = findRedirect(results); + if (redirect) { + if (redirect.idx >= matchesToLoad.length) { + // If this redirect came from a fetcher make sure we mark it in + // fetchRedirectIds so it doesn't get revalidated on the next set of + // loader executions + let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key; + fetchRedirectIds.add(fetcherKey); + } + return startRedirectNavigation(state, redirect.result); + } + + // Process and commit output from loaders + let { + loaderData, + errors + } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds); + + // Since we let revalidations complete even if the submitting fetcher was + // deleted, only put it back to idle if it hasn't been deleted + if (state.fetchers.has(key)) { + let doneFetcher = getDoneFetcher(actionResult.data); + state.fetchers.set(key, doneFetcher); + } + abortStaleFetchLoads(loadId); + + // If we are currently in a navigation loading state and this fetcher is + // more recent than the navigation, we want the newer data so abort the + // navigation and complete it with the fetcher data + if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) { + invariant(pendingAction, "Expected pending action"); + pendingNavigationController && pendingNavigationController.abort(); + completeNavigation(state.navigation.location, { + matches, + loaderData, + errors, + fetchers: new Map(state.fetchers) + }); + } else { + // otherwise just update with the fetcher data, preserving any existing + // loaderData for loaders that did not need to reload. We have to + // manually merge here since we aren't going through completeNavigation + updateState({ + errors, + loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors), + fetchers: new Map(state.fetchers) + }); + isRevalidationRequired = false; + } + } + + // Call the matched loader for fetcher.load(), handling redirects, errors, etc. + async function handleFetcherLoader(key, routeId, path, match, matches, flushSync, submission) { + let existingFetcher = state.fetchers.get(key); + updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), { + flushSync + }); + + // Call the loader for this fetcher route match + let abortController = new AbortController(); + let fetchRequest = createClientSideRequest(init.history, path, abortController.signal); + fetchControllers.set(key, abortController); + let originatingLoadId = incrementingLoadId; + let result = await callLoaderOrAction("loader", fetchRequest, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); + + // Deferred isn't supported for fetcher loads, await everything and treat it + // as a normal load. resolveDeferredData will return undefined if this + // fetcher gets aborted, so we just leave result untouched and short circuit + // below if that happens + if (isDeferredResult(result)) { + result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result; + } + + // We can delete this so long as we weren't aborted by our our own fetcher + // re-load which would have put _new_ controller is in fetchControllers + if (fetchControllers.get(key) === abortController) { + fetchControllers.delete(key); + } + if (fetchRequest.signal.aborted) { + return; + } + + // We don't want errors bubbling up or redirects followed for unmounted + // fetchers, so short circuit here if it was removed from the UI + if (deletedFetchers.has(key)) { + updateFetcherState(key, getDoneFetcher(undefined)); + return; + } + + // If the loader threw a redirect Response, start a new REPLACE navigation + if (isRedirectResult(result)) { + if (pendingNavigationLoadId > originatingLoadId) { + // A new navigation was kicked off after our loader started, so that + // should take precedence over this redirect navigation + updateFetcherState(key, getDoneFetcher(undefined)); + return; + } else { + fetchRedirectIds.add(key); + await startRedirectNavigation(state, result); + return; + } + } + + // Process any non-redirect errors thrown + if (isErrorResult(result)) { + setFetcherError(key, routeId, result.error); + return; + } + invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); + + // Put the fetcher back into an idle state + updateFetcherState(key, getDoneFetcher(result.data)); + } + + /** + * Utility function to handle redirects returned from an action or loader. + * Normally, a redirect "replaces" the navigation that triggered it. So, for + * example: + * + * - user is on /a + * - user clicks a link to /b + * - loader for /b redirects to /c + * + * In a non-JS app the browser would track the in-flight navigation to /b and + * then replace it with /c when it encountered the redirect response. In + * the end it would only ever update the URL bar with /c. + * + * In client-side routing using pushState/replaceState, we aim to emulate + * this behavior and we also do not update history until the end of the + * navigation (including processed redirects). This means that we never + * actually touch history until we've processed redirects, so we just use + * the history action from the original navigation (PUSH or REPLACE). + */ + async function startRedirectNavigation(state, redirect, _temp2) { + let { + submission, + fetcherSubmission, + replace + } = _temp2 === void 0 ? {} : _temp2; + if (redirect.revalidate) { + isRevalidationRequired = true; + } + let redirectLocation = createLocation(state.location, redirect.location, { + _isRedirect: true + }); + invariant(redirectLocation, "Expected a location on the redirect navigation"); + if (isBrowser) { + let isDocumentReload = false; + if (redirect.reloadDocument) { + // Hard reload if the response contained X-Remix-Reload-Document + isDocumentReload = true; + } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) { + const url = init.history.createURL(redirect.location); + isDocumentReload = + // Hard reload if it's an absolute URL to a new origin + url.origin !== routerWindow.location.origin || + // Hard reload if it's an absolute URL that does not match our basename + stripBasename(url.pathname, basename) == null; + } + if (isDocumentReload) { + if (replace) { + routerWindow.location.replace(redirect.location); + } else { + routerWindow.location.assign(redirect.location); + } + return; + } + } + + // There's no need to abort on redirects, since we don't detect the + // redirect until the action/loaders have settled + pendingNavigationController = null; + let redirectHistoryAction = replace === true ? Action.Replace : Action.Push; + + // Use the incoming submission if provided, fallback on the active one in + // state.navigation + let { + formMethod, + formAction, + formEncType + } = state.navigation; + if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) { + submission = getSubmissionFromNavigation(state.navigation); + } + + // If this was a 307/308 submission we want to preserve the HTTP method and + // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the + // redirected location + let activeSubmission = submission || fetcherSubmission; + if (redirectPreserveMethodStatusCodes.has(redirect.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) { + await startNavigation(redirectHistoryAction, redirectLocation, { + submission: _extends({}, activeSubmission, { + formAction: redirect.location + }), + // Preserve this flag across redirects + preventScrollReset: pendingPreventScrollReset + }); + } else { + // If we have a navigation submission, we will preserve it through the + // redirect navigation + let overrideNavigation = getLoadingNavigation(redirectLocation, submission); + await startNavigation(redirectHistoryAction, redirectLocation, { + overrideNavigation, + // Send fetcher submissions through for shouldRevalidate + fetcherSubmission, + // Preserve this flag across redirects + preventScrollReset: pendingPreventScrollReset + }); + } + } + async function callLoadersAndMaybeResolveData(currentMatches, matches, 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(match => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath)), ...fetchersToLoad.map(f => { + if (f.matches && f.match && f.controller) { + return callLoaderOrAction("loader", createClientSideRequest(init.history, f.path, f.controller.signal), f.match, f.matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath); + } else { + let error = { + type: ResultType.error, + error: getInternalRouterError(404, { + pathname: f.path + }) + }; + return error; + } + })]); + let loaderResults = results.slice(0, matchesToLoad.length); + let fetcherResults = results.slice(matchesToLoad.length); + await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, loaderResults.map(() => request.signal), false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(f => f.match), fetcherResults, fetchersToLoad.map(f => f.controller ? f.controller.signal : null), 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 updateFetcherState(key, fetcher, opts) { + if (opts === void 0) { + opts = {}; + } + state.fetchers.set(key, fetcher); + updateState({ + fetchers: new Map(state.fetchers) + }, { + flushSync: (opts && opts.flushSync) === true + }); + } + function setFetcherError(key, routeId, error, opts) { + if (opts === void 0) { + opts = {}; + } + let boundaryMatch = findNearestBoundary(state.matches, routeId); + deleteFetcher(key); + updateState({ + errors: { + [boundaryMatch.route.id]: error + }, + fetchers: new Map(state.fetchers) + }, { + flushSync: (opts && opts.flushSync) === true + }); + } + function getFetcher(key) { + if (future.v7_fetcherPersist) { + activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1); + // If this fetcher was previously marked for deletion, unmark it since we + // have a new instance + if (deletedFetchers.has(key)) { + deletedFetchers.delete(key); + } + } + return state.fetchers.get(key) || IDLE_FETCHER; + } + function deleteFetcher(key) { + let fetcher = state.fetchers.get(key); + // Don't abort the controller if this is a deletion of a fetcher.submit() + // in it's loading phase since - we don't want to abort the corresponding + // revalidation and want them to complete and land + if (fetchControllers.has(key) && !(fetcher && fetcher.state === "loading" && fetchReloadIds.has(key))) { + abortFetcher(key); + } + fetchLoadMatches.delete(key); + fetchReloadIds.delete(key); + fetchRedirectIds.delete(key); + deletedFetchers.delete(key); + state.fetchers.delete(key); + } + function deleteFetcherAndUpdateState(key) { + if (future.v7_fetcherPersist) { + let count = (activeFetchers.get(key) || 0) - 1; + if (count <= 0) { + activeFetchers.delete(key); + deletedFetchers.add(key); + } else { + activeFetchers.set(key, count); + } + } else { + deleteFetcher(key); + } + updateState({ + fetchers: new Map(state.fetchers) + }); + } + function abortFetcher(key) { + let controller = fetchControllers.get(key); + invariant(controller, "Expected fetch controller: " + key); + controller.abort(); + fetchControllers.delete(key); + } + function markFetchersDone(keys) { + for (let key of keys) { + let fetcher = getFetcher(key); + let doneFetcher = getDoneFetcher(fetcher.data); + state.fetchers.set(key, doneFetcher); + } + } + function markFetchRedirectsDone() { + let doneKeys = []; + let updatedFetchers = false; + for (let key of fetchRedirectIds) { + let fetcher = state.fetchers.get(key); + invariant(fetcher, "Expected fetcher: " + key); + if (fetcher.state === "loading") { + fetchRedirectIds.delete(key); + doneKeys.push(key); + updatedFetchers = true; + } + } + markFetchersDone(doneKeys); + return updatedFetchers; + } + function abortStaleFetchLoads(landedId) { + let yeetedKeys = []; + for (let [key, id] of fetchReloadIds) { + if (id < landedId) { + let fetcher = state.fetchers.get(key); + invariant(fetcher, "Expected fetcher: " + key); + if (fetcher.state === "loading") { + abortFetcher(key); + fetchReloadIds.delete(key); + yeetedKeys.push(key); + } + } + } + markFetchersDone(yeetedKeys); + return yeetedKeys.length > 0; + } + function getBlocker(key, fn) { + let blocker = state.blockers.get(key) || IDLE_BLOCKER; + if (blockerFunctions.get(key) !== fn) { + blockerFunctions.set(key, fn); + } + return blocker; + } + function deleteBlocker(key) { + state.blockers.delete(key); + blockerFunctions.delete(key); + } + + // Utility function to update blockers, ensuring valid state transitions + function updateBlocker(key, newBlocker) { + let blocker = state.blockers.get(key) || IDLE_BLOCKER; + + // Poor mans state machine :) + // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM + invariant(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state); + let blockers = new Map(state.blockers); + blockers.set(key, newBlocker); + updateState({ + blockers + }); + } + function shouldBlockNavigation(_ref2) { + let { + currentLocation, + nextLocation, + historyAction + } = _ref2; + if (blockerFunctions.size === 0) { + return; + } + + // We ony support a single active blocker at the moment since we don't have + // any compelling use cases for multi-blocker yet + if (blockerFunctions.size > 1) { + warning(false, "A router only supports one blocker at a time"); + } + let entries = Array.from(blockerFunctions.entries()); + let [blockerKey, blockerFunction] = entries[entries.length - 1]; + let blocker = state.blockers.get(blockerKey); + if (blocker && blocker.state === "proceeding") { + // If the blocker is currently proceeding, we don't need to re-check + // it and can let this navigation continue + return; + } + + // At this point, we know we're unblocked/blocked so we need to check the + // user-provided blocker function + if (blockerFunction({ + currentLocation, + nextLocation, + historyAction + })) { + return blockerKey; + } + } + function 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 || null; + + // 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 getScrollKey(location, matches) { + if (getScrollRestorationKey) { + let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData))); + return key || location.key; + } + return location.key; + } + function saveScrollPosition(location, matches) { + if (savedScrollPositions && getScrollPosition) { + let key = getScrollKey(location, matches); + savedScrollPositions[key] = getScrollPosition(); + } + } + function getSavedScrollPosition(location, matches) { + if (savedScrollPositions) { + let key = getScrollKey(location, matches); + let y = savedScrollPositions[key]; + if (typeof y === "number") { + return y; + } + } + return null; + } + function _internalSetRoutes(newRoutes) { + manifest = {}; + inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest); + } + router = { + get basename() { + return basename; + }, + get future() { + return future; + }, + get state() { + return state; + }, + get routes() { + return dataRoutes; + }, + get window() { + return routerWindow; + }, + initialize, + subscribe, + enableScrollRestoration, + navigate, + fetch, + revalidate, + // Passthrough to history-aware createHref used by useHref so we get proper + // hash-aware URLs in DOM paths + createHref: to => init.history.createHref(to), + encodeLocation: to => init.history.encodeLocation(to), + getFetcher, + deleteFetcher: deleteFetcherAndUpdateState, + dispose, + getBlocker, + deleteBlocker, + _internalFetchControllers: fetchControllers, + _internalActiveDeferreds: activeDeferreds, + // TODO: Remove setRoutes, it's temporary to avoid dealing with + // updating the tree while validating the update algorithm. + _internalSetRoutes + }; + return router; + } + //#endregion + + //////////////////////////////////////////////////////////////////////////////// + //#region createStaticHandler + //////////////////////////////////////////////////////////////////////////////// + + const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred"); + + /** + * Future flags to toggle new feature behavior + */ + + function createStaticHandler(routes, opts) { + invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler"); + let manifest = {}; + let basename = (opts ? opts.basename : null) || "/"; + let mapRouteProperties; + if (opts != null && opts.mapRouteProperties) { + mapRouteProperties = opts.mapRouteProperties; + } else if (opts != null && opts.detectErrorBoundary) { + // If they are still using the deprecated version, wrap it with the new API + let detectErrorBoundary = opts.detectErrorBoundary; + mapRouteProperties = route => ({ + hasErrorBoundary: detectErrorBoundary(route) + }); + } else { + mapRouteProperties = defaultMapRouteProperties; + } + // Config driven behavior flags + let future = _extends({ + v7_relativeSplatPath: false + }, opts ? opts.future : null); + let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest); + + /** + * The query() method is intended for document requests, in which we want to + * call an optional action and potentially multiple loaders for all nested + * routes. It returns a StaticHandlerContext object, which is very similar + * to the router state (location, loaderData, actionData, errors, etc.) and + * also adds SSR-specific information such as the statusCode and headers + * from action/loaders Responses. + * + * It _should_ never throw and should report all errors through the + * returned context.errors object, properly associating errors to their error + * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be + * used to emulate React error boundaries during SSr by performing a second + * pass only down to the boundaryId. + * + * The one exception where we do not return a StaticHandlerContext is when a + * redirect response is returned or thrown from any action/loader. We + * propagate that out and return the raw Response so the HTTP server can + * return it directly. + */ + async function query(request, _temp3) { + let { + requestContext + } = _temp3 === void 0 ? {} : _temp3; + let url = new URL(request.url); + let method = request.method; + let location = createLocation("", createPath(url), null, "default"); + let matches = matchRoutes(dataRoutes, location, basename); + + // SSR supports HEAD requests while SPA doesn't + if (!isValidMethod(method) && method !== "HEAD") { + let error = getInternalRouterError(405, { + method + }); + let { + matches: methodNotAllowedMatches, + route + } = getShortCircuitMatches(dataRoutes); + return { + basename, + location, + matches: methodNotAllowedMatches, + loaderData: {}, + actionData: null, + errors: { + [route.id]: error + }, + statusCode: error.status, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } else if (!matches) { + let error = getInternalRouterError(404, { + pathname: location.pathname + }); + let { + matches: notFoundMatches, + route + } = getShortCircuitMatches(dataRoutes); + return { + basename, + location, + matches: notFoundMatches, + loaderData: {}, + actionData: null, + errors: { + [route.id]: error + }, + statusCode: error.status, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } + let result = await queryImpl(request, location, matches, requestContext); + if (isResponse(result)) { + return result; + } + + // When returning StaticHandlerContext, we patch back in the location here + // since we need it for React Context. But this helps keep our submit and + // loadRouteData operating on a Request instead of a Location + return _extends({ + location, + basename + }, result); + } + + /** + * The queryRoute() method is intended for targeted route requests, either + * for fetch ?_data requests or resource route requests. In this case, we + * are only ever calling a single action or loader, and we are returning the + * returned value directly. In most cases, this will be a Response returned + * from the action/loader, but it may be a primitive or other value as well - + * and in such cases the calling context should handle that accordingly. + * + * We do respect the throw/return differentiation, so if an action/loader + * throws, then this method will throw the value. This is important so we + * can do proper boundary identification in Remix where a thrown Response + * must go to the Catch Boundary but a returned Response is happy-path. + * + * One thing to note is that any Router-initiated Errors that make sense + * to associate with a status code will be thrown as an ErrorResponse + * instance which include the raw Error, such that the calling context can + * serialize the error as they see fit while including the proper response + * code. Examples here are 404 and 405 errors that occur prior to reaching + * any user-defined loaders. + */ + async function queryRoute(request, _temp4) { + let { + routeId, + requestContext + } = _temp4 === void 0 ? {} : _temp4; + let url = new URL(request.url); + let method = request.method; + let location = createLocation("", createPath(url), null, "default"); + let matches = matchRoutes(dataRoutes, location, basename); + + // SSR supports HEAD requests while SPA doesn't + if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") { + throw getInternalRouterError(405, { + method + }); + } else if (!matches) { + throw getInternalRouterError(404, { + pathname: location.pathname + }); + } + let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location); + if (routeId && !match) { + throw getInternalRouterError(403, { + pathname: location.pathname, + routeId + }); + } else if (!match) { + // This should never hit I don't think? + throw getInternalRouterError(404, { + pathname: location.pathname + }); + } + let result = await queryImpl(request, location, matches, requestContext, match); + if (isResponse(result)) { + return result; + } + let error = result.errors ? Object.values(result.errors)[0] : undefined; + if (error !== undefined) { + // If we got back result.errors, that means the loader/action threw + // _something_ that wasn't a Response, but it's not guaranteed/required + // to be an `instanceof Error` either, so we have to use throw here to + // preserve the "error" state outside of queryImpl. + throw error; + } + + // Pick off the right state value to return + if (result.actionData) { + return Object.values(result.actionData)[0]; + } + if (result.loaderData) { + var _result$activeDeferre; + let data = Object.values(result.loaderData)[0]; + if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) { + data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id]; + } + return data; + } + return undefined; + } + async function queryImpl(request, location, matches, requestContext, routeMatch) { + invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal"); + try { + if (isMutationMethod(request.method.toLowerCase())) { + let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, routeMatch != null); + return result; + } + let result = await loadRouteData(request, matches, requestContext, routeMatch); + return isResponse(result) ? result : _extends({}, result, { + actionData: null, + actionHeaders: {} + }); + } catch (e) { + // If the user threw/returned a Response in callLoaderOrAction, we throw + // it to bail out and then return or throw here based on whether the user + // returned or threw + if (isQueryRouteResponse(e)) { + if (e.type === ResultType.error) { + throw e.response; + } + return e.response; + } + // Redirects are always returned since they don't propagate to catch + // boundaries + if (isRedirectResponse(e)) { + return e; + } + throw e; + } + } + async function submit(request, matches, actionMatch, requestContext, isRouteRequest) { + let result; + if (!actionMatch.route.action && !actionMatch.route.lazy) { + let error = getInternalRouterError(405, { + method: request.method, + pathname: new URL(request.url).pathname, + routeId: actionMatch.route.id + }); + if (isRouteRequest) { + throw error; + } + result = { + type: ResultType.error, + error + }; + } else { + result = await callLoaderOrAction("action", request, actionMatch, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath, { + isStaticRequest: true, + isRouteRequest, + requestContext + }); + if (request.signal.aborted) { + let method = isRouteRequest ? "queryRoute" : "query"; + throw new Error(method + "() call aborted: " + request.method + " " + request.url); + } + } + if (isRedirectResult(result)) { + // Uhhhh - this should never happen, we should always throw these from + // callLoaderOrAction, but the type narrowing here keeps TS happy and we + // can get back on the "throw all redirect responses" train here should + // this ever happen :/ + throw new Response(null, { + status: result.status, + headers: { + Location: result.location + } + }); + } + if (isDeferredResult(result)) { + let error = getInternalRouterError(400, { + type: "defer-action" + }); + if (isRouteRequest) { + throw error; + } + result = { + type: ResultType.error, + error + }; + } + if (isRouteRequest) { + // Note: This should only be non-Response values if we get here, since + // isRouteRequest should throw any Response received in callLoaderOrAction + if (isErrorResult(result)) { + throw result.error; + } + return { + matches: [actionMatch], + loaderData: {}, + actionData: { + [actionMatch.route.id]: result.data + }, + errors: null, + // Note: statusCode + headers are unused here since queryRoute will + // return the raw Response or value + statusCode: 200, + loaderHeaders: {}, + actionHeaders: {}, + activeDeferreds: null + }; + } + 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, requestContext, undefined, { + [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 + } : {}) + }); + } + + // Create a GET request for the loaders + let loaderRequest = new Request(request.url, { + headers: request.headers, + redirect: request.redirect, + signal: request.signal + }); + let context = await loadRouteData(loaderRequest, matches, requestContext); + return _extends({}, context, result.statusCode ? { + statusCode: result.statusCode + } : {}, { + actionData: { + [actionMatch.route.id]: result.data + }, + actionHeaders: _extends({}, result.headers ? { + [actionMatch.route.id]: result.headers + } : {}) + }); + } + async function loadRouteData(request, matches, requestContext, routeMatch, pendingActionError) { + let isRouteRequest = routeMatch != null; + + // Short circuit if we have no loaders to run (queryRoute()) + if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) { + throw getInternalRouterError(400, { + method: request.method, + pathname: new URL(request.url).pathname, + routeId: routeMatch == null ? void 0 : routeMatch.route.id + }); + } + let requestMatches = routeMatch ? [routeMatch] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]); + let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy); + + // Short circuit if we have no loaders to run (query()) + if (matchesToLoad.length === 0) { + return { + matches, + // Add a null for all matched routes for proper revalidation on the client + loaderData: matches.reduce((acc, m) => Object.assign(acc, { + [m.route.id]: null + }), {}), + errors: pendingActionError || null, + statusCode: 200, + loaderHeaders: {}, + activeDeferreds: null + }; + } + let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, manifest, mapRouteProperties, basename, future.v7_relativeSplatPath, { + isStaticRequest: true, + isRouteRequest, + requestContext + }))]); + if (request.signal.aborted) { + let method = isRouteRequest ? "queryRoute" : "query"; + throw new Error(method + "() call aborted: " + request.method + " " + request.url); + } + + // Process and commit output from loaders + let activeDeferreds = new Map(); + let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError, activeDeferreds); + + // Add a null for any non-loader matches for proper revalidation on the client + let executedLoaders = new Set(matchesToLoad.map(match => match.route.id)); + matches.forEach(match => { + if (!executedLoaders.has(match.route.id)) { + context.loaderData[match.route.id] = null; + } + }); + return _extends({}, context, { + matches, + activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null + }); + } + 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; + } + function isSubmissionNavigation(opts) { + return opts != null && ("formData" in opts && opts.formData != null || "body" in opts && opts.body !== undefined); + } + function normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) { + let contextualMatches; + let activeRouteMatch; + if (fromRouteId) { + // Grab matches up to the calling route so our route-relative logic is + // relative to the correct source route + contextualMatches = []; + for (let match of matches) { + contextualMatches.push(match); + if (match.route.id === fromRouteId) { + activeRouteMatch = match; + break; + } + } + } else { + contextualMatches = matches; + activeRouteMatch = matches[matches.length - 1]; + } + + // Resolve the relative path + let path = resolveTo(to ? to : ".", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === "path"); + + // When `to` is not specified we inherit search/hash from the current + // location, unlike when to="." and we just inherit the path. + // See https://github.com/remix-run/remix/issues/927 + if (to == null) { + path.search = location.search; + path.hash = location.hash; + } + + // Add an ?index param for matched index routes if we don't already have one + if ((to == null || to === "" || to === ".") && activeRouteMatch && activeRouteMatch.route.index && !hasNakedIndexQuery(path.search)) { + path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index"; + } + + // If we're operating within a basename, prepend it to the pathname. If + // this is a root navigation, then just use the raw basename which allows + // the basename to have full control over the presence of a trailing slash + // on root actions + if (prependBasename && basename !== "/") { + path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]); + } + return createPath(path); + } + + // Normalize navigation options by converting formMethod=GET formData objects to + // URLSearchParams so they behave identically to links with query params + function normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) { + // Return location verbatim on non-submission navigations + if (!opts || !isSubmissionNavigation(opts)) { + return { + path + }; + } + if (opts.formMethod && !isValidMethod(opts.formMethod)) { + return { + path, + error: getInternalRouterError(405, { + method: opts.formMethod + }) + }; + } + let getInvalidBodyError = () => ({ + path, + error: getInternalRouterError(400, { + type: "invalid-body" + }) + }); + + // Create a Submission on non-GET navigations + let rawFormMethod = opts.formMethod || "get"; + let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase(); + let formAction = stripHashFromPath(path); + if (opts.body !== undefined) { + if (opts.formEncType === "text/plain") { + // text only support POST/PUT/PATCH/DELETE submissions + if (!isMutationMethod(formMethod)) { + return getInvalidBodyError(); + } + let text = typeof opts.body === "string" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ? + // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data + Array.from(opts.body.entries()).reduce((acc, _ref3) => { + let [name, value] = _ref3; + return "" + acc + name + "=" + value + "\n"; + }, "") : String(opts.body); + return { + path, + submission: { + formMethod, + formAction, + formEncType: opts.formEncType, + formData: undefined, + json: undefined, + text + } + }; + } else if (opts.formEncType === "application/json") { + // json only supports POST/PUT/PATCH/DELETE submissions + if (!isMutationMethod(formMethod)) { + return getInvalidBodyError(); + } + try { + let json = typeof opts.body === "string" ? JSON.parse(opts.body) : opts.body; + return { + path, + submission: { + formMethod, + formAction, + formEncType: opts.formEncType, + formData: undefined, + json, + text: undefined + } + }; + } catch (e) { + return getInvalidBodyError(); + } + } + } + invariant(typeof FormData === "function", "FormData is not available in this environment"); + let searchParams; + let formData; + if (opts.formData) { + searchParams = convertFormDataToSearchParams(opts.formData); + formData = opts.formData; + } else if (opts.body instanceof FormData) { + searchParams = convertFormDataToSearchParams(opts.body); + formData = opts.body; + } else if (opts.body instanceof URLSearchParams) { + searchParams = opts.body; + formData = convertSearchParamsToFormData(searchParams); + } else if (opts.body == null) { + searchParams = new URLSearchParams(); + formData = new FormData(); + } else { + try { + searchParams = new URLSearchParams(opts.body); + formData = convertSearchParamsToFormData(searchParams); + } catch (e) { + return getInvalidBodyError(); + } + } + let submission = { + formMethod, + formAction, + formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded", + formData, + json: undefined, + text: undefined + }; + if (isMutationMethod(submission.formMethod)) { + return { + path, + submission + }; + } + + // Flatten submission onto URLSearchParams for GET submissions + let parsedPath = parsePath(path); + // On GET navigation submissions we can drop the ?index param from the + // resulting location since all loaders will run. But fetcher GET submissions + // only run a single loader so we need to preserve any incoming ?index params + if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) { + searchParams.append("index", ""); + } + parsedPath.search = "?" + searchParams; + return { + path: createPath(parsedPath), + submission + }; + } + + // Filter out all routes 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(history, state, matches, submission, location, isInitialLoad, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionData, pendingError) { + let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : undefined; + let currentUrl = history.createURL(state.location); + let nextUrl = history.createURL(location); + + // 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) => { + let { + route + } = match; + if (route.lazy) { + // We haven't loaded this route yet so we don't know if it's got a loader! + return true; + } + if (route.loader == null) { + return false; + } + if (isInitialLoad) { + if (route.loader.hydrate) { + return true; + } + return state.loaderData[route.id] === undefined && ( + // Don't re-run if the loader ran and threw an error + !state.errors || state.errors[route.id] === undefined); + } + + // Always call the loader on new route instances and pending defer cancellations + if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) { + return true; + } + + // This is the default implementation for when we revalidate. If the route + // provides it's own implementation, then we give them full control but + // provide this value so they can leverage it if needed after they check + // their own specific use cases + let currentRouteMatch = state.matches[index]; + let nextRouteMatch = match; + return shouldRevalidateLoader(match, _extends({ + currentUrl, + currentParams: currentRouteMatch.params, + nextUrl, + nextParams: nextRouteMatch.params + }, submission, { + actionResult, + defaultShouldRevalidate: + // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate + isRevalidationRequired || + // Clicked the same link, resubmitted a GET form + currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search || + // Search params affect all loaders + currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch) + })); + }); + + // Pick fetcher.loads that need to be revalidated + let revalidatingFetchers = []; + fetchLoadMatches.forEach((f, key) => { + // Don't revalidate: + // - on initial load (shouldn't be any fetchers then anyway) + // - if fetcher won't be present in the subsequent render + // - no longer matches the URL (v7_fetcherPersist=false) + // - was unmounted but persisted due to v7_fetcherPersist=true + if (isInitialLoad || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) { + return; + } + let fetcherMatches = matchRoutes(routesToUse, f.path, basename); + + // If the fetcher path no longer matches, push it in with null matches so + // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is + // currently only a use-case for Remix HMR where the route tree can change + // at runtime and remove a route previously loaded via a fetcher + if (!fetcherMatches) { + revalidatingFetchers.push({ + key, + routeId: f.routeId, + path: f.path, + matches: null, + match: null, + controller: null + }); + return; + } + + // Revalidating fetchers are decoupled from the route matches since they + // load from a static href. They revalidate based on explicit revalidation + // (submission, useRevalidator, or X-Remix-Revalidate) + let fetcher = state.fetchers.get(key); + let fetcherMatch = getTargetMatch(fetcherMatches, f.path); + let shouldRevalidate = false; + if (fetchRedirectIds.has(key)) { + // Never trigger a revalidation of an actively redirecting fetcher + shouldRevalidate = false; + } else if (cancelledFetcherLoads.includes(key)) { + // Always revalidate if the fetcher was cancelled + shouldRevalidate = true; + } else if (fetcher && fetcher.state !== "idle" && fetcher.data === undefined) { + // If the fetcher hasn't ever completed loading yet, then this isn't a + // revalidation, it would just be a brand new load if an explicit + // revalidation is required + shouldRevalidate = isRevalidationRequired; + } else { + // Otherwise fall back on any user-defined shouldRevalidate, defaulting + // to explicit revalidations only + shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({ + currentUrl, + currentParams: state.matches[state.matches.length - 1].params, + nextUrl, + nextParams: matches[matches.length - 1].params + }, submission, { + actionResult, + defaultShouldRevalidate: isRevalidationRequired + })); + } + if (shouldRevalidate) { + revalidatingFetchers.push({ + key, + routeId: f.routeId, + path: f.path, + matches: fetcherMatches, + match: fetcherMatch, + controller: new AbortController() + }); + } + }); + return [navigationMatches, revalidatingFetchers]; + } + function isNewLoader(currentLoaderData, currentMatch, match) { + let isNew = + // [a] -> [a, b] + !currentMatch || + // [a, b] -> [a, c] + match.route.id !== currentMatch.route.id; + + // Handle the case that we don't have data for a re-used route, potentially + // from a prior error or from a cancelled pending deferred + let isMissingData = currentLoaderData[match.route.id] === undefined; + + // Always load if this is a net-new route or we don't yet have data + return isNew || isMissingData; + } + function isNewRouteInstance(currentMatch, match) { + let currentPath = currentMatch.route.path; + return ( + // param change for this match, /users/123 -> /users/456 + currentMatch.pathname !== match.pathname || + // splat param changed, which is not present in match.path + // e.g. /files/images/avatar.jpg -> files/finances.xls + currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"] + ); + } + function shouldRevalidateLoader(loaderMatch, arg) { + if (loaderMatch.route.shouldRevalidate) { + let routeChoice = loaderMatch.route.shouldRevalidate(arg); + if (typeof routeChoice === "boolean") { + return routeChoice; + } + } + return arg.defaultShouldRevalidate; + } + + /** + * Execute route.lazy() methods to lazily load route modules (loader, action, + * shouldRevalidate) and update the routeManifest in place which shares objects + * with dataRoutes so those get updated as well. + */ + async function loadLazyRouteModule(route, mapRouteProperties, manifest) { + if (!route.lazy) { + return; + } + let lazyRoute = await route.lazy(); + + // If the lazy route function was executed and removed by another parallel + // call then we can return - first lazy() to finish wins because the return + // value of lazy is expected to be static + if (!route.lazy) { + return; + } + let routeToUpdate = manifest[route.id]; + invariant(routeToUpdate, "No route found in manifest"); + + // Update the route in place. This should be safe because there's no way + // we could yet be sitting on this route as we can't get there without + // resolving lazy() first. + // + // This is different than the HMR "update" use-case where we may actively be + // on the route being updated. The main concern boils down to "does this + // mutation affect any ongoing navigations or any current state.matches + // values?". If not, it should be safe to update in place. + let routeUpdates = {}; + for (let lazyRouteProperty in lazyRoute) { + let staticRouteValue = routeToUpdate[lazyRouteProperty]; + let isPropertyStaticallyDefined = staticRouteValue !== undefined && + // This property isn't static since it should always be updated based + // on the route updates + lazyRouteProperty !== "hasErrorBoundary"; + warning(!isPropertyStaticallyDefined, "Route \"" + routeToUpdate.id + "\" has a static property \"" + lazyRouteProperty + "\" " + "defined but its lazy function is also returning a value for this property. " + ("The lazy route property \"" + lazyRouteProperty + "\" will be ignored.")); + if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) { + routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty]; + } + } + + // Mutate the route with the provided updates. Do this first so we pass + // the updated version to mapRouteProperties + Object.assign(routeToUpdate, routeUpdates); + + // Mutate the `hasErrorBoundary` property on the route based on the route + // updates and remove the `lazy` function so we don't resolve the lazy + // route again. + Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), { + lazy: undefined + })); + } + async function callLoaderOrAction(type, request, match, matches, manifest, mapRouteProperties, basename, v7_relativeSplatPath, opts) { + if (opts === void 0) { + opts = {}; + } + let resultType; + let result; + let onReject; + let runHandler = handler => { + // Setup a promise we can race against so that abort signals short circuit + let reject; + let abortPromise = new Promise((_, r) => reject = r); + onReject = () => reject(); + request.signal.addEventListener("abort", onReject); + return Promise.race([handler({ + request, + params: match.params, + context: opts.requestContext + }), abortPromise]); + }; + try { + let handler = match.route[type]; + if (match.route.lazy) { + if (handler) { + // Run statically defined handler in parallel with lazy() + let handlerError; + let values = await Promise.all([ + // If the handler throws, don't let it immediately bubble out, + // since we need to let the lazy() execution finish so we know if this + // route has a boundary that can handle the error + runHandler(handler).catch(e => { + handlerError = e; + }), loadLazyRouteModule(match.route, mapRouteProperties, manifest)]); + if (handlerError) { + throw handlerError; + } + result = values[0]; + } else { + // Load lazy route module, then run any returned handler + await loadLazyRouteModule(match.route, mapRouteProperties, manifest); + handler = match.route[type]; + if (handler) { + // Handler still run even if we got interrupted to maintain consistency + // with un-abortable behavior of handler execution on non-lazy or + // previously-lazy-loaded routes + result = await runHandler(handler); + } else if (type === "action") { + let url = new URL(request.url); + let pathname = url.pathname + url.search; + throw getInternalRouterError(405, { + method: request.method, + pathname, + routeId: match.route.id + }); + } else { + // lazy() route has no loader to run. Short circuit here so we don't + // hit the invariant below that errors on returning undefined. + return { + type: ResultType.data, + data: undefined + }; + } + } + } else if (!handler) { + let url = new URL(request.url); + let pathname = url.pathname + url.search; + throw getInternalRouterError(404, { + pathname + }); + } else { + result = await runHandler(handler); + } + invariant(result !== undefined, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ("\"" + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`."); + } catch (e) { + resultType = ResultType.error; + result = e; + } finally { + if (onReject) { + request.signal.removeEventListener("abort", onReject); + } + } + if (isResponse(result)) { + let status = result.status; + + // Process redirects + if (redirectStatusCodes.has(status)) { + let location = result.headers.get("Location"); + invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header"); + + // Support relative routing in internal redirects + if (!ABSOLUTE_URL_REGEX.test(location)) { + location = normalizeTo(new URL(request.url), matches.slice(0, matches.indexOf(match) + 1), basename, true, location, v7_relativeSplatPath); + } else if (!opts.isStaticRequest) { + // Strip off the protocol+origin for same-origin + same-basename absolute + // redirects. If this is a static request, we can let it go back to the + // browser as-is + let currentUrl = new URL(request.url); + let url = location.startsWith("//") ? new URL(currentUrl.protocol + location) : new URL(location); + let isSameBasename = stripBasename(url.pathname, basename) != null; + if (url.origin === currentUrl.origin && isSameBasename) { + location = url.pathname + url.search + url.hash; + } + } + + // Don't process redirects in the router during static requests requests. + // Instead, throw the Response and let the server handle it with an HTTP + // redirect. We also update the Location header in place in this flow so + // basename and relative routing is taken into account + if (opts.isStaticRequest) { + result.headers.set("Location", location); + throw result; + } + return { + type: ResultType.redirect, + status, + location, + revalidate: result.headers.get("X-Remix-Revalidate") !== null, + reloadDocument: result.headers.get("X-Remix-Reload-Document") !== null + }; + } + + // For SSR single-route requests, we want to hand Responses back directly + // without unwrapping. We do this with the QueryRouteResponse wrapper + // interface so we can know whether it was returned or thrown + if (opts.isRouteRequest) { + let queryRouteResponse = { + type: resultType === ResultType.error ? ResultType.error : ResultType.data, + response: result + }; + throw queryRouteResponse; + } + let data; + try { + let contentType = result.headers.get("Content-Type"); + // Check between word boundaries instead of startsWith() due to the last + // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type + if (contentType && /\bapplication\/json\b/.test(contentType)) { + if (result.body == null) { + data = null; + } else { + data = await result.json(); + } + } else { + data = await result.text(); + } + } catch (e) { + return { + type: ResultType.error, + error: e + }; + } + if (resultType === ResultType.error) { + return { + type: resultType, + error: new ErrorResponseImpl(status, result.statusText, data), + headers: result.headers + }; + } + return { + type: ResultType.data, + data, + statusCode: result.status, + headers: result.headers + }; + } + if (resultType === ResultType.error) { + return { + type: resultType, + error: result + }; + } + if (isDeferredData(result)) { + var _result$init, _result$init2; + return { + type: ResultType.deferred, + deferredData: result, + statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status, + headers: ((_result$init2 = result.init) == null ? void 0 : _result$init2.headers) && new Headers(result.init.headers) + }; + } + return { + type: ResultType.data, + data: result + }; + } + + // Utility method for creating the Request instances for loaders/actions during + // client-side navigations and fetches. During SSR we will always have a + // Request instance from the static handler (query/queryRoute) + function createClientSideRequest(history, location, signal, submission) { + let url = history.createURL(stripHashFromPath(location)).toString(); + let init = { + signal + }; + if (submission && isMutationMethod(submission.formMethod)) { + let { + formMethod, + formEncType + } = submission; + // Didn't think we needed this but it turns out unlike other methods, patch + // won't be properly normalized to uppercase and results in a 405 error. + // See: https://fetch.spec.whatwg.org/#concept-method + init.method = formMethod.toUpperCase(); + if (formEncType === "application/json") { + init.headers = new Headers({ + "Content-Type": formEncType + }); + init.body = JSON.stringify(submission.json); + } else if (formEncType === "text/plain") { + // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) + init.body = submission.text; + } else if (formEncType === "application/x-www-form-urlencoded" && submission.formData) { + // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) + init.body = convertFormDataToSearchParams(submission.formData); + } else { + // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request) + init.body = submission.formData; + } + } + return new Request(url, init); + } + function convertFormDataToSearchParams(formData) { + let searchParams = new URLSearchParams(); + for (let [key, value] of formData.entries()) { + // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs + searchParams.append(key, typeof value === "string" ? value : value.name); + } + return searchParams; + } + function convertSearchParamsToFormData(searchParams) { + let formData = new FormData(); + for (let [key, value] of searchParams.entries()) { + formData.append(key, value); + } + return formData; + } + function processRouteLoaderData(matches, 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 = errors || {}; + + // Prefer higher error values if lower errors bubble to the same boundary + if (errors[boundaryMatch.route.id] == null) { + errors[boundaryMatch.route.id] = error; + } + + // Clear our any prior loaderData for the throwing route + loaderData[id] = undefined; + + // Once we find our first (highest) error, we set the status code and + // prevent deeper status codes from overriding + if (!foundError) { + foundError = true; + statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500; + } + if (result.headers) { + loaderHeaders[id] = result.headers; + } + } else { + if (isDeferredResult(result)) { + activeDeferreds.set(id, result.deferredData); + loaderData[id] = result.deferredData.data; + } 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. Also clear out any loaderData for the + // throwing route + if (pendingError) { + errors = pendingError; + loaderData[Object.keys(pendingError)[0]] = undefined; + } + 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, + controller + } = revalidatingFetchers[index]; + invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result"); + let result = fetcherResults[index]; + + // Process fetcher non-redirect errors + if (controller && controller.signal.aborted) { + // Nothing to do for aborted fetchers + continue; + } else if (isErrorResult(result)) { + let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id); + if (!(errors && errors[boundaryMatch.route.id])) { + errors = _extends({}, errors, { + [boundaryMatch.route.id]: result.error + }); + } + state.fetchers.delete(key); + } else if (isRedirectResult(result)) { + // Should never get here, redirects should get processed above, but we + // keep this to type narrow to a success result in the else + invariant(false, "Unhandled fetcher revalidation redirect"); + } else if (isDeferredResult(result)) { + // Should never get here, deferred data should be awaited for fetchers + // in resolveDeferredResults + invariant(false, "Unhandled fetcher deferred data"); + } else { + let doneFetcher = getDoneFetcher(result.data); + state.fetchers.set(key, doneFetcher); + } + } + return { + loaderData, + errors + }; + } + function mergeLoaderData(loaderData, newLoaderData, matches, errors) { + let mergedLoaderData = _extends({}, newLoaderData); + for (let match of matches) { + let id = match.route.id; + if (newLoaderData.hasOwnProperty(id)) { + if (newLoaderData[id] !== undefined) { + mergedLoaderData[id] = newLoaderData[id]; + } + } else if (loaderData[id] !== undefined && match.route.loader) { + // Preserve existing keys not included in newLoaderData and where a loader + // wasn't removed by HMR + mergedLoaderData[id] = loaderData[id]; + } + if (errors && errors.hasOwnProperty(id)) { + // Don't keep any loader data below the boundary + break; + } + } + return mergedLoaderData; + } + + // Find the nearest error boundary, looking upwards from the leaf route (or the + // route specified by routeId) for the closest ancestor error boundary, + // defaulting to the root match + function findNearestBoundary(matches, routeId) { + let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches]; + return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0]; + } + function getShortCircuitMatches(routes) { + // Prefer a root layout route if present, otherwise shim in a route object + let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === "/") || { + id: "__shim-error-route__" + }; + return { + matches: [{ + params: {}, + pathname: "", + pathnameBase: "", + route + }], + route + }; + } + function getInternalRouterError(status, _temp5) { + let { + pathname, + routeId, + method, + type + } = _temp5 === void 0 ? {} : _temp5; + let statusText = "Unknown Server Error"; + let errorMessage = "Unknown @remix-run/router error"; + if (status === 400) { + statusText = "Bad Request"; + if (method && pathname && routeId) { + errorMessage = "You made a " + method + " request to \"" + pathname + "\" but " + ("did not provide a `loader` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; + } else if (type === "defer-action") { + errorMessage = "defer() is not supported in actions"; + } else if (type === "invalid-body") { + errorMessage = "Unable to encode submission body"; + } + } else if (status === 403) { + statusText = "Forbidden"; + errorMessage = "Route \"" + routeId + "\" does not match URL \"" + pathname + "\""; + } else if (status === 404) { + statusText = "Not Found"; + errorMessage = "No route matches URL \"" + pathname + "\""; + } else if (status === 405) { + statusText = "Method Not Allowed"; + if (method && pathname && routeId) { + errorMessage = "You made a " + method.toUpperCase() + " request to \"" + pathname + "\" but " + ("did not provide an `action` for route \"" + routeId + "\", ") + "so there is no way to handle the request."; + } else if (method) { + errorMessage = "Invalid request method \"" + method.toUpperCase() + "\""; + } + } + return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true); + } + + // Find any returned redirect errors, starting from the lowest match + function findRedirect(results) { + for (let i = results.length - 1; i >= 0; i--) { + let result = results[i]; + if (isRedirectResult(result)) { + return { + result, + idx: i + }; + } + } + } + function stripHashFromPath(path) { + let parsedPath = typeof path === "string" ? parsePath(path) : path; + return createPath(_extends({}, parsedPath, { + hash: "" + })); + } + function isHashChangeOnly(a, b) { + if (a.pathname !== b.pathname || a.search !== b.search) { + return false; + } + if (a.hash === "") { + // /page -> /page#hash + return b.hash !== ""; + } else if (a.hash === b.hash) { + // /page#hash -> /page#hash + return true; + } else if (b.hash !== "") { + // /page#hash -> /page#other + return true; + } + + // If the hash is removed the browser will re-perform a request to the server + // /page#hash -> /page + return false; + } + function isDeferredResult(result) { + return result.type === ResultType.deferred; + } + function isErrorResult(result) { + return result.type === ResultType.error; + } + function isRedirectResult(result) { + return (result && result.type) === ResultType.redirect; + } + function isDeferredData(value) { + let deferred = value; + return deferred && typeof deferred === "object" && typeof deferred.data === "object" && typeof deferred.subscribe === "function" && typeof deferred.cancel === "function" && typeof deferred.resolveData === "function"; + } + function isResponse(value) { + return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined"; + } + function isRedirectResponse(result) { + if (!isResponse(result)) { + return false; + } + let status = result.status; + let location = result.headers.get("Location"); + return status >= 300 && status <= 399 && location != null; + } + function isQueryRouteResponse(obj) { + return obj && isResponse(obj.response) && (obj.type === ResultType.data || obj.type === ResultType.error); + } + function isValidMethod(method) { + return validRequestMethods.has(method.toLowerCase()); + } + function isMutationMethod(method) { + return validMutationMethods.has(method.toLowerCase()); + } + async function resolveDeferredResults(currentMatches, matchesToLoad, results, signals, isFetcher, currentLoaderData) { + for (let index = 0; index < results.length; index++) { + let result = results[index]; + let match = matchesToLoad[index]; + // If we don't have a match, then we can have a deferred result to do + // anything with. This is for revalidating fetchers where the route was + // removed during HMR + if (!match) { + continue; + } + let currentMatch = currentMatches.find(m => m.route.id === match.route.id); + let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined; + if (isDeferredResult(result) && (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 + let signal = signals[index]; + invariant(signal, "Expected an AbortSignal for revalidating fetcher deferred result"); + 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 === ""); + } + function getTargetMatch(matches, location) { + let search = typeof location === "string" ? parsePath(location).search : location.search; + if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) { + // Return the leaf index route when index is present + return matches[matches.length - 1]; + } + // Otherwise grab the deepest "path contributing" match (ignoring index and + // pathless layout routes) + let pathMatches = getPathContributingMatches(matches); + return pathMatches[pathMatches.length - 1]; + } + function getSubmissionFromNavigation(navigation) { + let { + formMethod, + formAction, + formEncType, + text, + formData, + json + } = navigation; + if (!formMethod || !formAction || !formEncType) { + return; + } + if (text != null) { + return { + formMethod, + formAction, + formEncType, + formData: undefined, + json: undefined, + text + }; + } else if (formData != null) { + return { + formMethod, + formAction, + formEncType, + formData, + json: undefined, + text: undefined + }; + } else if (json !== undefined) { + return { + formMethod, + formAction, + formEncType, + formData: undefined, + json, + text: undefined + }; + } + } + function getLoadingNavigation(location, submission) { + if (submission) { + let navigation = { + state: "loading", + location, + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text + }; + return navigation; + } else { + let navigation = { + state: "loading", + location, + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined + }; + return navigation; + } + } + function getSubmittingNavigation(location, submission) { + let navigation = { + state: "submitting", + location, + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text + }; + return navigation; + } + function getLoadingFetcher(submission, data) { + if (submission) { + let fetcher = { + state: "loading", + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text, + data + }; + return fetcher; + } else { + let fetcher = { + state: "loading", + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined, + data + }; + return fetcher; + } + } + function getSubmittingFetcher(submission, existingFetcher) { + let fetcher = { + state: "submitting", + formMethod: submission.formMethod, + formAction: submission.formAction, + formEncType: submission.formEncType, + formData: submission.formData, + json: submission.json, + text: submission.text, + data: existingFetcher ? existingFetcher.data : undefined + }; + return fetcher; + } + function getDoneFetcher(data) { + let fetcher = { + state: "idle", + formMethod: undefined, + formAction: undefined, + formEncType: undefined, + formData: undefined, + json: undefined, + text: undefined, + data + }; + return fetcher; + } + function restoreAppliedTransitions(_window, transitions) { + try { + let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY); + if (sessionPositions) { + let json = JSON.parse(sessionPositions); + for (let [k, v] of Object.entries(json || {})) { + if (v && Array.isArray(v)) { + transitions.set(k, new Set(v || [])); + } + } + } + } catch (e) { + // no-op, use default empty object + } + } + function persistAppliedTransitions(_window, transitions) { + if (transitions.size > 0) { + let json = {}; + for (let [k, v] of transitions) { + json[k] = [...v]; + } + try { + _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json)); + } catch (error) { + warning(false, "Failed to save applied view transitions in sessionStorage (" + error + ")."); + } + } + } + + //#endregion + + exports.AbortedDeferredError = AbortedDeferredError; + exports.Action = Action; + exports.IDLE_BLOCKER = IDLE_BLOCKER; + exports.IDLE_FETCHER = IDLE_FETCHER; + exports.IDLE_NAVIGATION = IDLE_NAVIGATION; + exports.UNSAFE_DEFERRED_SYMBOL = UNSAFE_DEFERRED_SYMBOL; + exports.UNSAFE_DeferredData = DeferredData; + exports.UNSAFE_ErrorResponseImpl = ErrorResponseImpl; + exports.UNSAFE_convertRouteMatchToUiMatch = convertRouteMatchToUiMatch; + exports.UNSAFE_convertRoutesToDataRoutes = convertRoutesToDataRoutes; + exports.UNSAFE_getResolveToMatches = getResolveToMatches; + exports.UNSAFE_invariant = invariant; + exports.UNSAFE_warning = warning; + exports.createBrowserHistory = createBrowserHistory; + exports.createHashHistory = createHashHistory; + exports.createMemoryHistory = createMemoryHistory; + exports.createPath = createPath; + exports.createRouter = createRouter; + exports.createStaticHandler = createStaticHandler; + exports.defer = defer; + exports.generatePath = generatePath; + exports.getStaticContextFromError = getStaticContextFromError; + exports.getToPathname = getToPathname; + exports.isDeferredData = isDeferredData; + exports.isRouteErrorResponse = isRouteErrorResponse; + exports.joinPaths = joinPaths; + exports.json = json; + exports.matchPath = matchPath; + exports.matchRoutes = matchRoutes; + exports.normalizePathname = normalizePathname; + exports.parsePath = parsePath; + exports.redirect = redirect; + exports.redirectDocument = redirectDocument; + exports.resolvePath = resolvePath; + exports.resolveTo = resolveTo; + exports.stripBasename = stripBasename; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=router.umd.js.map diff --git a/node_modules/@remix-run/router/dist/router.umd.js.map b/node_modules/@remix-run/router/dist/router.umd.js.map new file mode 100644 index 0000000..a51abb1 --- /dev/null +++ b/node_modules/@remix-run/router/dist/router.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"router.umd.js","sources":["../history.ts","../utils.ts","../router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\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 * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly {\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 let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: 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 statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n status: number;\n location: string;\n revalidate: boolean;\n reloadDocument?: 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\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on ``,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable | null;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (args: LoaderFunctionArgs):\n | Promise\n | DataFunctionValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (args: ActionFunctionArgs):\n | Promise\n | DataFunctionValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction {\n (): Promise>>;\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 lazy?: LazyRouteFunction;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record;\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 `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam =\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 you 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 mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: number[] = [],\n manifest: RouteManifest = {}\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 !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/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(\n branches[i],\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n safelyDecodeURI(pathname)\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch,\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/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\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/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, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = safelyDecodeURIComponent(value || \"\", paramName);\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(\n /\\/:([\\w-]+)(\\?)?/g,\n (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n }\n );\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nfunction safelyDecodeURI(value: string) {\n try {\n return decodeURI(value);\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\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 * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/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 *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === matches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial;\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 (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\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 pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n ActionFunction,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n AgnosticRouteObject,\n DataResult,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n ImmutableRouteKey,\n LoaderFunction,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(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 * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\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 * Map of current blockers\n */\n blockers: 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 * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record;\n actionHeaders: Record;\n activeDeferreds: Record | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: { requestContext?: unknown }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: { routeId?: string; requestContext?: unknown }\n ): Promise;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n unstable_viewTransitionOpts?: ViewTransitionOpts;\n unstable_flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\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 * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\n/**\n * Wrapper object to allow us to throw any response out from callLoaderOrAction\n * for queryRouter while preserving whether or not it was thrown or returned\n * from the loader/action\n */\ninterface QueryRouteResponse {\n type: ResultType.data | ResultType.error;\n response: Response;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\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 // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let 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 error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized: boolean;\n let hasLazyRoutes = initialMatches.some((m) => m.route.lazy);\n let hasLoaders = initialMatches.some((m) => m.route.loader);\n if (hasLazyRoutes) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!hasLoaders) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n initialized = initialMatches.every(\n (m) =>\n m.route.loader &&\n m.route.loader.hydrate !== true &&\n ((loaderData && loaderData[m.route.id] !== undefined) ||\n (errors && errors[m.route.id] !== undefined))\n );\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map> = new Map<\n string,\n Set\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location, {\n initialHydration: true,\n });\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n }\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 { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n 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 | null,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.unstable_viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n { 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 initialHydration?: boolean;\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a \n // which will default to a navigation to /page\n if (\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let 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 (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\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, flushSync }\n );\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n\n // Create a GET request for the loaders\n request = new Request(request.url, { signal: request.signal });\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.fetcherSubmission,\n opts && opts.replace,\n opts && opts.initialHydration === true,\n flushSync,\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 ...(pendingActionData ? { actionData: pendingActionData } : {}),\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; flushSync?: boolean } = {}\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n replace =\n result.location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(state, result, { submission, replace });\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 // Send back an empty object we can use to clear out any prior actionData\n pendingActionData: {},\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\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 fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: 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 =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionData,\n pendingError\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\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 we have partialHydration enabled, then don't update the state for the\n // initial data load since iot's not a \"navigation\"\n if (\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration)\n ) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n let actionData = pendingActionData || state.actionData;\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData\n ? Object.keys(actionData).length === 0\n ? { actionData: null }\n : { actionData }\n : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(state, redirect.result, { 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 let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResult = await callLoaderOrAction(\n \"action\",\n fetchRequest,\n match,\n requestMatches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(state, actionResult, {\n fetcherSubmission: submission,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n false,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n { [match.route.id]: actionResult.data },\n undefined // No need to send through errors since we short circuit above\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(state, redirect.result);\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 // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(state, result);\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n state: RouterState,\n redirect: RedirectResult,\n {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n\n let redirectLocation = createLocation(state.location, redirect.location, {\n _isRedirect: true,\n });\n invariant(\n redirectLocation,\n \"Expected a location on the redirect navigation\"\n );\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.reloadDocument) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) {\n const url = init.history.createURL(redirect.location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(redirect.location);\n } else {\n routerWindow.location.assign(redirect.location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: redirect.location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: 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((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n )\n ),\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n return callLoaderOrAction(\n \"loader\",\n createClientSideRequest(init.history, f.path, f.controller.signal),\n f.match,\n f.matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n } else {\n let error: ErrorResult = {\n type: ResultType.error,\n error: getInternalRouterError(404, { pathname: f.path }),\n };\n return error;\n }\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 loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\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 updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher(key: string): Fetcher {\n if (future.v7_fetcherPersist) {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({ fetchers: new Map(state.fetchers) });\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 = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function 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 || null;\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 getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n ...(opts ? opts.future : null),\n };\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n */\n async function query(\n request: Request,\n { requestContext }: { requestContext?: unknown } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(request, location, matches, requestContext);\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n }: { requestContext?: unknown; routeId?: string } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n match\n );\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction, we throw\n // it to bail out and then return or throw here based on whether the user\n // returned or threw\n if (isQueryRouteResponse(e)) {\n if (e.type === ResultType.error) {\n throw e.response;\n }\n return e.response;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath,\n { isStaticRequest: true, isRouteRequest, requestContext }\n );\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.status,\n headers: {\n Location: result.location,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n 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(\n request,\n matches,\n requestContext,\n undefined,\n {\n [boundaryMatch.route.id]: result.error,\n }\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 // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n let context = await loadRouteData(loaderRequest, matches, requestContext);\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 requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch,\n pendingActionError?: RouteData\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n );\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath,\n { isStaticRequest: true, isRouteRequest, requestContext }\n )\n ),\n ]);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError,\n activeDeferreds\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n 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\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes 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 history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isInitialLoad: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : undefined;\n\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let { route } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n\n if (route.loader == null) {\n return false;\n }\n\n if (isInitialLoad) {\n if (route.loader.hydrate) {\n return true;\n }\n return (\n state.loaderData[route.id] === undefined &&\n // Don't re-run if the loader ran and threw an error\n (!state.errors || state.errors[route.id] === undefined)\n );\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n defaultShouldRevalidate:\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial load (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (\n isInitialLoad ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.includes(key)) {\n // Always revalidate if the fetcher was cancelled\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n defaultShouldRevalidate: isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n basename: string,\n v7_relativeSplatPath: boolean,\n opts: {\n isStaticRequest?: boolean;\n isRouteRequest?: boolean;\n requestContext?: unknown;\n } = {}\n): Promise {\n let resultType;\n let result;\n let onReject: (() => void) | undefined;\n\n let runHandler = (handler: ActionFunction | LoaderFunction) => {\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 onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n return Promise.race([\n handler({\n request,\n params: match.params,\n context: opts.requestContext,\n }),\n abortPromise,\n ]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let values = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadLazyRouteModule(match.route, mapRouteProperties, manifest),\n ]);\n if (handlerError) {\n throw handlerError;\n }\n result = values[0];\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n\n handler = match.route[type];\n if (handler) {\n // Handler still run even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, data: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n if (isResponse(result)) {\n let status = result.status;\n\n // Process redirects\n if (redirectStatusCodes.has(status)) {\n let location = result.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n // Support relative routing in internal redirects\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n location = normalizeTo(\n new URL(request.url),\n matches.slice(0, matches.indexOf(match) + 1),\n basename,\n true,\n location,\n v7_relativeSplatPath\n );\n } else if (!opts.isStaticRequest) {\n // Strip off the protocol+origin for same-origin + same-basename absolute\n // redirects. If this is a static request, we can let it go back to the\n // browser as-is\n let currentUrl = new URL(request.url);\n let url = location.startsWith(\"//\")\n ? new URL(currentUrl.protocol + location)\n : new URL(location);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n location = url.pathname + url.search + url.hash;\n }\n }\n\n // Don't process redirects in the router during static requests requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect. We also update the Location header in place in this flow so\n // basename and relative routing is taken into account\n if (opts.isStaticRequest) {\n result.headers.set(\"Location\", location);\n throw result;\n }\n\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n reloadDocument: result.headers.get(\"X-Remix-Reload-Document\") !== null,\n };\n }\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping. We do this with the QueryRouteResponse wrapper\n // interface so we can know whether it was returned or thrown\n if (opts.isRouteRequest) {\n let queryRouteResponse: QueryRouteResponse = {\n type:\n resultType === ResultType.error ? ResultType.error : ResultType.data,\n response: result,\n };\n throw queryRouteResponse;\n }\n\n let data: any;\n\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return { type: ResultType.error, error: e };\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponseImpl(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 (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n 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\n errors = errors || {};\n\n // Prefer higher error values if lower errors bubble to the same boundary\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n } else {\n loaderData[id] = result.data;\n }\n\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. Also clear out any loaderData for the\n // throwing route\n if (pendingError) {\n errors = pendingError;\n loaderData[Object.keys(pendingError)[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n 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, controller } = 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 (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isQueryRouteResponse(obj: any): obj is QueryRouteResponse {\n return (\n obj &&\n isResponse(obj.response) &&\n (obj.type === ResultType.data || obj.type === ResultType.error)\n );\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\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 // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (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 let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\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\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n\n//#endregion\n"],"names":["Action","PopStateEventType","createMemoryHistory","options","initialEntries","initialIndex","v5Compat","entries","map","entry","index","createMemoryLocation","state","undefined","clampIndex","length","action","Pop","listener","n","Math","min","max","getCurrentLocation","to","key","location","createLocation","pathname","warning","charAt","JSON","stringify","createHref","createPath","history","createURL","URL","encodeLocation","path","parsePath","search","hash","push","Push","nextLocation","splice","delta","replace","Replace","go","nextIndex","listen","fn","createBrowserHistory","createBrowserLocation","window","globalHistory","usr","createBrowserHref","getUrlBasedHistory","createHashHistory","createHashLocation","substr","startsWith","createHashHref","base","document","querySelector","href","getAttribute","url","hashIndex","indexOf","slice","validateHashLocation","invariant","value","message","Error","cond","console","warn","e","createKey","random","toString","getHistoryState","idx","current","_extends","_ref","parsedPath","searchIndex","getLocation","validateLocation","defaultView","getIndex","replaceState","handlePop","historyState","pushState","error","DOMException","name","assign","origin","addEventListener","removeEventListener","ResultType","immutableRouteKeys","Set","isIndexRoute","route","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","treePath","id","join","children","indexRoute","pathOrLayoutRoute","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","rankRouteBranches","matches","i","matchRouteBranch","safelyDecodeURI","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","meta","caseSensitive","childrenIndex","joinPaths","routesMeta","concat","score","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","sort","a","b","compareIndexes","paramRe","dynamicSegmentValue","indexRouteValue","emptySegmentValue","staticSegmentValue","splatPenalty","isSplat","s","initialScore","some","filter","reduce","segment","test","siblings","every","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","generatePath","originalPath","prefix","p","String","array","isLastSegment","star","keyMatch","optional","param","pattern","matcher","compiledParams","compilePath","captureGroups","memo","paramName","splatValue","safelyDecodeURIComponent","regexpSource","_","RegExp","decodeURI","decodeURIComponent","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","resolvePathname","normalizeSearch","normalizeHash","relativeSegments","pop","getInvalidPathError","char","field","dest","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","isEmptyPath","from","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","getToPathname","paths","json","init","responseInit","status","headers","Headers","has","set","Response","AbortedDeferredError","DeferredData","constructor","pendingKeysSet","subscribers","deferredKeys","Array","isArray","reject","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","acc","_ref2","trackPromise","done","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","v","k","resolveData","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","isTrackedPromise","_tracked","_error","_data","defer","redirect","redirectDocument","response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","createRouter","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","dataRoutes","inFlightDataRoutes","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialErrors","getInternalRouterError","getShortCircuitMatches","initialized","hasLazyRoutes","m","lazy","hasLoaders","loader","errors","hydrate","router","historyAction","navigation","restoreScrollPosition","preventScrollReset","revalidation","actionData","fetchers","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingNavigationController","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","fetchRedirectIds","fetchLoadMatches","activeFetchers","deletedFetchers","activeDeferreds","blockerFunctions","ignoreNextHistoryUpdate","initialize","blockerKey","shouldBlockNavigation","currentLocation","updateBlocker","updateState","startNavigation","restoreAppliedTransitions","_saveAppliedTransitions","persistAppliedTransitions","initialHydration","dispose","clear","deleteFetcher","deleteBlocker","newState","opts","completedFetchers","deletedFetchersKeys","fetcher","unstable_viewTransitionOpts","viewTransitionOpts","unstable_flushSync","flushSync","completeNavigation","_temp","_location$state","_location$state2","isActionReload","isMutationMethod","_isRedirect","keys","mergeLoaderData","priorPaths","toPaths","getSavedScrollPosition","navigate","normalizedPath","normalizeTo","fromRouteId","relative","submission","normalizeNavigateOptions","userReplace","pendingError","enableViewTransition","unstable_viewTransition","revalidate","interruptActiveLoads","startUninterruptedRevalidation","overrideNavigation","saveScrollPosition","routesToUse","loadingNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","request","createClientSideRequest","pendingActionData","findNearestBoundary","actionOutput","handleAction","shortCircuited","pendingActionError","getLoadingNavigation","Request","handleLoaders","fetcherSubmission","getSubmittingNavigation","actionMatch","getTargetMatch","type","method","routeId","callLoaderOrAction","isRedirectResult","startRedirectNavigation","isErrorResult","boundaryMatch","isDeferredResult","activeSubmission","getSubmissionFromNavigation","matchesToLoad","revalidatingFetchers","getMatchesToLoad","updatedFetchers","markFetchRedirectsDone","rf","revalidatingFetcher","getLoadingFetcher","abortFetcher","abortPendingFetchRevalidations","f","results","loaderResults","fetcherResults","callLoadersAndMaybeResolveData","findRedirect","fetcherKey","processLoaderData","deferredData","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","fetch","setFetcherError","handleFetcherAction","handleFetcherLoader","requestMatches","existingFetcher","updateFetcherState","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","actionResult","getDoneFetcher","revalidationRequest","loadId","loadFetcher","staleKey","doneFetcher","resolveDeferredData","_temp2","redirectLocation","isDocumentReload","reloadDocument","redirectHistoryAction","currentMatches","fetchersToLoad","all","resolveDeferredResults","getFetcher","deleteFetcherAndUpdateState","count","markFetchersDone","doneKeys","landedId","yeetedKeys","getBlocker","blocker","newBlocker","blockerFunction","predicate","cancelledRouteIds","dfd","enableScrollRestoration","positions","getPosition","getKey","y","getScrollKey","_internalSetRoutes","newRoutes","_internalFetchControllers","_internalActiveDeferreds","UNSAFE_DEFERRED_SYMBOL","Symbol","createStaticHandler","query","_temp3","requestContext","isValidMethod","methodNotAllowedMatches","statusCode","loaderHeaders","actionHeaders","queryImpl","isResponse","queryRoute","_temp4","find","values","_result$activeDeferre","routeMatch","submit","loadRouteData","isQueryRouteResponse","isRedirectResponse","isRouteRequest","isStaticRequest","Location","context","loaderRequest","getLoaderMatchesUntilBoundary","processRouteLoaderData","executedLoaders","fromEntries","getStaticContextFromError","newContext","_deepestRenderedBoundaryId","isSubmissionNavigation","body","prependBasename","contextualMatches","activeRouteMatch","hasNakedIndexQuery","normalizeFormMethod","isFetcher","getInvalidBodyError","rawFormMethod","toUpperCase","stripHashFromPath","FormData","URLSearchParams","parse","searchParams","convertFormDataToSearchParams","convertSearchParamsToFormData","append","boundaryId","boundaryMatches","findIndex","isInitialLoad","currentUrl","nextUrl","navigationMatches","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","fetcherMatches","fetcherMatch","shouldRevalidate","currentLoaderData","currentMatch","isNew","isMissingData","currentPath","loaderMatch","arg","routeChoice","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","staticRouteValue","isPropertyStaticallyDefined","resultType","onReject","runHandler","handler","handlerError","protocol","isSameBasename","queryRouteResponse","contentType","isDeferredData","_result$init","_result$init2","deferred","foundError","newLoaderData","mergedLoaderData","hasOwnProperty","eligibleMatches","reverse","_temp5","errorMessage","obj","signals","isRevalidatingLoader","unwrap","getAll","_window","transitions","sessionPositions","sessionStorage","getItem","setItem"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAA;EACA;EACA;;EAEA;EACA;EACA;AACYA,MAAAA,MAAM,0BAANA,MAAM,EAAA;IAANA,MAAM,CAAA,KAAA,CAAA,GAAA,KAAA,CAAA;IAANA,MAAM,CAAA,MAAA,CAAA,GAAA,MAAA,CAAA;IAANA,MAAM,CAAA,SAAA,CAAA,GAAA,SAAA,CAAA;EAAA,EAAA,OAANA,MAAM,CAAA;EAAA,CAAA,CAAA,EAAA,EAAA;;EAwBlB;EACA;EACA;;EAkBA;EACA;EAEA;EACA;EACA;EACA;EAgBA;EACA;EACA;EAkBA;EACA;EACA;EAKA;EACA;EACA;EACA;EACA;EAGA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAgFA,MAAMC,iBAAiB,GAAG,UAAU,CAAA;EACpC;;EAEA;EACA;EACA;;EAEA;EACA;EACA;EACA;EASA;EACA;EACA;EACA;EACA;EAQA;EACA;EACA;EACA;EACO,SAASC,mBAAmBA,CACjCC,OAA6B,EACd;EAAA,EAAA,IADfA,OAA6B,KAAA,KAAA,CAAA,EAAA;MAA7BA,OAA6B,GAAG,EAAE,C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P,EAAE,CAAC/B,CAAC,CAAC,CAAA;EAC5B,KAAA;KACD,CAAA;EAED,EAAA,OAAOgB,OAAO,CAAA;EAChB,CAAA;;EAEA;;ECluBA;EACA;EACA;;EAKY0E,IAAAA,UAAU,0BAAVA,UAAU,EAAA;IAAVA,UAAU,CAAA,MAAA,CAAA,GAAA,MAAA,CAAA;IAAVA,UAAU,CAAA,UAAA,CAAA,GAAA,UAAA,CAAA;IAAVA,UAAU,CAAA,UAAA,CAAA,GAAA,UAAA,CAAA;IAAVA,UAAU,CAAA,OAAA,CAAA,GAAA,OAAA,CAAA;EAAA,EAAA,OAAVA,UAAU,CAAA;EAAA,CAAA,CAAA,EAAA,CAAA,CAAA;;EAOtB;EACA;EACA;;EAQA;EACA;EACA;;EAQA;EACA;EACA;;EASA;EACA;EACA;;EAOA;EACA;EACA;;EAUA;EACA;EACA;EACA;;EAGA;EACA;EACA;EACA;;EAIA;EACA;EACA;EACA;;EAUA;;EAQA;EACA;EACA;EACA;EACA;;EA2BA;EACA;EACA;EACA;EACA;;EAOA;EACA;EACA;EAEA;EACA;EACA;EAIA;EACA;EACA;EAIA;EACA;EACA;EACA;EACA;EAGA;EACA;EACA;EAOA;EACA;EACA;EAOA;EACA;EACA;EAgBA;EACA;EACA;EACA;EACA;EACA;EACA;EAKA;EACA;EACA;EACA;EACA;EACA;EAKA;EACA;EACA;EACA;EAOA;EACA;EACA;EACA;EACA;EASO,MAAMC,kBAAkB,GAAG,IAAIC,GAAG,CAAoB,CAC3D,MAAM,EACN,eAAe,EACf,MAAM,EACN,IAAI,EACJ,OAAO,EACP,UAAU,CACX,CAAC,CAAA;;EASF;EACA;EACA;EACA;;EAKA;EACA;EACA;;EAaA;EACA;EACA;;EAMA;EACA;EACA;;EAMA;EACA;EACA;EACA;;EAcA;EACA;EACA;;EAOA;;EAaA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAWA;EACA;EACA;EAKA;EACA;EACA;EAKA;EACA;EACA;EA0BA,SAAS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AK,EAAE;EACdzE,MAAAA,OAAO,CACL,KAAK,EACyDyE,6DAAAA,GAAAA,KAAK,OACrE,CAAC,CAAA;EACH,KAAA;EACF,GAAA;EACF,CAAA;;EAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@remix-run/router/dist/router.umd.min.js b/node_modules/@remix-run/router/dist/router.umd.min.js new file mode 100644 index 0000000..3c9a6c4 --- /dev/null +++ b/node_modules/@remix-run/router/dist/router.umd.min.js @@ -0,0 +1,12 @@ +/** + * @remix-run/router v1.14.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(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).RemixRouter={})}(this,(function(e){"use strict";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0&&(t.hash=e.substr(r),e=e.substr(0,r));let a=e.indexOf("?");a>=0&&(t.search=e.substr(a),e=e.substr(0,a)),e&&(t.pathname=e)}return t}function d(e,n,c,d){void 0===d&&(d={});let{window:u=document.defaultView,v5Compat:h=!1}=d,f=u.history,p=r.Pop,m=null,y=v();function v(){return(f.state||{idx:null}).idx}function g(){p=r.Pop;let e=v(),t=null==e?null:e-y;y=e,m&&m({action:p,location:w.location,delta:t})}function b(e){let t="null"!==u.location.origin?u.location.origin:u.location.href,r="string"==typeof e?e:l(e);return o(t,"No window.location.(origin|href) available to create URL for href: "+r),new URL(r,t)}null==y&&(y=0,f.replaceState(t({},f.state,{idx:y}),""));let w={get action(){return p},get location(){return e(u,f)},listen(e){if(m)throw new Error("A history only accepts one active listener");return u.addEventListener(a,g),m=e,()=>{u.removeEventListener(a,g),m=null}},createHref:e=>n(u,e),createURL:b,encodeLocation(e){let t=b(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:function(e,t){p=r.Push;let a=s(w.location,e,t);c&&c(a,e),y=v()+1;let o=i(a,y),n=w.createHref(a);try{f.pushState(o,"",n)}catch(e){if(e instanceof DOMException&&"DataCloneError"===e.name)throw e;u.location.assign(n)}h&&m&&m({action:p,location:w.location,delta:1})},replace:function(e,t){p=r.Replace;let a=s(w.location,e,t);c&&c(a,e),y=v();let o=i(a,y),n=w.createHref(a);f.replaceState(o,"",n),h&&m&&m({action:p,location:w.location,delta:0})},go:e=>f.go(e)};return w}let u=function(e){return e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error",e}({});const h=new Set(["lazy","caseSensitive","path","id","index","children"]);function f(e,r,a,n){return void 0===a&&(a=[]),void 0===n&&(n={}),e.map(((e,i)=>{let s=[...a,i],l="string"==typeof e.id?e.id:s.join("-");if(o(!0!==e.index||!e.children,"Cannot specify children on an index route"),o(!n[l],'Found a route id collision on id "'+l+"\". Route id's must be globally unique within Data Router usages"),function(e){return!0===e.index}(e)){let a=t({},e,r(e),{id:l});return n[l]=a,a}{let a=t({},e,r(e),{id:l,children:void 0});return n[l]=a,e.children&&(a.children=f(e.children,r,s,n)),a}}))}function p(e,t,r){void 0===r&&(r="/");let a=E(("string"==typeof t?c(t):t).pathname||"/",r);if(null==a)return null;let o=y(e);!function(e){e.sort(((e,t)=>e.score!==t.score?t.score-e.score:function(e,t){return e.length===t.length&&e.slice(0,-1).every(((e,r)=>e===t[r]))?e[e.length-1]-t[t.length-1]:0}(e.routesMeta.map((e=>e.childrenIndex)),t.routesMeta.map((e=>e.childrenIndex)))))}(o);let n=null;for(let e=0;null==n&&e{let s={relativePath:void 0===i?e.path||"":i,caseSensitive:!0===e.caseSensitive,childrenIndex:n,route:e};s.relativePath.startsWith("/")&&(o(s.relativePath.startsWith(a),'Absolute route path "'+s.relativePath+'" nested under path "'+a+'" is not valid. An absolute child route path must start with the combined path of all its parent routes.'),s.relativePath=s.relativePath.slice(a.length));let l=j([a,s.relativePath]),c=r.concat(s);e.children&&e.children.length>0&&(o(!0!==e.index,'Index routes must not have child routes. Please remove all child routes from route path "'+l+'".'),y(e.children,t,c,l)),(null!=e.path||e.index)&&t.push({path:l,score:w(l,e.index),routesMeta:c})};return e.forEach(((e,t)=>{var r;if(""!==e.path&&null!=(r=e.path)&&r.includes("?"))for(let r of v(e.path))n(e,t,r);else n(e,t)})),t}function v(e){let t=e.split("/");if(0===t.length)return[];let[r,...a]=t,o=r.endsWith("?"),n=r.replace(/\?$/,"");if(0===a.length)return o?[n,""]:[n];let i=v(a.join("/")),s=[];return s.push(...i.map((e=>""===e?n:[n,e].join("/")))),o&&s.push(...i),s.map((t=>e.startsWith("/")&&""===t?"/":t))}const g=/^:[\w-]+$/,b=e=>"*"===e;function w(e,t){let r=e.split("/"),a=r.length;return r.some(b)&&(a+=-2),t&&(a+=2),r.filter((e=>!b(e))).reduce(((e,t)=>e+(g.test(t)?3:""===t?1:10)),a)}function D(e,t){let{routesMeta:r}=e,a={},o="/",n=[];for(let e=0;e(a.push({paramName:t,isOptional:null!=r}),r?"/?([^\\/]+)?":"/([^\\/]+)")));e.endsWith("*")?(a.push({paramName:"*"}),o+="*"===e||"/*"===e?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?o+="\\/*$":""!==e&&"/"!==e&&(o+="(?:(?=\\/|$))");return[new RegExp(o,t?void 0:"i"),a]}(e.path,e.caseSensitive,e.end),o=t.match(r);if(!o)return null;let i=o[0],s=i.replace(/(.)\/+$/,"$1"),l=o.slice(1);return{params:a.reduce(((e,t,r)=>{let{paramName:a,isOptional:o}=t;if("*"===a){let e=l[r]||"";s=i.slice(0,i.length-e.length).replace(/(.)\/+$/,"$1")}const c=l[r];return e[a]=o&&!c?void 0:function(e,t){try{return decodeURIComponent(e)}catch(r){return n(!1,'The value for the URL param "'+t+'" will not be decoded because the string "'+e+'" is a malformed URL segment. This is probably due to a bad percent encoding ('+r+")."),e}}(c||"",a),e}),{}),pathname:i,pathnameBase:s,pattern:e}}function R(e){try{return decodeURI(e)}catch(t){return n(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent encoding ('+t+")."),e}}function E(e,t){if("/"===t)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let r=t.endsWith("/")?t.length-1:t.length,a=e.charAt(r);return a&&"/"!==a?null:e.slice(r)||"/"}function P(e,t){void 0===t&&(t="/");let{pathname:r,search:a="",hash:o=""}="string"==typeof e?c(e):e,n=r?r.startsWith("/")?r:function(e,t){let r=t.replace(/\/+$/,"").split("/");return e.split("/").forEach((e=>{".."===e?r.length>1&&r.pop():"."!==e&&r.push(e)})),r.length>1?r.join("/"):"/"}(r,t):t;return{pathname:n,search:_(a),hash:T(o)}}function x(e,t,r,a){return"Cannot include a '"+e+"' character in a manually specified `to."+t+"` field ["+JSON.stringify(a)+"]. Please separate it out to the `to."+r+'` field. Alternatively you may provide the full path as a string in and the router will parse it for you.'}function L(e){return e.filter(((e,t)=>0===t||e.route.path&&e.route.path.length>0))}function A(e,t){let r=L(e);return t?r.map(((t,r)=>r===e.length-1?t.pathname:t.pathnameBase)):r.map((e=>e.pathnameBase))}function M(e,r,a,n){let i;void 0===n&&(n=!1),"string"==typeof e?i=c(e):(i=t({},e),o(!i.pathname||!i.pathname.includes("?"),x("?","pathname","search",i)),o(!i.pathname||!i.pathname.includes("#"),x("#","pathname","hash",i)),o(!i.search||!i.search.includes("#"),x("#","search","hash",i)));let s,l=""===e||""===i.pathname,d=l?"/":i.pathname;if(null==d)s=a;else{let e=r.length-1;if(!n&&d.startsWith("..")){let t=d.split("/");for(;".."===t[0];)t.shift(),e-=1;i.pathname=t.join("/")}s=e>=0?r[e]:"/"}let u=P(i,s),h=d&&"/"!==d&&d.endsWith("/"),f=(l||"."===d)&&a.endsWith("/");return u.pathname.endsWith("/")||!h&&!f||(u.pathname+="/"),u}const j=e=>e.join("/").replace(/\/\/+/g,"/"),k=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),_=e=>e&&"?"!==e?e.startsWith("?")?e:"?"+e:"",T=e=>e&&"#"!==e?e.startsWith("#")?e:"#"+e:"";class C extends Error{}class U{constructor(e,t){let r;this.pendingKeysSet=new Set,this.subscribers=new Set,this.deferredKeys=[],o(e&&"object"==typeof e&&!Array.isArray(e),"defer() only accepts plain objects"),this.abortPromise=new Promise(((e,t)=>r=t)),this.controller=new AbortController;let a=()=>r(new C("Deferred data aborted"));this.unlistenAbortSignal=()=>this.controller.signal.removeEventListener("abort",a),this.controller.signal.addEventListener("abort",a),this.data=Object.entries(e).reduce(((e,t)=>{let[r,a]=t;return Object.assign(e,{[r]:this.trackPromise(r,a)})}),{}),this.done&&this.unlistenAbortSignal(),this.init=t}trackPromise(e,t){if(!(t instanceof Promise))return t;this.deferredKeys.push(e),this.pendingKeysSet.add(e);let r=Promise.race([t,this.abortPromise]).then((t=>this.onSettle(r,e,void 0,t)),(t=>this.onSettle(r,e,t)));return r.catch((()=>{})),Object.defineProperty(r,"_tracked",{get:()=>!0}),r}onSettle(e,t,r,a){if(this.controller.signal.aborted&&r instanceof C)return this.unlistenAbortSignal(),Object.defineProperty(e,"_error",{get:()=>r}),Promise.reject(r);if(this.pendingKeysSet.delete(t),this.done&&this.unlistenAbortSignal(),void 0===r&&void 0===a){let r=new Error('Deferred data for key "'+t+'" resolved/rejected with `undefined`, you must resolve/reject with a value or `null`.');return Object.defineProperty(e,"_error",{get:()=>r}),this.emit(!1,t),Promise.reject(r)}return void 0===a?(Object.defineProperty(e,"_error",{get:()=>r}),this.emit(!1,t),Promise.reject(r)):(Object.defineProperty(e,"_data",{get:()=>a}),this.emit(!1,t),a)}emit(e,t){this.subscribers.forEach((r=>r(e,t)))}subscribe(e){return this.subscribers.add(e),()=>this.subscribers.delete(e)}cancel(){this.controller.abort(),this.pendingKeysSet.forEach(((e,t)=>this.pendingKeysSet.delete(t))),this.emit(!0)}async resolveData(e){let t=!1;if(!this.done){let r=()=>this.cancel();e.addEventListener("abort",r),t=await new Promise((t=>{this.subscribe((a=>{e.removeEventListener("abort",r),(a||this.done)&&t(a)}))}))}return t}get done(){return 0===this.pendingKeysSet.size}get unwrappedData(){return o(null!==this.data&&this.done,"Can only unwrap data on initialized and settled deferreds"),Object.entries(this.data).reduce(((e,t)=>{let[r,a]=t;return Object.assign(e,{[r]:O(a)})}),{})}get pendingKeys(){return Array.from(this.pendingKeysSet)}}function O(e){if(!function(e){return e instanceof Promise&&!0===e._tracked}(e))return e;if(e._error)throw e._error;return e._data}const H=function(e,r){void 0===r&&(r=302);let a=r;"number"==typeof a?a={status:a}:void 0===a.status&&(a.status=302);let o=new Headers(a.headers);return o.set("Location",e),new Response(null,t({},a,{headers:o}))};class I{constructor(e,t,r,a){void 0===a&&(a=!1),this.status=e,this.statusText=t||"",this.internal=a,r instanceof Error?(this.data=r.toString(),this.error=r):this.data=r}}function z(e){return null!=e&&"number"==typeof e.status&&"string"==typeof e.statusText&&"boolean"==typeof e.internal&&"data"in e}const q=["post","put","patch","delete"],B=new Set(q),N=["get",...q],F=new Set(N),W=new Set([301,302,303,307,308]),$=new Set([307,308]),K={state:"idle",location:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},J={state:"idle",data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Y={state:"unblocked",proceed:void 0,reset:void 0,location:void 0},V=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,X=e=>({hasErrorBoundary:Boolean(e.hasErrorBoundary)}),G="remix-router-transitions";const Q=Symbol("deferred");function Z(e,t,r,a,o,n,i,s){let c,d;if(i){c=[];for(let e of t)if(c.push(e),e.route.id===i){d=e;break}}else c=t,d=t[t.length-1];let u=M(o||".",A(c,n),E(e.pathname,r)||e.pathname,"path"===s);return null==o&&(u.search=e.search,u.hash=e.hash),null!=o&&""!==o&&"."!==o||!d||!d.route.index||Le(u.search)||(u.search=u.search?u.search.replace(/^\?/,"?index&"):"?index"),a&&"/"!==r&&(u.pathname="/"===u.pathname?r:j([r,u.pathname])),l(u)}function ee(e,t,r,a){if(!a||!function(e){return null!=e&&("formData"in e&&null!=e.formData||"body"in e&&void 0!==e.body)}(a))return{path:r};if(a.formMethod&&!Re(a.formMethod))return{path:r,error:me(405,{method:a.formMethod})};let n,i,s=()=>({path:r,error:me(400,{type:"invalid-body"})}),d=a.formMethod||"get",u=e?d.toUpperCase():d.toLowerCase(),h=ve(r);if(void 0!==a.body){if("text/plain"===a.formEncType){if(!Ee(u))return s();let e="string"==typeof a.body?a.body:a.body instanceof FormData||a.body instanceof URLSearchParams?Array.from(a.body.entries()).reduce(((e,t)=>{let[r,a]=t;return""+e+r+"="+a+"\n"}),""):String(a.body);return{path:r,submission:{formMethod:u,formAction:h,formEncType:a.formEncType,formData:void 0,json:void 0,text:e}}}if("application/json"===a.formEncType){if(!Ee(u))return s();try{let e="string"==typeof a.body?JSON.parse(a.body):a.body;return{path:r,submission:{formMethod:u,formAction:h,formEncType:a.formEncType,formData:void 0,json:e,text:void 0}}}catch(e){return s()}}}if(o("function"==typeof FormData,"FormData is not available in this environment"),a.formData)n=le(a.formData),i=a.formData;else if(a.body instanceof FormData)n=le(a.body),i=a.body;else if(a.body instanceof URLSearchParams)n=a.body,i=ce(n);else if(null==a.body)n=new URLSearchParams,i=new FormData;else try{n=new URLSearchParams(a.body),i=ce(n)}catch(e){return s()}let f={formMethod:u,formAction:h,formEncType:a&&a.formEncType||"application/x-www-form-urlencoded",formData:i,json:void 0,text:void 0};if(Ee(f.formMethod))return{path:r,submission:f};let p=c(r);return t&&p.search&&Le(p.search)&&n.append("index",""),p.search="?"+n,{path:l(p),submission:f}}function te(e,t){let r=e;if(t){let a=e.findIndex((e=>e.route.id===t));a>=0&&(r=e.slice(0,a))}return r}function re(e,r,a,o,n,i,s,l,c,d,u,h,f,m,y,v){let g=v?Object.values(v)[0]:y?Object.values(y)[0]:void 0,b=e.createURL(r.location),w=e.createURL(n),D=v?Object.keys(v)[0]:void 0,S=te(a,D).filter(((e,a)=>{let{route:n}=e;if(n.lazy)return!0;if(null==n.loader)return!1;if(i)return!!n.loader.hydrate||void 0===r.loaderData[n.id]&&(!r.errors||void 0===r.errors[n.id]);if(function(e,t,r){let a=!t||r.route.id!==t.route.id,o=void 0===e[r.route.id];return a||o}(r.loaderData,r.matches[a],e)||l.some((t=>t===e.route.id)))return!0;let c=r.matches[a],d=e;return oe(e,t({currentUrl:b,currentParams:c.params,nextUrl:w,nextParams:d.params},o,{actionResult:g,defaultShouldRevalidate:s||b.pathname+b.search===w.pathname+w.search||b.search!==w.search||ae(c,d)}))})),R=[];return u.forEach(((e,n)=>{if(i||!a.some((t=>t.route.id===e.routeId))||d.has(n))return;let l=p(f,e.path,m);if(!l)return void R.push({key:n,routeId:e.routeId,path:e.path,matches:null,match:null,controller:null});let u=r.fetchers.get(n),y=Ae(l,e.path),v=!1;v=!h.has(n)&&(!!c.includes(n)||(u&&"idle"!==u.state&&void 0===u.data?s:oe(y,t({currentUrl:b,currentParams:r.matches[r.matches.length-1].params,nextUrl:w,nextParams:a[a.length-1].params},o,{actionResult:g,defaultShouldRevalidate:s})))),v&&R.push({key:n,routeId:e.routeId,path:e.path,matches:l,match:y,controller:new AbortController})})),[S,R]}function ae(e,t){let r=e.route.path;return e.pathname!==t.pathname||null!=r&&r.endsWith("*")&&e.params["*"]!==t.params["*"]}function oe(e,t){if(e.route.shouldRevalidate){let r=e.route.shouldRevalidate(t);if("boolean"==typeof r)return r}return t.defaultShouldRevalidate}async function ne(e,r,a){if(!e.lazy)return;let i=await e.lazy();if(!e.lazy)return;let s=a[e.id];o(s,"No route found in manifest");let l={};for(let e in i){let t=void 0!==s[e]&&"hasErrorBoundary"!==e;n(!t,'Route "'+s.id+'" has a static property "'+e+'" defined but its lazy function is also returning a value for this property. The lazy route property "'+e+'" will be ignored.'),t||h.has(e)||(l[e]=i[e])}Object.assign(s,l),Object.assign(s,t({},r(s),{lazy:void 0}))}async function ie(e,t,r,a,n,i,s,l,c){let d,h,f;void 0===c&&(c={});let p=e=>{let a,o=new Promise(((e,t)=>a=t));return f=()=>a(),t.signal.addEventListener("abort",f),Promise.race([e({request:t,params:r.params,context:c.requestContext}),o])};try{let a=r.route[e];if(r.route.lazy)if(a){let e,t=await Promise.all([p(a).catch((t=>{e=t})),ne(r.route,i,n)]);if(e)throw e;h=t[0]}else{if(await ne(r.route,i,n),a=r.route[e],!a){if("action"===e){let e=new URL(t.url),a=e.pathname+e.search;throw me(405,{method:t.method,pathname:a,routeId:r.route.id})}return{type:u.data,data:void 0}}h=await p(a)}else{if(!a){let e=new URL(t.url);throw me(404,{pathname:e.pathname+e.search})}h=await p(a)}o(void 0!==h,"You defined "+("action"===e?"an action":"a loader")+' for route "'+r.route.id+"\" but didn't return anything from your `"+e+"` function. Please return a value or `null`.")}catch(e){d=u.error,h=e}finally{f&&t.signal.removeEventListener("abort",f)}if(Se(h)){let e,n=h.status;if(W.has(n)){let e=h.headers.get("Location");if(o(e,"Redirects returned/thrown from loaders/actions must have a Location header"),V.test(e)){if(!c.isStaticRequest){let r=new URL(t.url),a=e.startsWith("//")?new URL(r.protocol+e):new URL(e),o=null!=E(a.pathname,s);a.origin===r.origin&&o&&(e=a.pathname+a.search+a.hash)}}else e=Z(new URL(t.url),a.slice(0,a.indexOf(r)+1),s,!0,e,l);if(c.isStaticRequest)throw h.headers.set("Location",e),h;return{type:u.redirect,status:n,location:e,revalidate:null!==h.headers.get("X-Remix-Revalidate"),reloadDocument:null!==h.headers.get("X-Remix-Reload-Document")}}if(c.isRouteRequest){throw{type:d===u.error?u.error:u.data,response:h}}try{let t=h.headers.get("Content-Type");e=t&&/\bapplication\/json\b/.test(t)?null==h.body?null:await h.json():await h.text()}catch(e){return{type:u.error,error:e}}return d===u.error?{type:d,error:new I(n,h.statusText,e),headers:h.headers}:{type:u.data,data:e,statusCode:h.status,headers:h.headers}}return d===u.error?{type:d,error:h}:De(h)?{type:u.deferred,deferredData:h,statusCode:null==(m=h.init)?void 0:m.status,headers:(null==(y=h.init)?void 0:y.headers)&&new Headers(h.init.headers)}:{type:u.data,data:h};var m,y}function se(e,t,r,a){let o=e.createURL(ve(t)).toString(),n={signal:r};if(a&&Ee(a.formMethod)){let{formMethod:e,formEncType:t}=a;n.method=e.toUpperCase(),"application/json"===t?(n.headers=new Headers({"Content-Type":t}),n.body=JSON.stringify(a.json)):"text/plain"===t?n.body=a.text:"application/x-www-form-urlencoded"===t&&a.formData?n.body=le(a.formData):n.body=a.formData}return new Request(o,n)}function le(e){let t=new URLSearchParams;for(let[r,a]of e.entries())t.append(r,"string"==typeof a?a:a.name);return t}function ce(e){let t=new FormData;for(let[r,a]of e.entries())t.append(r,a);return t}function de(e,t,r,a,n){let i,s={},l=null,c=!1,d={};return r.forEach(((r,u)=>{let h=t[u].route.id;if(o(!we(r),"Cannot handle redirect results in processLoaderData"),be(r)){let t=fe(e,h),o=r.error;a&&(o=Object.values(a)[0],a=void 0),l=l||{},null==l[t.route.id]&&(l[t.route.id]=o),s[h]=void 0,c||(c=!0,i=z(r.error)?r.error.status:500),r.headers&&(d[h]=r.headers)}else ge(r)?(n.set(h,r.deferredData),s[h]=r.deferredData.data):s[h]=r.data,null==r.statusCode||200===r.statusCode||c||(i=r.statusCode),r.headers&&(d[h]=r.headers)})),a&&(l=a,s[Object.keys(a)[0]]=void 0),{loaderData:s,errors:l,statusCode:i||200,loaderHeaders:d}}function ue(e,r,a,n,i,s,l,c){let{loaderData:d,errors:u}=de(r,a,n,i,c);for(let r=0;re.route.id===t))+1):[...e]).reverse().find((e=>!0===e.route.hasErrorBoundary))||e[0]}function pe(e){let t=1===e.length?e[0]:e.find((e=>e.index||!e.path||"/"===e.path))||{id:"__shim-error-route__"};return{matches:[{params:{},pathname:"",pathnameBase:"",route:t}],route:t}}function me(e,t){let{pathname:r,routeId:a,method:o,type:n}=void 0===t?{}:t,i="Unknown Server Error",s="Unknown @remix-run/router error";return 400===e?(i="Bad Request",o&&r&&a?s="You made a "+o+' request to "'+r+'" but did not provide a `loader` for route "'+a+'", so there is no way to handle the request.':"defer-action"===n?s="defer() is not supported in actions":"invalid-body"===n&&(s="Unable to encode submission body")):403===e?(i="Forbidden",s='Route "'+a+'" does not match URL "'+r+'"'):404===e?(i="Not Found",s='No route matches URL "'+r+'"'):405===e&&(i="Method Not Allowed",o&&r&&a?s="You made a "+o.toUpperCase()+' request to "'+r+'" but did not provide an `action` for route "'+a+'", so there is no way to handle the request.':o&&(s='Invalid request method "'+o.toUpperCase()+'"')),new I(e||500,i,new Error(s),!0)}function ye(e){for(let t=e.length-1;t>=0;t--){let r=e[t];if(we(r))return{result:r,idx:t}}}function ve(e){return l(t({},"string"==typeof e?c(e):e,{hash:""}))}function ge(e){return e.type===u.deferred}function be(e){return e.type===u.error}function we(e){return(e&&e.type)===u.redirect}function De(e){let t=e;return t&&"object"==typeof t&&"object"==typeof t.data&&"function"==typeof t.subscribe&&"function"==typeof t.cancel&&"function"==typeof t.resolveData}function Se(e){return null!=e&&"number"==typeof e.status&&"string"==typeof e.statusText&&"object"==typeof e.headers&&void 0!==e.body}function Re(e){return F.has(e.toLowerCase())}function Ee(e){return B.has(e.toLowerCase())}async function Pe(e,t,r,a,n,i){for(let s=0;se.route.id===c.route.id)),u=null!=d&&!ae(d,c)&&void 0!==(i&&i[c.route.id]);if(ge(l)&&(n||u)){let e=a[s];o(e,"Expected an AbortSignal for revalidating fetcher deferred result"),await xe(l,e,n).then((e=>{e&&(r[s]=e||r[s])}))}}}async function xe(e,t,r){if(void 0===r&&(r=!1),!await e.deferredData.resolveData(t)){if(r)try{return{type:u.data,data:e.deferredData.unwrappedData}}catch(e){return{type:u.error,error:e}}return{type:u.data,data:e.deferredData.data}}}function Le(e){return new URLSearchParams(e).getAll("index").some((e=>""===e))}function Ae(e,t){let r="string"==typeof t?c(t).search:t.search;if(e[e.length-1].route.index&&Le(r||""))return e[e.length-1];let a=L(e);return a[a.length-1]}function Me(e){let{formMethod:t,formAction:r,formEncType:a,text:o,formData:n,json:i}=e;if(t&&r&&a)return null!=o?{formMethod:t,formAction:r,formEncType:a,formData:void 0,json:void 0,text:o}:null!=n?{formMethod:t,formAction:r,formEncType:a,formData:n,json:void 0,text:void 0}:void 0!==i?{formMethod:t,formAction:r,formEncType:a,formData:void 0,json:i,text:void 0}:void 0}function je(e,t){if(t){return{state:"loading",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}return{state:"loading",location:e,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function ke(e,t){return{state:"submitting",location:e,formMethod:t.formMethod,formAction:t.formAction,formEncType:t.formEncType,formData:t.formData,json:t.json,text:t.text}}function _e(e,t){if(e){return{state:"loading",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}}return{state:"loading",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function Te(e){return{state:"idle",formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}e.AbortedDeferredError=C,e.Action=r,e.IDLE_BLOCKER=Y,e.IDLE_FETCHER=J,e.IDLE_NAVIGATION=K,e.UNSAFE_DEFERRED_SYMBOL=Q,e.UNSAFE_DeferredData=U,e.UNSAFE_ErrorResponseImpl=I,e.UNSAFE_convertRouteMatchToUiMatch=m,e.UNSAFE_convertRoutesToDataRoutes=f,e.UNSAFE_getResolveToMatches=A,e.UNSAFE_invariant=o,e.UNSAFE_warning=n,e.createBrowserHistory=function(e){return void 0===e&&(e={}),d((function(e,t){let{pathname:r,search:a,hash:o}=e.location;return s("",{pathname:r,search:a,hash:o},t.state&&t.state.usr||null,t.state&&t.state.key||"default")}),(function(e,t){return"string"==typeof t?t:l(t)}),null,e)},e.createHashHistory=function(e){return void 0===e&&(e={}),d((function(e,t){let{pathname:r="/",search:a="",hash:o=""}=c(e.location.hash.substr(1));return r.startsWith("/")||r.startsWith(".")||(r="/"+r),s("",{pathname:r,search:a,hash:o},t.state&&t.state.usr||null,t.state&&t.state.key||"default")}),(function(e,t){let r=e.document.querySelector("base"),a="";if(r&&r.getAttribute("href")){let t=e.location.href,r=t.indexOf("#");a=-1===r?t:t.slice(0,r)}return a+"#"+("string"==typeof t?t:l(t))}),(function(e,t){n("/"===e.pathname.charAt(0),"relative pathnames are not supported in hash history.push("+JSON.stringify(t)+")")}),e)},e.createMemoryHistory=function(e){void 0===e&&(e={});let t,{initialEntries:a=["/"],initialIndex:o,v5Compat:i=!1}=e;t=a.map(((e,t)=>m(e,"string"==typeof e?null:e.state,0===t?"default":void 0)));let d=f(null==o?t.length-1:o),u=r.Pop,h=null;function f(e){return Math.min(Math.max(e,0),t.length-1)}function p(){return t[d]}function m(e,r,a){void 0===r&&(r=null);let o=s(t?p().pathname:"/",e,r,a);return n("/"===o.pathname.charAt(0),"relative pathnames are not supported in memory history: "+JSON.stringify(e)),o}function y(e){return"string"==typeof e?e:l(e)}return{get index(){return d},get action(){return u},get location(){return p()},createHref:y,createURL:e=>new URL(y(e),"http://localhost"),encodeLocation(e){let t="string"==typeof e?c(e):e;return{pathname:t.pathname||"",search:t.search||"",hash:t.hash||""}},push(e,a){u=r.Push;let o=m(e,a);d+=1,t.splice(d,t.length,o),i&&h&&h({action:u,location:o,delta:1})},replace(e,a){u=r.Replace;let o=m(e,a);t[d]=o,i&&h&&h({action:u,location:o,delta:0})},go(e){u=r.Pop;let a=f(d+e),o=t[a];d=a,h&&h({action:u,location:o,delta:e})},listen:e=>(h=e,()=>{h=null})}},e.createPath=l,e.createRouter=function(e){const a=e.window?e.window:"undefined"!=typeof window?window:void 0,i=void 0!==a&&void 0!==a.document&&void 0!==a.document.createElement,l=!i;let c;if(o(e.routes.length>0,"You must provide a non-empty routes array to createRouter"),e.mapRouteProperties)c=e.mapRouteProperties;else if(e.detectErrorBoundary){let t=e.detectErrorBoundary;c=e=>({hasErrorBoundary:t(e)})}else c=X;let d,h,y={},v=f(e.routes,c,void 0,y),g=e.basename||"/",b=t({v7_fetcherPersist:!1,v7_normalizeFormMethod:!1,v7_partialHydration:!1,v7_prependBasename:!1,v7_relativeSplatPath:!1},e.future),w=null,D=new Set,S=null,R=null,P=null,x=null!=e.hydrationData,L=p(v,e.history.location,g),A=null;if(null==L){let t=me(404,{pathname:e.history.location.pathname}),{matches:r,route:a}=pe(v);L=r,A={[a.id]:t}}let M,j=L.some((e=>e.route.lazy)),k=L.some((e=>e.route.loader));if(j)h=!1;else if(k)if(b.v7_partialHydration){let t=e.hydrationData?e.hydrationData.loaderData:null,r=e.hydrationData?e.hydrationData.errors:null;h=L.every((e=>e.route.loader&&!0!==e.route.loader.hydrate&&(t&&void 0!==t[e.route.id]||r&&void 0!==r[e.route.id])))}else h=null!=e.hydrationData;else h=!0;let _,T={historyAction:e.history.action,location:e.history.location,matches:L,initialized:h,navigation:K,restoreScrollPosition:null==e.hydrationData&&null,preventScrollReset:!1,revalidation:"idle",loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||A,fetchers:new Map,blockers:new Map},C=r.Pop,U=!1,O=!1,H=new Map,I=null,z=!1,q=!1,B=[],N=[],F=new Map,W=0,Q=-1,te=new Map,ae=new Set,oe=new Map,ne=new Map,le=new Set,ce=new Map,de=new Map,ve=!1;function De(e,r){void 0===r&&(r={}),T=t({},T,e);let a=[],o=[];b.v7_fetcherPersist&&T.fetchers.forEach(((e,t)=>{"idle"===e.state&&(le.has(t)?o.push(t):a.push(t))})),[...D].forEach((e=>e(T,{deletedFetchers:o,unstable_viewTransitionOpts:r.viewTransitionOpts,unstable_flushSync:!0===r.flushSync}))),b.v7_fetcherPersist&&(a.forEach((e=>T.fetchers.delete(e))),o.forEach((e=>ze(e))))}function Se(a,o,n){var i,s;let l,{flushSync:c}=void 0===n?{}:n,u=null!=T.actionData&&null!=T.navigation.formMethod&&Ee(T.navigation.formMethod)&&"loading"===T.navigation.state&&!0!==(null==(i=a.state)?void 0:i._isRedirect);l=o.actionData?Object.keys(o.actionData).length>0?o.actionData:null:u?T.actionData:null;let h=o.loaderData?he(T.loaderData,o.loaderData,o.matches||[],o.errors):T.loaderData,f=T.blockers;f.size>0&&(f=new Map(f),f.forEach(((e,t)=>f.set(t,Y))));let p,m=!0===U||null!=T.navigation.formMethod&&Ee(T.navigation.formMethod)&&!0!==(null==(s=a.state)?void 0:s._isRedirect);if(d&&(v=d,d=void 0),z||C===r.Pop||(C===r.Push?e.history.push(a,a.state):C===r.Replace&&e.history.replace(a,a.state)),C===r.Pop){let e=H.get(T.location.pathname);e&&e.has(a.pathname)?p={currentLocation:T.location,nextLocation:a}:H.has(a.pathname)&&(p={currentLocation:a,nextLocation:T.location})}else if(O){let e=H.get(T.location.pathname);e?e.add(a.pathname):(e=new Set([a.pathname]),H.set(T.location.pathname,e)),p={currentLocation:T.location,nextLocation:a}}De(t({},o,{actionData:l,loaderData:h,historyAction:C,location:a,initialized:!0,navigation:K,revalidation:"idle",restoreScrollPosition:Ve(a,o.matches||T.matches),preventScrollReset:m,blockers:f}),{viewTransitionOpts:p,flushSync:!0===c}),C=r.Pop,U=!1,O=!1,z=!1,q=!1,B=[],N=[]}async function Re(a,o,n){_&&_.abort(),_=null,C=a,z=!0===(n&&n.startUninterruptedRevalidation),function(e,t){if(S&&P){let r=Ye(e,t);S[r]=P()}}(T.location,T.matches),U=!0===(n&&n.preventScrollReset),O=!0===(n&&n.enableViewTransition);let i=d||v,s=n&&n.overrideNavigation,l=p(i,o,g),h=!0===(n&&n.flushSync);if(!l){let e=me(404,{pathname:o.pathname}),{matches:t,route:r}=pe(i);return Je(),void Se(o,{matches:t,loaderData:{},errors:{[r.id]:e}},{flushSync:h})}if(T.initialized&&!q&&function(e,t){if(e.pathname!==t.pathname||e.search!==t.search)return!1;if(""===e.hash)return""!==t.hash;if(e.hash===t.hash)return!0;if(""!==t.hash)return!0;return!1}(T.location,o)&&!(n&&n.submission&&Ee(n.submission.formMethod)))return void Se(o,{matches:l},{flushSync:h});_=new AbortController;let f,m,w=se(e.history,o,_.signal,n&&n.submission);if(n&&n.pendingError)m={[fe(l).route.id]:n.pendingError};else if(n&&n.submission&&Ee(n.submission.formMethod)){let e=await async function(e,t,a,o,n){void 0===n&&(n={});let i;Ue(),De({navigation:ke(t,a)},{flushSync:!0===n.flushSync});let s=Ae(o,t);if(s.route.action||s.route.lazy){if(i=await ie("action",e,s,o,y,c,g,b.v7_relativeSplatPath),e.signal.aborted)return{shortCircuited:!0}}else i={type:u.error,error:me(405,{method:e.method,pathname:t.pathname,routeId:s.route.id})};if(we(i)){let e;return e=n&&null!=n.replace?n.replace:i.location===T.location.pathname+T.location.search,await Le(T,i,{submission:a,replace:e}),{shortCircuited:!0}}if(be(i)){let e=fe(o,s.route.id);return!0!==(n&&n.replace)&&(C=r.Push),{pendingActionData:{},pendingActionError:{[e.route.id]:i.error}}}if(ge(i))throw me(400,{type:"defer-action"});return{pendingActionData:{[s.route.id]:i.data}}}(w,o,n.submission,l,{replace:n.replace,flushSync:h});if(e.shortCircuited)return;f=e.pendingActionData,m=e.pendingActionError,s=je(o,n.submission),h=!1,w=new Request(w.url,{signal:w.signal})}let{shortCircuited:D,loaderData:R,errors:E}=await async function(r,a,o,n,i,s,l,c,u,h,f){let p=n||je(a,i),m=i||s||Me(p),y=d||v,[w,D]=re(e.history,T,o,m,a,b.v7_partialHydration&&!0===c,q,B,N,le,oe,ae,y,g,h,f);if(Je((e=>!(o&&o.some((t=>t.route.id===e)))||w&&w.some((t=>t.route.id===e)))),Q=++W,0===w.length&&0===D.length){let e=Ne();return Se(a,t({matches:o,loaderData:{},errors:f||null},h?{actionData:h}:{},e?{fetchers:new Map(T.fetchers)}:{}),{flushSync:u}),{shortCircuited:!0}}if(!(z||b.v7_partialHydration&&c)){D.forEach((e=>{let t=T.fetchers.get(e.key),r=_e(void 0,t?t.data:void 0);T.fetchers.set(e.key,r)}));let e=h||T.actionData;De(t({navigation:p},e?0===Object.keys(e).length?{actionData:null}:{actionData:e}:{},D.length>0?{fetchers:new Map(T.fetchers)}:{}),{flushSync:u})}D.forEach((e=>{F.has(e.key)&&qe(e.key),e.controller&&F.set(e.key,e.controller)}));let S=()=>D.forEach((e=>qe(e.key)));_&&_.signal.addEventListener("abort",S);let{results:R,loaderResults:E,fetcherResults:P}=await Ce(T.matches,o,w,D,r);if(r.signal.aborted)return{shortCircuited:!0};_&&_.signal.removeEventListener("abort",S);D.forEach((e=>F.delete(e.key)));let x=ye(R);if(x){if(x.idx>=w.length){let e=D[x.idx-w.length].key;ae.add(e)}return await Le(T,x.result,{replace:l}),{shortCircuited:!0}}let{loaderData:L,errors:A}=ue(T,o,w,E,f,D,P,ce);ce.forEach(((e,t)=>{e.subscribe((r=>{(r||e.done)&&ce.delete(t)}))}));let M=Ne(),j=Fe(Q),k=M||j||D.length>0;return t({loaderData:L,errors:A},k?{fetchers:new Map(T.fetchers)}:{})}(w,o,l,s,n&&n.submission,n&&n.fetcherSubmission,n&&n.replace,n&&!0===n.initialHydration,h,f,m);D||(_=null,Se(o,t({matches:l},f?{actionData:f}:{},{loaderData:R,errors:E})))}async function Le(n,l,c){let{submission:d,fetcherSubmission:u,replace:h}=void 0===c?{}:c;l.revalidate&&(q=!0);let f=s(n.location,l.location,{_isRedirect:!0});if(o(f,"Expected a location on the redirect navigation"),i){let t=!1;if(l.reloadDocument)t=!0;else if(V.test(l.location)){const r=e.history.createURL(l.location);t=r.origin!==a.location.origin||null==E(r.pathname,g)}if(t)return void(h?a.location.replace(l.location):a.location.assign(l.location))}_=null;let p=!0===h?r.Replace:r.Push,{formMethod:m,formAction:y,formEncType:v}=n.navigation;!d&&!u&&m&&y&&v&&(d=Me(n.navigation));let b=d||u;if($.has(l.status)&&b&&Ee(b.formMethod))await Re(p,f,{submission:t({},b,{formAction:l.location}),preventScrollReset:U});else{let e=je(f,d);await Re(p,f,{overrideNavigation:e,fetcherSubmission:u,preventScrollReset:U})}}async function Ce(t,r,a,o,n){let i=await Promise.all([...a.map((e=>ie("loader",n,e,r,y,c,g,b.v7_relativeSplatPath))),...o.map((t=>{if(t.matches&&t.match&&t.controller)return ie("loader",se(e.history,t.path,t.controller.signal),t.match,t.matches,y,c,g,b.v7_relativeSplatPath);return{type:u.error,error:me(404,{pathname:t.path})}}))]),s=i.slice(0,a.length),l=i.slice(a.length);return await Promise.all([Pe(t,a,s,s.map((()=>n.signal)),!1,T.loaderData),Pe(t,o.map((e=>e.match)),l,o.map((e=>e.controller?e.controller.signal:null)),!0)]),{results:i,loaderResults:s,fetcherResults:l}}function Ue(){q=!0,B.push(...Je()),oe.forEach(((e,t)=>{F.has(t)&&(N.push(t),qe(t))}))}function Oe(e,t,r){void 0===r&&(r={}),T.fetchers.set(e,t),De({fetchers:new Map(T.fetchers)},{flushSync:!0===(r&&r.flushSync)})}function He(e,t,r,a){void 0===a&&(a={});let o=fe(T.matches,t);ze(e),De({errors:{[o.route.id]:r},fetchers:new Map(T.fetchers)},{flushSync:!0===(a&&a.flushSync)})}function Ie(e){return b.v7_fetcherPersist&&(ne.set(e,(ne.get(e)||0)+1),le.has(e)&&le.delete(e)),T.fetchers.get(e)||J}function ze(e){let t=T.fetchers.get(e);!F.has(e)||t&&"loading"===t.state&&te.has(e)||qe(e),oe.delete(e),te.delete(e),ae.delete(e),le.delete(e),T.fetchers.delete(e)}function qe(e){let t=F.get(e);o(t,"Expected fetch controller: "+e),t.abort(),F.delete(e)}function Be(e){for(let t of e){let e=Te(Ie(t).data);T.fetchers.set(t,e)}}function Ne(){let e=[],t=!1;for(let r of ae){let a=T.fetchers.get(r);o(a,"Expected fetcher: "+r),"loading"===a.state&&(ae.delete(r),e.push(r),t=!0)}return Be(e),t}function Fe(e){let t=[];for(let[r,a]of te)if(a0}function We(e){T.blockers.delete(e),de.delete(e)}function $e(e,t){let r=T.blockers.get(e)||Y;o("unblocked"===r.state&&"blocked"===t.state||"blocked"===r.state&&"blocked"===t.state||"blocked"===r.state&&"proceeding"===t.state||"blocked"===r.state&&"unblocked"===t.state||"proceeding"===r.state&&"unblocked"===t.state,"Invalid blocker state transition: "+r.state+" -> "+t.state);let a=new Map(T.blockers);a.set(e,t),De({blockers:a})}function Ke(e){let{currentLocation:t,nextLocation:r,historyAction:a}=e;if(0===de.size)return;de.size>1&&n(!1,"A router only supports one blocker at a time");let o=Array.from(de.entries()),[i,s]=o[o.length-1],l=T.blockers.get(i);return l&&"proceeding"===l.state?void 0:s({currentLocation:t,nextLocation:r,historyAction:a})?i:void 0}function Je(e){let t=[];return ce.forEach(((r,a)=>{e&&!e(a)||(r.cancel(),t.push(a),ce.delete(a))})),t}function Ye(e,t){if(R){return R(e,t.map((e=>m(e,T.loaderData))))||e.key}return e.key}function Ve(e,t){if(S){let r=Ye(e,t),a=S[r];if("number"==typeof a)return a}return null}return M={get basename(){return g},get future(){return b},get state(){return T},get routes(){return v},get window(){return a},initialize:function(){if(w=e.history.listen((t=>{let{action:r,location:a,delta:o}=t;if(ve)return void(ve=!1);n(0===de.size||null!=o,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let i=Ke({currentLocation:T.location,nextLocation:a,historyAction:r});return i&&null!=o?(ve=!0,e.history.go(-1*o),void $e(i,{state:"blocked",location:a,proceed(){$e(i,{state:"proceeding",proceed:void 0,reset:void 0,location:a}),e.history.go(o)},reset(){let e=new Map(T.blockers);e.set(i,Y),De({blockers:e})}})):Re(r,a)})),i){!function(e,t){try{let r=e.sessionStorage.getItem(G);if(r){let e=JSON.parse(r);for(let[r,a]of Object.entries(e||{}))a&&Array.isArray(a)&&t.set(r,new Set(a||[]))}}catch(e){}}(a,H);let e=()=>function(e,t){if(t.size>0){let r={};for(let[e,a]of t)r[e]=[...a];try{e.sessionStorage.setItem(G,JSON.stringify(r))}catch(e){n(!1,"Failed to save applied view transitions in sessionStorage ("+e+").")}}}(a,H);a.addEventListener("pagehide",e),I=()=>a.removeEventListener("pagehide",e)}return T.initialized||Re(r.Pop,T.location,{initialHydration:!0}),M},subscribe:function(e){return D.add(e),()=>D.delete(e)},enableScrollRestoration:function(e,t,r){if(S=e,P=t,R=r||null,!x&&T.navigation===K){x=!0;let e=Ve(T.location,T.matches);null!=e&&De({restoreScrollPosition:e})}return()=>{S=null,P=null,R=null}},navigate:async function a(o,n){if("number"==typeof o)return void e.history.go(o);let i=Z(T.location,T.matches,g,b.v7_prependBasename,o,b.v7_relativeSplatPath,null==n?void 0:n.fromRouteId,null==n?void 0:n.relative),{path:l,submission:c,error:d}=ee(b.v7_normalizeFormMethod,!1,i,n),u=T.location,h=s(T.location,l,n&&n.state);h=t({},h,e.history.encodeLocation(h));let f=n&&null!=n.replace?n.replace:void 0,p=r.Push;!0===f?p=r.Replace:!1===f||null!=c&&Ee(c.formMethod)&&c.formAction===T.location.pathname+T.location.search&&(p=r.Replace);let m=n&&"preventScrollReset"in n?!0===n.preventScrollReset:void 0,y=!0===(n&&n.unstable_flushSync),v=Ke({currentLocation:u,nextLocation:h,historyAction:p});if(!v)return await Re(p,h,{submission:c,pendingError:d,preventScrollReset:m,replace:n&&n.replace,enableViewTransition:n&&n.unstable_viewTransition,flushSync:y});$e(v,{state:"blocked",location:h,proceed(){$e(v,{state:"proceeding",proceed:void 0,reset:void 0,location:h}),a(o,n)},reset(){let e=new Map(T.blockers);e.set(v,Y),De({blockers:e})}})},fetch:function(t,r,a,n){if(l)throw new Error("router.fetch() was called during the server render, but it shouldn't be. You are likely calling a useFetcher() method in the body of your component. Try moving it to a useEffect or a callback.");F.has(t)&&qe(t);let i=!0===(n&&n.unstable_flushSync),s=d||v,u=Z(T.location,T.matches,g,b.v7_prependBasename,a,b.v7_relativeSplatPath,r,null==n?void 0:n.relative),h=p(s,u,g);if(!h)return void He(t,r,me(404,{pathname:u}),{flushSync:i});let{path:f,submission:m,error:w}=ee(b.v7_normalizeFormMethod,!0,u,n);if(w)return void He(t,r,w,{flushSync:i});let D=Ae(h,f);U=!0===(n&&n.preventScrollReset),m&&Ee(m.formMethod)?async function(t,r,a,n,i,s,l){if(Ue(),oe.delete(t),!n.route.action&&!n.route.lazy){let e=me(405,{method:l.formMethod,pathname:a,routeId:r});return void He(t,r,e,{flushSync:s})}let u=T.fetchers.get(t);Oe(t,function(e,t){return{state:"submitting",formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}(l,u),{flushSync:s});let h=new AbortController,f=se(e.history,a,h.signal,l);F.set(t,h);let m=W,w=await ie("action",f,n,i,y,c,g,b.v7_relativeSplatPath);if(f.signal.aborted)return void(F.get(t)===h&&F.delete(t));if(b.v7_fetcherPersist&&le.has(t)){if(we(w)||be(w))return void Oe(t,Te(void 0))}else{if(we(w))return F.delete(t),Q>m?void Oe(t,Te(void 0)):(ae.add(t),Oe(t,_e(l)),Le(T,w,{fetcherSubmission:l}));if(be(w))return void He(t,r,w.error)}if(ge(w))throw me(400,{type:"defer-action"});let D=T.navigation.location||T.location,S=se(e.history,D,h.signal),R=d||v,E="idle"!==T.navigation.state?p(R,T.navigation.location,g):T.matches;o(E,"Didn't find any matches after fetcher action");let P=++W;te.set(t,P);let x=_e(l,w.data);T.fetchers.set(t,x);let[L,A]=re(e.history,T,E,l,D,!1,q,B,N,le,oe,ae,R,g,{[n.route.id]:w.data},void 0);A.filter((e=>e.key!==t)).forEach((e=>{let t=e.key,r=T.fetchers.get(t),a=_e(void 0,r?r.data:void 0);T.fetchers.set(t,a),F.has(t)&&qe(t),e.controller&&F.set(t,e.controller)})),De({fetchers:new Map(T.fetchers)});let M=()=>A.forEach((e=>qe(e.key)));h.signal.addEventListener("abort",M);let{results:j,loaderResults:k,fetcherResults:U}=await Ce(T.matches,E,L,A,S);if(h.signal.aborted)return;h.signal.removeEventListener("abort",M),te.delete(t),F.delete(t),A.forEach((e=>F.delete(e.key)));let O=ye(j);if(O){if(O.idx>=L.length){let e=A[O.idx-L.length].key;ae.add(e)}return Le(T,O.result)}let{loaderData:H,errors:I}=ue(T,T.matches,L,k,void 0,A,U,ce);if(T.fetchers.has(t)){let e=Te(w.data);T.fetchers.set(t,e)}Fe(P),"loading"===T.navigation.state&&P>Q?(o(C,"Expected pending action"),_&&_.abort(),Se(T.navigation.location,{matches:E,loaderData:H,errors:I,fetchers:new Map(T.fetchers)})):(De({errors:I,loaderData:he(T.loaderData,H,E,I),fetchers:new Map(T.fetchers)}),q=!1)}(t,r,f,D,h,i,m):(oe.set(t,{routeId:r,path:f}),async function(t,r,a,n,i,s,l){let d=T.fetchers.get(t);Oe(t,_e(l,d?d.data:void 0),{flushSync:s});let u=new AbortController,h=se(e.history,a,u.signal);F.set(t,u);let f=W,p=await ie("loader",h,n,i,y,c,g,b.v7_relativeSplatPath);ge(p)&&(p=await xe(p,h.signal,!0)||p);F.get(t)===u&&F.delete(t);if(h.signal.aborted)return;if(le.has(t))return void Oe(t,Te(void 0));if(we(p))return Q>f?void Oe(t,Te(void 0)):(ae.add(t),void await Le(T,p));if(be(p))return void He(t,r,p.error);o(!ge(p),"Unhandled fetcher deferred data"),Oe(t,Te(p.data))}(t,r,f,D,h,i,m))},revalidate:function(){Ue(),De({revalidation:"loading"}),"submitting"!==T.navigation.state&&("idle"!==T.navigation.state?Re(C||T.historyAction,T.navigation.location,{overrideNavigation:T.navigation}):Re(T.historyAction,T.location,{startUninterruptedRevalidation:!0}))},createHref:t=>e.history.createHref(t),encodeLocation:t=>e.history.encodeLocation(t),getFetcher:Ie,deleteFetcher:function(e){if(b.v7_fetcherPersist){let t=(ne.get(e)||0)-1;t<=0?(ne.delete(e),le.add(e)):ne.set(e,t)}else ze(e);De({fetchers:new Map(T.fetchers)})},dispose:function(){w&&w(),I&&I(),D.clear(),_&&_.abort(),T.fetchers.forEach(((e,t)=>ze(t))),T.blockers.forEach(((e,t)=>We(t)))},getBlocker:function(e,t){let r=T.blockers.get(e)||Y;return de.get(e)!==t&&de.set(e,t),r},deleteBlocker:We,_internalFetchControllers:F,_internalActiveDeferreds:ce,_internalSetRoutes:function(e){y={},d=f(e,c,void 0,y)}},M},e.createStaticHandler=function(e,r){o(e.length>0,"You must provide a non-empty routes array to createStaticHandler");let a,n={},i=(r?r.basename:null)||"/";if(null!=r&&r.mapRouteProperties)a=r.mapRouteProperties;else if(null!=r&&r.detectErrorBoundary){let e=r.detectErrorBoundary;a=t=>({hasErrorBoundary:e(t)})}else a=X;let c=t({v7_relativeSplatPath:!1},r?r.future:null),d=f(e,a,void 0,n);async function h(e,r,s,l,d){o(e.signal,"query()/queryRoute() requests must contain an AbortController signal");try{if(Ee(e.method.toLowerCase())){let o=await async function(e,r,o,s,l){let d;if(o.route.action||o.route.lazy){if(d=await ie("action",e,o,r,n,a,i,c.v7_relativeSplatPath,{isStaticRequest:!0,isRouteRequest:l,requestContext:s}),e.signal.aborted){throw new Error((l?"queryRoute":"query")+"() call aborted: "+e.method+" "+e.url)}}else{let t=me(405,{method:e.method,pathname:new URL(e.url).pathname,routeId:o.route.id});if(l)throw t;d={type:u.error,error:t}}if(we(d))throw new Response(null,{status:d.status,headers:{Location:d.location}});if(ge(d)){let e=me(400,{type:"defer-action"});if(l)throw e;d={type:u.error,error:e}}if(l){if(be(d))throw d.error;return{matches:[o],loaderData:{},actionData:{[o.route.id]:d.data},errors:null,statusCode:200,loaderHeaders:{},actionHeaders:{},activeDeferreds:null}}if(be(d)){let a=fe(r,o.route.id);return t({},await m(e,r,s,void 0,{[a.route.id]:d.error}),{statusCode:z(d.error)?d.error.status:500,actionData:null,actionHeaders:t({},d.headers?{[o.route.id]:d.headers}:{})})}let h=new Request(e.url,{headers:e.headers,redirect:e.redirect,signal:e.signal});return t({},await m(h,r,s),d.statusCode?{statusCode:d.statusCode}:{},{actionData:{[o.route.id]:d.data},actionHeaders:t({},d.headers?{[o.route.id]:d.headers}:{})})}(e,s,d||Ae(s,r),l,null!=d);return o}let o=await m(e,s,l,d);return Se(o)?o:t({},o,{actionData:null,actionHeaders:{}})}catch(e){if((h=e)&&Se(h.response)&&(h.type===u.data||h.type===u.error)){if(e.type===u.error)throw e.response;return e.response}if(function(e){if(!Se(e))return!1;let t=e.status,r=e.headers.get("Location");return t>=300&&t<=399&&null!=r}(e))return e;throw e}var h}async function m(e,r,o,s,l){let d=null!=s;if(d&&(null==s||!s.route.loader)&&(null==s||!s.route.lazy))throw me(400,{method:e.method,pathname:new URL(e.url).pathname,routeId:null==s?void 0:s.route.id});let u=(s?[s]:te(r,Object.keys(l||{})[0])).filter((e=>e.route.loader||e.route.lazy));if(0===u.length)return{matches:r,loaderData:r.reduce(((e,t)=>Object.assign(e,{[t.route.id]:null})),{}),errors:l||null,statusCode:200,loaderHeaders:{},activeDeferreds:null};let h=await Promise.all([...u.map((t=>ie("loader",e,t,r,n,a,i,c.v7_relativeSplatPath,{isStaticRequest:!0,isRouteRequest:d,requestContext:o})))]);if(e.signal.aborted){throw new Error((d?"queryRoute":"query")+"() call aborted: "+e.method+" "+e.url)}let f=new Map,p=de(r,u,h,l,f),m=new Set(u.map((e=>e.route.id)));return r.forEach((e=>{m.has(e.route.id)||(p.loaderData[e.route.id]=null)})),t({},p,{matches:r,activeDeferreds:f.size>0?Object.fromEntries(f.entries()):null})}return{dataRoutes:d,query:async function(e,r){let{requestContext:a}=void 0===r?{}:r,o=new URL(e.url),n=e.method,c=s("",l(o),null,"default"),u=p(d,c,i);if(!Re(n)&&"HEAD"!==n){let e=me(405,{method:n}),{matches:t,route:r}=pe(d);return{basename:i,location:c,matches:t,loaderData:{},actionData:null,errors:{[r.id]:e},statusCode:e.status,loaderHeaders:{},actionHeaders:{},activeDeferreds:null}}if(!u){let e=me(404,{pathname:c.pathname}),{matches:t,route:r}=pe(d);return{basename:i,location:c,matches:t,loaderData:{},actionData:null,errors:{[r.id]:e},statusCode:e.status,loaderHeaders:{},actionHeaders:{},activeDeferreds:null}}let f=await h(e,c,u,a);return Se(f)?f:t({location:c,basename:i},f)},queryRoute:async function(e,t){let{routeId:r,requestContext:a}=void 0===t?{}:t,o=new URL(e.url),n=e.method,c=s("",l(o),null,"default"),u=p(d,c,i);if(!Re(n)&&"HEAD"!==n&&"OPTIONS"!==n)throw me(405,{method:n});if(!u)throw me(404,{pathname:c.pathname});let f=r?u.find((e=>e.route.id===r)):Ae(u,c);if(r&&!f)throw me(403,{pathname:c.pathname,routeId:r});if(!f)throw me(404,{pathname:c.pathname});let m=await h(e,c,u,a,f);if(Se(m))return m;let y=m.errors?Object.values(m.errors)[0]:void 0;if(void 0!==y)throw y;if(m.actionData)return Object.values(m.actionData)[0];if(m.loaderData){var v;let e=Object.values(m.loaderData)[0];return null!=(v=m.activeDeferreds)&&v[f.route.id]&&(e[Q]=m.activeDeferreds[f.route.id]),e}}}},e.defer=function(e,t){return void 0===t&&(t={}),new U(e,"number"==typeof t?{status:t}:t)},e.generatePath=function(e,t){void 0===t&&(t={});let r=e;r.endsWith("*")&&"*"!==r&&!r.endsWith("/*")&&(n(!1,'Route path "'+r+'" will be treated as if it were "'+r.replace(/\*$/,"/*")+'" because the `*` character must always follow a `/` in the pattern. To get rid of this warning, please change the route path to "'+r.replace(/\*$/,"/*")+'".'),r=r.replace(/\*$/,"/*"));const a=r.startsWith("/")?"/":"",i=e=>null==e?"":"string"==typeof e?e:String(e);return a+r.split(/\/+/).map(((e,r,a)=>{if(r===a.length-1&&"*"===e){return i(t["*"])}const n=e.match(/^:([\w-]+)(\??)$/);if(n){const[,e,r]=n;let a=t[e];return o("?"===r||null!=a,'Missing ":'+e+'" param'),i(a)}return e.replace(/\?$/g,"")})).filter((e=>!!e)).join("/")},e.getStaticContextFromError=function(e,r,a){return t({},r,{statusCode:500,errors:{[r._deepestRenderedBoundaryId||e[0].id]:a}})},e.getToPathname=function(e){return""===e||""===e.pathname?"/":"string"==typeof e?c(e).pathname:e.pathname},e.isDeferredData=De,e.isRouteErrorResponse=z,e.joinPaths=j,e.json=function(e,r){void 0===r&&(r={});let a="number"==typeof r?{status:r}:r,o=new Headers(a.headers);return o.has("Content-Type")||o.set("Content-Type","application/json; charset=utf-8"),new Response(JSON.stringify(e),t({},a,{headers:o}))},e.matchPath=S,e.matchRoutes=p,e.normalizePathname=k,e.parsePath=c,e.redirect=H,e.redirectDocument=(e,t)=>{let r=H(e,t);return r.headers.set("X-Remix-Reload-Document","true"),r},e.resolvePath=P,e.resolveTo=M,e.stripBasename=E,Object.defineProperty(e,"__esModule",{value:!0})})); +//# sourceMappingURL=router.umd.min.js.map diff --git a/node_modules/@remix-run/router/dist/router.umd.min.js.map b/node_modules/@remix-run/router/dist/router.umd.min.js.map new file mode 100644 index 0000000..41663f5 --- /dev/null +++ b/node_modules/@remix-run/router/dist/router.umd.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"router.umd.min.js","sources":["../history.ts","../utils.ts","../router.ts"],"sourcesContent":["////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n// TODO: (v7) Change the Location generic default from `any` to `unknown` and\n// remove Remix `useLocation` wrapper.\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: State;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. This may be either a URL or the pieces\n * of a URL path.\n */\nexport type To = string | Partial;\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 * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly {\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 let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n","import type { Location, Path, To } from \"./history\";\nimport { invariant, parsePath, warning } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: 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 statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n status: number;\n location: string;\n revalidate: boolean;\n reloadDocument?: 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\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on ``,\n * useSubmit(), ``, etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n context?: Context;\n}\n\n// TODO: (v7) Change the defaults from any to unknown in and remove Remix wrappers:\n// ActionFunction, ActionFunctionArgs, LoaderFunction, LoaderFunctionArgs\n// Also, make them a type alias instead of an interface\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs\n extends DataFunctionArgs {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable | null;\n\n/**\n * Route loader function signature\n */\nexport type LoaderFunction = {\n (args: LoaderFunctionArgs):\n | Promise\n | DataFunctionValue;\n} & { hydrate?: boolean };\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (args: ActionFunctionArgs):\n | Promise\n | DataFunctionValue;\n}\n\n/**\n * Arguments passed to shouldRevalidate function\n */\nexport interface ShouldRevalidateFunctionArgs {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionResult?: any;\n defaultShouldRevalidate: boolean;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: ShouldRevalidateFunctionArgs): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction {\n (): Promise>>;\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 lazy?: LazyRouteFunction;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record;\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 `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\nexport type PathParam =\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 you 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 mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: number[] = [],\n manifest: RouteManifest = {}\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 !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/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(\n branches[i],\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n safelyDecodeURI(pathname)\n );\n }\n\n return matches;\n}\n\nexport interface UIMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: Data;\n handle: Handle;\n}\n\nexport function convertRouteMatchToUiMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UIMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle,\n };\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch,\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/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\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/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, compiledParams] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = compiledParams.reduce>(\n (memo, { paramName, isOptional }, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = safelyDecodeURIComponent(value || \"\", paramName);\n }\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\ntype CompiledPathParam = { paramName: string; isOptional?: boolean };\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, CompiledPathParam[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let params: CompiledPathParam[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(\n /\\/:([\\w-]+)(\\?)?/g,\n (_: string, paramName: string, isOptional) => {\n params.push({ paramName, isOptional: isOptional != null });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n }\n );\n\n if (path.endsWith(\"*\")) {\n params.push({ paramName: \"*\" });\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, params];\n}\n\nfunction safelyDecodeURI(value: string) {\n try {\n return decodeURI(value);\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\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 * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/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 *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nexport function getResolveToMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[], v7_relativeSplatPath: boolean) {\n let pathMatches = getPathContributingMatches(matches);\n\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) =>\n idx === matches.length - 1 ? match.pathname : match.pathnameBase\n );\n }\n\n return pathMatches.map((match) => match.pathnameBase);\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial;\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 (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\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 pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirectDocument: RedirectFunction = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n\nexport type ErrorResponse = {\n status: number;\n statusText: string;\n data: any;\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nexport class ErrorResponseImpl implements ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n private error?: Error;\n private internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n","import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n ActionFunction,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n AgnosticRouteObject,\n DataResult,\n DeferredData,\n DeferredResult,\n DetectErrorBoundaryFunction,\n ErrorResult,\n FormEncType,\n FormMethod,\n HTMLFormMethod,\n ImmutableRouteKey,\n LoaderFunction,\n MapRoutePropertiesFunction,\n MutationFormMethod,\n RedirectResult,\n RouteData,\n RouteManifest,\n ShouldRevalidateFunctionArgs,\n Submission,\n SuccessResult,\n UIMatch,\n V7_FormMethod,\n V7_MutationFormMethod,\n} from \"./utils\";\nimport {\n ErrorResponseImpl,\n ResultType,\n convertRouteMatchToUiMatch,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n getResolveToMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the future config for the router\n */\n get future(): FutureConfig;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the window associated with the router\n */\n get window(): RouterInit[\"window\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(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 * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\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 * Map of current blockers\n */\n blockers: 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 * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_fetcherPersist: boolean;\n v7_normalizeFormMethod: boolean;\n v7_partialHydration: boolean;\n v7_prependBasename: boolean;\n v7_relativeSplatPath: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record;\n actionHeaders: Record;\n activeDeferreds: Record | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: { requestContext?: unknown }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: { routeId?: string; requestContext?: unknown }\n ): Promise;\n}\n\ntype ViewTransitionOpts = {\n currentLocation: Location;\n nextLocation: Location;\n};\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (\n state: RouterState,\n opts: {\n deletedFetchers: string[];\n unstable_viewTransitionOpts?: ViewTransitionOpts;\n unstable_flushSync: boolean;\n }\n ): void;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UIMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n unstable_flushSync?: boolean;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n unstable_viewTransition?: boolean;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\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 * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\n/**\n * Wrapper object to allow us to throw any response out from callLoaderOrAction\n * for queryRouter while preserving whether or not it was thrown or returned\n * from the loader/action\n */\ninterface QueryRouteResponse {\n type: ResultType.data | ResultType.error;\n response: Response;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\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 // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let 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 error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized: boolean;\n let hasLazyRoutes = initialMatches.some((m) => m.route.lazy);\n let hasLoaders = initialMatches.some((m) => m.route.loader);\n if (hasLazyRoutes) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!hasLoaders) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n initialized = initialMatches.every(\n (m) =>\n m.route.loader &&\n m.route.loader.hydrate !== true &&\n ((loaderData && loaderData[m.route.id] !== undefined) ||\n (errors && errors[m.route.id] !== undefined))\n );\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions: Map> = new Map<\n string,\n Set\n >();\n\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener: (() => void) | null = null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () =>\n persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () =>\n routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location, {\n initialHydration: true,\n });\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(\n newState: Partial,\n opts: {\n flushSync?: boolean;\n viewTransitionOpts?: ViewTransitionOpts;\n } = {}\n ): void {\n state = {\n ...state,\n ...newState,\n };\n\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers: string[] = [];\n let deletedFetchersKeys: string[] = [];\n\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach((subscriber) =>\n subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true,\n })\n );\n\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach((key) => state.fetchers.delete(key));\n deletedFetchersKeys.forEach((key) => deleteFetcher(key));\n }\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 { flushSync }: { flushSync?: boolean } = {}\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n let viewTransitionOpts: ViewTransitionOpts | undefined;\n\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === HistoryAction.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location,\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location,\n };\n }\n\n updateState(\n {\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n },\n {\n viewTransitionOpts,\n flushSync: flushSync === true,\n }\n );\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n 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 | null,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n future.v7_relativeSplatPath,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.unstable_viewTransition,\n flushSync,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n { 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 initialHydration?: boolean;\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponseImpl;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n enableViewTransition?: boolean;\n flushSync?: boolean;\n }\n ): Promise {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(\n location,\n {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n },\n { flushSync }\n );\n return;\n }\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a \n // which will default to a navigation to /page\n if (\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches }, { flushSync });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let 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 (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\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, flushSync }\n );\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n\n // Create a GET request for the loaders\n request = new Request(request.url, { signal: request.signal });\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.fetcherSubmission,\n opts && opts.replace,\n opts && opts.initialHydration === true,\n flushSync,\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 ...(pendingActionData ? { actionData: pendingActionData } : {}),\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; flushSync?: boolean } = {}\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation }, { flushSync: opts.flushSync === true });\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n replace =\n result.location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(state, result, { submission, replace });\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 // Send back an empty object we can use to clear out any prior actionData\n pendingActionData: {},\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\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 fetcherSubmission?: Submission,\n replace?: boolean,\n initialHydration?: boolean,\n flushSync?: 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 =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n future.v7_partialHydration && initialHydration === true,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionData,\n pendingError\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(\n location,\n {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n },\n { flushSync }\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 we have partialHydration enabled, then don't update the state for the\n // initial data load since iot's not a \"navigation\"\n if (\n !isUninterruptedRevalidation &&\n (!future.v7_partialHydration || !initialHydration)\n ) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n let actionData = pendingActionData || state.actionData;\n updateState(\n {\n navigation: loadingNavigation,\n ...(actionData\n ? Object.keys(actionData).length === 0\n ? { actionData: null }\n : { actionData }\n : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n },\n {\n flushSync,\n }\n );\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(state, redirect.result, { 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 let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n future.v7_relativeSplatPath,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath }),\n { flushSync }\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(\n key,\n routeId,\n path,\n match,\n matches,\n flushSync,\n submission\n );\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error, { flushSync });\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync,\n });\n\n // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResult = await callLoaderOrAction(\n \"action\",\n fetchRequest,\n match,\n requestMatches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(state, actionResult, {\n fetcherSubmission: submission,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n false,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n deletedFetchers,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n { [match.route.id]: actionResult.data },\n undefined // No need to send through errors since we short circuit above\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(state, redirect.result);\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 // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n fetchers: new Map(state.fetchers),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n flushSync: boolean,\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(\n key,\n getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n ),\n { flushSync }\n );\n\n // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(state, result);\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n state: RouterState,\n redirect: RedirectResult,\n {\n submission,\n fetcherSubmission,\n replace,\n }: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n replace?: boolean;\n } = {}\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n\n let redirectLocation = createLocation(state.location, redirect.location, {\n _isRedirect: true,\n });\n invariant(\n redirectLocation,\n \"Expected a location on the redirect navigation\"\n );\n\n if (isBrowser) {\n let isDocumentReload = false;\n\n if (redirect.reloadDocument) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(redirect.location)) {\n const url = init.history.createURL(redirect.location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(redirect.location);\n } else {\n routerWindow.location.assign(redirect.location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let { formMethod, formAction, formEncType } = state.navigation;\n if (\n !submission &&\n !fetcherSubmission &&\n formMethod &&\n formAction &&\n formEncType\n ) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (\n redirectPreserveMethodStatusCodes.has(redirect.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: redirect.location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n submission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: 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((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n )\n ),\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n return callLoaderOrAction(\n \"loader\",\n createClientSideRequest(init.history, f.path, f.controller.signal),\n f.match,\n f.matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath\n );\n } else {\n let error: ErrorResult = {\n type: ResultType.error,\n error: getInternalRouterError(404, { pathname: f.path }),\n };\n return error;\n }\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 loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\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 updateFetcherState(\n key: string,\n fetcher: Fetcher,\n opts: { flushSync?: boolean } = {}\n ) {\n state.fetchers.set(key, fetcher);\n updateState(\n { fetchers: new Map(state.fetchers) },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function setFetcherError(\n key: string,\n routeId: string,\n error: any,\n opts: { flushSync?: boolean } = {}\n ) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState(\n {\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n },\n { flushSync: (opts && opts.flushSync) === true }\n );\n }\n\n function getFetcher(key: string): Fetcher {\n if (future.v7_fetcherPersist) {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n\n function deleteFetcherAndUpdateState(key: string): void {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({ fetchers: new Map(state.fetchers) });\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 = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function 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 || null;\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 getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => convertRouteMatchToUiMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface StaticHandlerFutureConfig {\n v7_relativeSplatPath: boolean;\n}\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future: StaticHandlerFutureConfig = {\n v7_relativeSplatPath: false,\n ...(opts ? opts.future : null),\n };\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n */\n async function query(\n request: Request,\n { requestContext }: { requestContext?: unknown } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(request, location, matches, requestContext);\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n }: { requestContext?: unknown; routeId?: string } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n match\n );\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction, we throw\n // it to bail out and then return or throw here based on whether the user\n // returned or threw\n if (isQueryRouteResponse(e)) {\n if (e.type === ResultType.error) {\n throw e.response;\n }\n return e.response;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath,\n { isStaticRequest: true, isRouteRequest, requestContext }\n );\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.status,\n headers: {\n Location: result.location,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n 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(\n request,\n matches,\n requestContext,\n undefined,\n {\n [boundaryMatch.route.id]: result.error,\n }\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 // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n let context = await loadRouteData(loaderRequest, matches, requestContext);\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 requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch,\n pendingActionError?: RouteData\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n );\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n future.v7_relativeSplatPath,\n { isStaticRequest: true, isRouteRequest, requestContext }\n )\n ),\n ]);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(\n `${method}() call aborted: ${request.method} ${request.url}`\n );\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError,\n activeDeferreds\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n 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\nfunction isSubmissionNavigation(\n opts: BaseNavigateOrFetchOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n v7_relativeSplatPath: boolean,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getResolveToMatches(contextualMatches, v7_relativeSplatPath),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: BaseNavigateOrFetchOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponseImpl;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes 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 history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isInitialLoad: boolean,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n deletedFetchers: Set,\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : undefined;\n\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let { route } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n\n if (route.loader == null) {\n return false;\n }\n\n if (isInitialLoad) {\n if (route.loader.hydrate) {\n return true;\n }\n return (\n state.loaderData[route.id] === undefined &&\n // Don't re-run if the loader ran and threw an error\n (!state.errors || state.errors[route.id] === undefined)\n );\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n defaultShouldRevalidate:\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial load (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (\n isInitialLoad ||\n !matches.some((m) => m.route.id === f.routeId) ||\n deletedFetchers.has(key)\n ) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.includes(key)) {\n // Always revalidate if the fetcher was cancelled\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n defaultShouldRevalidate: isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: ShouldRevalidateFunctionArgs\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n basename: string,\n v7_relativeSplatPath: boolean,\n opts: {\n isStaticRequest?: boolean;\n isRouteRequest?: boolean;\n requestContext?: unknown;\n } = {}\n): Promise {\n let resultType;\n let result;\n let onReject: (() => void) | undefined;\n\n let runHandler = (handler: ActionFunction | LoaderFunction) => {\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 onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n return Promise.race([\n handler({\n request,\n params: match.params,\n context: opts.requestContext,\n }),\n abortPromise,\n ]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let values = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch((e) => {\n handlerError = e;\n }),\n loadLazyRouteModule(match.route, mapRouteProperties, manifest),\n ]);\n if (handlerError) {\n throw handlerError;\n }\n result = values[0];\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n\n handler = match.route[type];\n if (handler) {\n // Handler still run even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, data: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n if (isResponse(result)) {\n let status = result.status;\n\n // Process redirects\n if (redirectStatusCodes.has(status)) {\n let location = result.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n // Support relative routing in internal redirects\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n location = normalizeTo(\n new URL(request.url),\n matches.slice(0, matches.indexOf(match) + 1),\n basename,\n true,\n location,\n v7_relativeSplatPath\n );\n } else if (!opts.isStaticRequest) {\n // Strip off the protocol+origin for same-origin + same-basename absolute\n // redirects. If this is a static request, we can let it go back to the\n // browser as-is\n let currentUrl = new URL(request.url);\n let url = location.startsWith(\"//\")\n ? new URL(currentUrl.protocol + location)\n : new URL(location);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n location = url.pathname + url.search + url.hash;\n }\n }\n\n // Don't process redirects in the router during static requests requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect. We also update the Location header in place in this flow so\n // basename and relative routing is taken into account\n if (opts.isStaticRequest) {\n result.headers.set(\"Location\", location);\n throw result;\n }\n\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n reloadDocument: result.headers.get(\"X-Remix-Reload-Document\") !== null,\n };\n }\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping. We do this with the QueryRouteResponse wrapper\n // interface so we can know whether it was returned or thrown\n if (opts.isRouteRequest) {\n let queryRouteResponse: QueryRouteResponse = {\n type:\n resultType === ResultType.error ? ResultType.error : ResultType.data,\n response: result,\n };\n throw queryRouteResponse;\n }\n\n let data: any;\n\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return { type: ResultType.error, error: e };\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponseImpl(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 (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n 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\n errors = errors || {};\n\n // Prefer higher error values if lower errors bubble to the same boundary\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n } else {\n loaderData[id] = result.data;\n }\n\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. Also clear out any loaderData for the\n // throwing route\n if (pendingError) {\n errors = pendingError;\n loaderData[Object.keys(pendingError)[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n 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, controller } = 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 (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponseImpl(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isQueryRouteResponse(obj: any): obj is QueryRouteResponse {\n return (\n obj &&\n isResponse(obj.response) &&\n (obj.type === ResultType.data || obj.type === ResultType.error)\n );\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\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 // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (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 let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\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\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n };\n return fetcher;\n}\n\nfunction restoreAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(\n TRANSITIONS_STORAGE_KEY\n );\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\n\nfunction persistAppliedTransitions(\n _window: Window,\n transitions: Map>\n) {\n if (transitions.size > 0) {\n let json: Record = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(\n TRANSITIONS_STORAGE_KEY,\n JSON.stringify(json)\n );\n } catch (error) {\n warning(\n false,\n `Failed to save applied view transitions in sessionStorage (${error}).`\n );\n }\n }\n}\n\n//#endregion\n"],"names":["Action","PopStateEventType","invariant","value","message","Error","warning","cond","console","warn","e","getHistoryState","location","index","usr","state","key","idx","createLocation","current","to","_extends","pathname","search","hash","parsePath","Math","random","toString","substr","createPath","_ref","charAt","path","parsedPath","hashIndex","indexOf","searchIndex","getUrlBasedHistory","getLocation","createHref","validateLocation","options","window","document","defaultView","v5Compat","globalHistory","history","action","Pop","listener","getIndex","handlePop","nextIndex","delta","createURL","base","origin","href","URL","replaceState","listen","fn","addEventListener","removeEventListener","encodeLocation","url","push","Push","historyState","pushState","error","DOMException","name","assign","replace","Replace","go","n","ResultType","immutableRouteKeys","Set","convertRoutesToDataRoutes","routes","mapRouteProperties","parentPath","manifest","map","route","treePath","id","join","children","isIndexRoute","indexRoute","pathOrLayoutRoute","undefined","matchRoutes","locationArg","basename","stripBasename","branches","flattenRoutes","sort","a","b","score","length","slice","every","i","compareIndexes","routesMeta","meta","childrenIndex","rankRouteBranches","matches","matchRouteBranch","safelyDecodeURI","convertRouteMatchToUiMatch","match","loaderData","params","data","handle","parentsMeta","flattenRoute","relativePath","caseSensitive","startsWith","joinPaths","concat","computeScore","forEach","_route$path","includes","exploded","explodeOptionalSegments","segments","split","first","rest","isOptional","endsWith","required","restExploded","result","subpath","paramRe","isSplat","s","initialScore","some","filter","reduce","segment","test","branch","matchedParams","matchedPathname","end","remainingPathname","matchPath","Object","pathnameBase","normalizePathname","pattern","matcher","compiledParams","regexpSource","_","paramName","RegExp","compilePath","captureGroups","memo","splatValue","decodeURIComponent","safelyDecodeURIComponent","decodeURI","toLowerCase","startIndex","nextChar","resolvePath","fromPathname","toPathname","pop","resolvePathname","normalizeSearch","normalizeHash","getInvalidPathError","char","field","dest","JSON","stringify","getPathContributingMatches","getResolveToMatches","v7_relativeSplatPath","pathMatches","resolveTo","toArg","routePathnames","locationPathname","isPathRelative","from","isEmptyPath","routePathnameIndex","toSegments","shift","hasExplicitTrailingSlash","hasCurrentTrailingSlash","paths","AbortedDeferredError","DeferredData","constructor","responseInit","reject","this","pendingKeysSet","subscribers","deferredKeys","Array","isArray","abortPromise","Promise","r","controller","AbortController","onAbort","unlistenAbortSignal","signal","entries","acc","_ref2","trackPromise","done","init","add","promise","race","then","onSettle","catch","defineProperty","get","aborted","delete","undefinedError","emit","settledKey","subscriber","subscribe","cancel","abort","v","k","async","resolve","size","unwrappedData","_ref3","unwrapTrackedPromise","pendingKeys","_tracked","isTrackedPromise","_error","_data","defer","redirect","status","headers","Headers","set","Response","ErrorResponseImpl","statusText","internal","isRouteErrorResponse","validMutationMethodsArr","validMutationMethods","validRequestMethodsArr","validRequestMethods","redirectStatusCodes","redirectPreserveMethodStatusCodes","IDLE_NAVIGATION","formMethod","formAction","formEncType","formData","json","text","IDLE_FETCHER","IDLE_BLOCKER","proceed","reset","ABSOLUTE_URL_REGEX","defaultMapRouteProperties","hasErrorBoundary","Boolean","TRANSITIONS_STORAGE_KEY","UNSAFE_DEFERRED_SYMBOL","Symbol","normalizeTo","prependBasename","fromRouteId","relative","contextualMatches","activeRouteMatch","hasNakedIndexQuery","normalizeNavigateOptions","normalizeFormMethod","isFetcher","opts","body","isSubmissionNavigation","isValidMethod","getInternalRouterError","method","searchParams","getInvalidBodyError","type","rawFormMethod","toUpperCase","stripHashFromPath","isMutationMethod","FormData","URLSearchParams","String","submission","parse","convertFormDataToSearchParams","convertSearchParamsToFormData","append","getLoaderMatchesUntilBoundary","boundaryId","boundaryMatches","findIndex","m","getMatchesToLoad","isInitialLoad","isRevalidationRequired","cancelledDeferredRoutes","cancelledFetcherLoads","deletedFetchers","fetchLoadMatches","fetchRedirectIds","routesToUse","pendingActionData","pendingError","actionResult","values","currentUrl","nextUrl","keys","navigationMatches","lazy","loader","hydrate","errors","currentLoaderData","currentMatch","isNew","isMissingData","isNewLoader","currentRouteMatch","nextRouteMatch","shouldRevalidateLoader","currentParams","nextParams","defaultShouldRevalidate","isNewRouteInstance","revalidatingFetchers","f","routeId","has","fetcherMatches","fetcher","fetchers","fetcherMatch","getTargetMatch","shouldRevalidate","currentPath","loaderMatch","arg","routeChoice","loadLazyRouteModule","lazyRoute","routeToUpdate","routeUpdates","lazyRouteProperty","isPropertyStaticallyDefined","callLoaderOrAction","request","resultType","onReject","runHandler","handler","context","requestContext","handlerError","all","isResponse","isStaticRequest","protocol","isSameBasename","revalidate","reloadDocument","isRouteRequest","response","contentType","statusCode","isDeferredData","deferred","deferredData","_result$init","_result$init2","createClientSideRequest","Request","processRouteLoaderData","matchesToLoad","results","activeDeferreds","foundError","loaderHeaders","isRedirectResult","isErrorResult","boundaryMatch","findNearestBoundary","isDeferredResult","processLoaderData","fetcherResults","doneFetcher","getDoneFetcher","mergeLoaderData","newLoaderData","mergedLoaderData","hasOwnProperty","reverse","find","getShortCircuitMatches","_temp5","errorMessage","findRedirect","resolveData","resolveDeferredResults","currentMatches","signals","isRevalidatingLoader","resolveDeferredData","unwrap","getAll","getSubmissionFromNavigation","navigation","getLoadingNavigation","getSubmittingNavigation","getLoadingFetcher","querySelector","getAttribute","initialEntries","initialIndex","entry","createMemoryLocation","clampIndex","min","max","getCurrentLocation","nextLocation","splice","routerWindow","isBrowser","createElement","isServer","detectErrorBoundary","inFlightDataRoutes","initialized","dataRoutes","future","v7_fetcherPersist","v7_normalizeFormMethod","v7_partialHydration","v7_prependBasename","unlistenHistory","savedScrollPositions","getScrollRestorationKey","getScrollPosition","initialScrollRestored","hydrationData","initialMatches","initialErrors","router","hasLazyRoutes","hasLoaders","pendingNavigationController","historyAction","restoreScrollPosition","preventScrollReset","revalidation","actionData","Map","blockers","pendingAction","HistoryAction","pendingPreventScrollReset","pendingViewTransitionEnabled","appliedViewTransitions","removePageHideEventListener","isUninterruptedRevalidation","fetchControllers","incrementingLoadId","pendingNavigationLoadId","fetchReloadIds","activeFetchers","blockerFunctions","ignoreNextHistoryUpdate","updateState","newState","completedFetchers","deletedFetchersKeys","unstable_viewTransitionOpts","viewTransitionOpts","unstable_flushSync","flushSync","deleteFetcher","completeNavigation","_temp","_location$state","_location$state2","isActionReload","_isRedirect","priorPaths","currentLocation","toPaths","getSavedScrollPosition","startNavigation","startUninterruptedRevalidation","getScrollKey","saveScrollPosition","enableViewTransition","loadingNavigation","overrideNavigation","notFoundMatches","cancelActiveDeferreds","isHashChangeOnly","actionOutput","interruptActiveLoads","actionMatch","shortCircuited","startRedirectNavigation","pendingActionError","handleAction","fetcherSubmission","initialHydration","activeSubmission","updatedFetchers","markFetchRedirectsDone","rf","revalidatingFetcher","abortFetcher","abortPendingFetchRevalidations","loaderResults","callLoadersAndMaybeResolveData","fetcherKey","didAbortFetchLoads","abortStaleFetchLoads","shouldUpdateFetchers","handleLoaders","_temp2","redirectLocation","isDocumentReload","redirectHistoryAction","fetchersToLoad","updateFetcherState","setFetcherError","getFetcher","markFetchersDone","doneKeys","landedId","yeetedKeys","deleteBlocker","updateBlocker","newBlocker","blocker","shouldBlockNavigation","blockerKey","blockerFunction","predicate","cancelledRouteIds","dfd","y","initialize","_window","transitions","sessionPositions","sessionStorage","getItem","restoreAppliedTransitions","_saveAppliedTransitions","setItem","persistAppliedTransitions","enableScrollRestoration","positions","getPosition","getKey","navigate","normalizedPath","userReplace","unstable_viewTransition","fetch","requestMatches","existingFetcher","getSubmittingFetcher","abortController","fetchRequest","originatingLoadId","revalidationRequest","loadId","loadFetcher","staleKey","handleFetcherAction","handleFetcherLoader","count","dispose","clear","getBlocker","_internalFetchControllers","_internalActiveDeferreds","_internalSetRoutes","newRoutes","queryImpl","routeMatch","Location","actionHeaders","loadRouteData","loaderRequest","submit","obj","isRedirectResponse","executedLoaders","fromEntries","query","_temp3","methodNotAllowedMatches","queryRoute","_temp4","_result$activeDeferre","originalPath","prefix","p","array","keyMatch","optional","param","_deepestRenderedBoundaryId","redirectDocument"],"mappings":";;;;;;;;;;udAOYA,IAAAA,WAAAA,GAAM,OAANA,EAAM,IAAA,MAANA,EAAM,KAAA,OAANA,EAAM,QAAA,UAANA,CAAM,EAAA,IA2LlB,MAAMC,EAA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MghB,EAAW/e,EAAQnC,MAAM,oBAC/B,GAAIkhB,EAAU,CACZ,OAAS3nB,EAAK4nB,GAAYD,EAC1B,IAAIE,EAAQlhB,EAAO3G,GAEnB,OADAd,EAAuB,MAAb0oB,GAA6B,MAATC,EAAa,aAAe7nB,EAAG,WACtDoL,EAAUyc,EACnB,CAGA,OAAOjf,EAAQhF,QAAQ,OAAQ,GAAG,IAGnC8E,QAAQE,KAAcA,IAEAhE,KAAK,IAChC,8BCg+EO,SACLR,EACA2T,EACAvU,GASA,OAPoCnD,EAAA,CAAA,EAC/B0X,EAAO,CACVa,WAAY,IACZpD,OAAQ,CACN,CAACuC,EAAQ+P,4BAA8B1jB,EAAO,GAAGO,IAAKnB,IAI5D,kBD5kEO,SAAuBpD,GAE5B,MAAc,KAAPA,GAAuC,KAAzBA,EAAYE,SAC7B,IACc,iBAAPF,EACPK,EAAUL,GAAIE,SACdF,EAAGE,QACT,oEAuCkC,SAACsG,EAAMkH,QAAI,IAAJA,IAAAA,EAAO,CAAA,GAC9C,IAAIrB,EAA+B,iBAATqB,EAAoB,CAAEiC,OAAQjC,GAASA,EAE7DkC,EAAU,IAAIC,QAAQxD,EAAauD,SAKvC,OAJKA,EAAQwG,IAAI,iBACfxG,EAAQE,IAAI,eAAgB,mCAGvB,IAAIC,SAAShF,KAAKC,UAAUxE,GAAKvG,EAAA,CAAA,EACnCoM,EAAY,CACfuD,YAEJ,oGAgPkD+X,CAAC5kB,EAAK2K,KACtD,IAAI4K,EAAW5I,EAAS3M,EAAK2K,GAE7B,OADA4K,EAAS1I,QAAQE,IAAI,0BAA2B,QACzCwI,CAAQ"} \ 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 new file mode 100644 index 0000000..94eddf3 --- /dev/null +++ b/node_modules/@remix-run/router/dist/utils.d.ts @@ -0,0 +1,502 @@ +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; + statusCode?: number; + headers?: Headers; +} +/** + * Redirect result from a loader or action + */ +export interface RedirectResult { + type: ResultType.redirect; + status: number; + location: string; + revalidate: boolean; + reloadDocument?: 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; +type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete"; +type UpperCaseFormMethod = Uppercase; +/** + * Users can specify either lowercase or uppercase form methods on ``, + * useSubmit(), ``, etc. + */ +export type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod; +/** + * Active navigation/fetcher form methods are exposed in lowercase on the + * RouterState + */ +export type FormMethod = LowerCaseFormMethod; +export type MutationFormMethod = Exclude; +/** + * In v7, active navigation/fetcher form methods are exposed in uppercase on the + * RouterState. This is to align with the normalization done via fetch(). + */ +export type V7_FormMethod = UpperCaseFormMethod; +export type V7_MutationFormMethod = Exclude; +export type FormEncType = "application/x-www-form-urlencoded" | "multipart/form-data" | "application/json" | "text/plain"; +type JsonObject = { + [Key in string]: JsonValue; +} & { + [Key in string]?: JsonValue | undefined; +}; +type JsonArray = JsonValue[] | readonly JsonValue[]; +type JsonPrimitive = string | number | boolean | null; +type JsonValue = JsonPrimitive | JsonObject | JsonArray; +/** + * @private + * Internal interface to pass around for action submissions, not intended for + * external consumption + */ +export type Submission = { + formMethod: FormMethod | V7_FormMethod; + formAction: string; + formEncType: FormEncType; + formData: FormData; + json: undefined; + text: undefined; +} | { + formMethod: FormMethod | V7_FormMethod; + formAction: string; + formEncType: FormEncType; + formData: undefined; + json: JsonValue; + text: undefined; +} | { + formMethod: FormMethod | V7_FormMethod; + formAction: string; + formEncType: FormEncType; + formData: undefined; + json: undefined; + text: string; +}; +/** + * @private + * Arguments passed to route loader/action functions. Same for now but we keep + * this as a private implementation detail in case they diverge in the future. + */ +interface DataFunctionArgs { + request: Request; + params: Params; + context?: Context; +} +/** + * Arguments passed to loader functions + */ +export interface LoaderFunctionArgs extends DataFunctionArgs { +} +/** + * Arguments passed to action functions + */ +export interface ActionFunctionArgs extends DataFunctionArgs { +} +/** + * Loaders and actions can return anything except `undefined` (`null` is a + * valid return value if there is no data to return). Responses are preferred + * and will ease any future migration to Remix + */ +type DataFunctionValue = Response | NonNullable | null; +/** + * Route loader function signature + */ +export type LoaderFunction = { + (args: LoaderFunctionArgs): Promise | DataFunctionValue; +} & { + hydrate?: boolean; +}; +/** + * Route action function signature + */ +export interface ActionFunction { + (args: ActionFunctionArgs): Promise | DataFunctionValue; +} +/** + * Arguments passed to shouldRevalidate function + */ +export interface ShouldRevalidateFunctionArgs { + currentUrl: URL; + currentParams: AgnosticDataRouteMatch["params"]; + nextUrl: URL; + nextParams: AgnosticDataRouteMatch["params"]; + formMethod?: Submission["formMethod"]; + formAction?: Submission["formAction"]; + formEncType?: Submission["formEncType"]; + text?: Submission["text"]; + formData?: Submission["formData"]; + json?: Submission["json"]; + actionResult?: any; + defaultShouldRevalidate: boolean; +} +/** + * Route shouldRevalidate function signature. This runs after any submission + * (navigation or fetcher), so we flatten the navigation/fetcher submission + * onto the arguments. It shouldn't matter whether it came from a navigation + * or a fetcher, what really matters is the URLs and the formData since loaders + * have to re-run based on the data models that were potentially mutated. + */ +export interface ShouldRevalidateFunction { + (args: ShouldRevalidateFunctionArgs): boolean; +} +/** + * Function provided by the framework-aware layers to set `hasErrorBoundary` + * from the framework-aware `errorElement` prop + * + * @deprecated Use `mapRouteProperties` instead + */ +export interface DetectErrorBoundaryFunction { + (route: AgnosticRouteObject): boolean; +} +/** + * Function provided by the framework-aware layers to set any framework-specific + * properties from framework-agnostic properties + */ +export interface MapRoutePropertiesFunction { + (route: AgnosticRouteObject): { + hasErrorBoundary: boolean; + } & Record; +} +/** + * Keys we cannot change from within a lazy() function. We spread all other keys + * onto the route. Either they're meaningful to the router, or they'll get + * ignored. + */ +export type ImmutableRouteKey = "lazy" | "caseSensitive" | "path" | "id" | "index" | "children"; +export declare const immutableRouteKeys: Set; +type RequireOne = Exclude<{ + [K in keyof T]: K extends Key ? Omit & Required> : never; +}[keyof T], undefined>; +/** + * lazy() function to load a route definition, which can add non-matching + * related properties to a route + */ +export interface LazyRouteFunction { + (): Promise>>; +} +/** + * 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; + lazy?: LazyRouteFunction; +}; +/** + * Index routes must not have children + */ +export type AgnosticIndexRouteObject = AgnosticBaseRouteObject & { + children?: undefined; + index: true; +}; +/** + * Non-index routes may have children, but cannot have index + */ +export type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & { + children?: AgnosticRouteObject[]; + index?: false; +}; +/** + * A route object represents a logical route, with (optionally) its child + * routes organized in a tree-like structure. + */ +export type AgnosticRouteObject = AgnosticIndexRouteObject | AgnosticNonIndexRouteObject; +export type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & { + id: string; +}; +export type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & { + children?: AgnosticDataRouteObject[]; + id: string; +}; +/** + * A data route object, which is just a RouteObject with a required unique ID + */ +export type AgnosticDataRouteObject = AgnosticDataIndexRouteObject | AgnosticDataNonIndexRouteObject; +export type RouteManifest = Record; +type _PathParam = Path extends `${infer L}/${infer R}` ? _PathParam | _PathParam : Path extends `:${infer Param}` ? Param extends `${infer Optional}?` ? Optional : Param : never; +/** + * Examples: + * "/a/b/*" -> "*" + * ":a" -> "a" + * "/a/:b" -> "b" + * "/a/blahblahblah:b" -> "b" + * "/:a/:b" -> "a" | "b" + * "/:a/b/:c/*" -> "a" | "c" | "*" + */ +export type PathParam = Path extends "*" | "/*" ? "*" : Path extends `${infer Rest}/*` ? "*" | _PathParam : _PathParam; +export type ParamParseKey = [ + 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 { + /** + * 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[], mapRouteProperties: MapRoutePropertiesFunction, parentPath?: number[], manifest?: RouteManifest): AgnosticDataRouteObject[]; +/** + * Matches the given routes to a location and returns the match data. + * + * @see https://reactrouter.com/utils/match-routes + */ +export declare function matchRoutes(routes: RouteObjectType[], locationArg: Partial | string, basename?: string): AgnosticRouteMatch[] | null; +export interface UIMatch { + id: string; + pathname: string; + params: AgnosticRouteMatch["params"]; + data: Data; + handle: Handle; +} +export declare function convertRouteMatchToUiMatch(match: AgnosticDataRouteMatch, loaderData: RouteData): UIMatch; +/** + * Returns a path with params interpolated. + * + * @see https://reactrouter.com/utils/generate-path + */ +export declare function generatePath(originalPath: Path, params?: { + [key in PathParam]: string | null; +}): 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/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; +/** + * Returns a resolved path object relative to the given pathname. + * + * @see https://reactrouter.com/utils/resolve-path + */ +export declare function resolvePath(to: To, fromPathname?: string): Path; +/** + * @private + * + * When processing relative navigation we want to ignore ancestor routes that + * do not contribute to the path, such that index/pathless layout routes don't + * interfere. + * + * For example, when moving a route element into an index route and/or a + * pathless layout route, relative link behavior contained within should stay + * the same. Both of the following examples should link back to the root: + * + * + * + * + * + * + * + * }> // <-- Does not contribute + * // <-- Does not contribute + * + * + */ +export declare function getPathContributingMatches(matches: T[]): T[]; +export declare function getResolveToMatches(matches: T[], v7_relativeSplatPath: boolean): string[]; +/** + * @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 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 pendingKeysSet; + private controller; + private abortPromise; + private unlistenAbortSignal; + private subscribers; + data: Record; + init?: ResponseInit; + deferredKeys: string[]; + constructor(data: Record, responseInit?: ResponseInit); + private trackPromise; + private onSettle; + private emit; + subscribe(fn: (aborted: boolean, settledKey?: string) => void): () => boolean; + cancel(): void; + resolveData(signal: AbortSignal): Promise; + get done(): boolean; + get unwrappedData(): {}; + get pendingKeys(): string[]; +} +export type DeferFunction = (data: Record, init?: number | ResponseInit) => DeferredData; +export declare const defer: DeferFunction; +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 declare const redirect: RedirectFunction; +/** + * A redirect response that will force a document reload to the new location. + * Sets the status code and the `Location` header. + * Defaults to "302 Found". + */ +export declare const redirectDocument: RedirectFunction; +export type ErrorResponse = { + status: number; + statusText: string; + data: any; +}; +/** + * @private + * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies + * + * We don't export the class for public use since it's an implementation + * detail, but we export the interface above so folks can build their own + * abstractions around instances via isRouteErrorResponse() + */ +export declare class ErrorResponseImpl implements ErrorResponse { + status: number; + statusText: string; + data: any; + private error?; + private internal; + constructor(status: number, statusText: string | undefined, data: any, internal?: boolean); +} +/** + * Check if the given error is an ErrorResponse generated from a 4xx/5xx + * Response thrown from an action/loader + */ +export declare function isRouteErrorResponse(error: any): error is ErrorResponse; +export {}; diff --git a/node_modules/@vitejs/plugin-react/dist/index.cjs b/node_modules/@vitejs/plugin-react/dist/index.cjs new file mode 100644 index 0000000..650a11f --- /dev/null +++ b/node_modules/@vitejs/plugin-react/dist/index.cjs @@ -0,0 +1,295 @@ +'use strict'; + +const vite = require('vite'); +const fs = require('node:fs'); +const path = require('node:path'); +const node_module = require('node:module'); + +var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null; +function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; } + +const fs__default = /*#__PURE__*/_interopDefaultCompat(fs); +const path__default = /*#__PURE__*/_interopDefaultCompat(path); + +const runtimePublicPath = "/@react-refresh"; +const _require = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))); +const reactRefreshDir = path__default.dirname( + _require.resolve("react-refresh/package.json") +); +const runtimeFilePath = path__default.join( + reactRefreshDir, + "cjs/react-refresh-runtime.development.js" +); +const runtimeCode = ` +const exports = {} +${fs__default.readFileSync(runtimeFilePath, "utf-8")} +${fs__default.readFileSync(_require.resolve("./refreshUtils.js"), "utf-8")} +export default exports +`; +const preambleCode = ` +import RefreshRuntime from "__BASE__${runtimePublicPath.slice(1)}" +RefreshRuntime.injectIntoGlobalHook(window) +window.$RefreshReg$ = () => {} +window.$RefreshSig$ = () => (type) => type +window.__vite_plugin_react_preamble_installed__ = true +`; +const header = ` +import RefreshRuntime from "${runtimePublicPath}"; + +const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope; +let prevRefreshReg; +let prevRefreshSig; + +if (import.meta.hot && !inWebWorker) { + if (!window.__vite_plugin_react_preamble_installed__) { + throw new Error( + "@vitejs/plugin-react can't detect preamble. Something is wrong. " + + "See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201" + ); + } + + prevRefreshReg = window.$RefreshReg$; + prevRefreshSig = window.$RefreshSig$; + window.$RefreshReg$ = (type, id) => { + RefreshRuntime.register(type, __SOURCE__ + " " + id) + }; + window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform; +}`.replace(/\n+/g, ""); +const footer = ` +if (import.meta.hot && !inWebWorker) { + window.$RefreshReg$ = prevRefreshReg; + window.$RefreshSig$ = prevRefreshSig; + + RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => { + RefreshRuntime.registerExportsForReactRefresh(__SOURCE__, currentExports); + import.meta.hot.accept((nextExports) => { + if (!nextExports) return; + const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(currentExports, nextExports); + if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage); + }); + }); +}`; +function addRefreshWrapper(code, id) { + return header.replace("__SOURCE__", JSON.stringify(id)) + code + footer.replace("__SOURCE__", JSON.stringify(id)); +} + +let babel; +async function loadBabel() { + if (!babel) { + babel = await import('@babel/core'); + } + return babel; +} +const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/; +const defaultIncludeRE = /\.[tj]sx?$/; +const tsRE = /\.tsx?$/; +function viteReact(opts = {}) { + let devBase = "/"; + const filter = vite.createFilter(opts.include ?? defaultIncludeRE, opts.exclude); + const jsxImportSource = opts.jsxImportSource ?? "react"; + const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`; + const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`; + let isProduction = true; + let projectRoot = process.cwd(); + let skipFastRefresh = false; + let runPluginOverrides; + let staticBabelOptions; + const importReactRE = /\bimport\s+(?:\*\s+as\s+)?React\b/; + const viteBabel = { + name: "vite:react-babel", + enforce: "pre", + config() { + if (opts.jsxRuntime === "classic") { + return { + esbuild: { + jsx: "transform" + } + }; + } else { + return { + esbuild: { + jsx: "automatic", + jsxImportSource: opts.jsxImportSource + }, + optimizeDeps: { esbuildOptions: { jsx: "automatic" } } + }; + } + }, + configResolved(config) { + devBase = config.base; + projectRoot = config.root; + isProduction = config.isProduction; + skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false; + if ("jsxPure" in opts) { + config.logger.warnOnce( + "[@vitejs/plugin-react] jsxPure was removed. You can configure esbuild.jsxSideEffects directly." + ); + } + const hooks = config.plugins.map((plugin) => plugin.api?.reactBabel).filter(defined); + if (hooks.length > 0) { + runPluginOverrides = (babelOptions, context) => { + hooks.forEach((hook) => hook(babelOptions, context, config)); + }; + } else if (typeof opts.babel !== "function") { + staticBabelOptions = createBabelOptions(opts.babel); + } + }, + async transform(code, id, options) { + if (id.includes("/node_modules/")) + return; + const [filepath] = id.split("?"); + if (!filter(filepath)) + return; + const ssr = options?.ssr === true; + const babelOptions = (() => { + if (staticBabelOptions) + return staticBabelOptions; + const newBabelOptions = createBabelOptions( + typeof opts.babel === "function" ? opts.babel(id, { ssr }) : opts.babel + ); + runPluginOverrides?.(newBabelOptions, { id, ssr }); + return newBabelOptions; + })(); + const plugins = [...babelOptions.plugins]; + const isJSX = filepath.endsWith("x"); + const useFastRefresh = !skipFastRefresh && !ssr && (isJSX || (opts.jsxRuntime === "classic" ? importReactRE.test(code) : code.includes(jsxImportDevRuntime) || code.includes(jsxImportRuntime))); + if (useFastRefresh) { + plugins.push([ + await loadPlugin("react-refresh/babel"), + { skipEnvCheck: true } + ]); + } + if (opts.jsxRuntime === "classic" && isJSX) { + if (!isProduction) { + plugins.push( + await loadPlugin("@babel/plugin-transform-react-jsx-self"), + await loadPlugin("@babel/plugin-transform-react-jsx-source") + ); + } + } + if (!plugins.length && !babelOptions.presets.length && !babelOptions.configFile && !babelOptions.babelrc) { + return; + } + const parserPlugins = [...babelOptions.parserOpts.plugins]; + if (!filepath.endsWith(".ts")) { + parserPlugins.push("jsx"); + } + if (tsRE.test(filepath)) { + parserPlugins.push("typescript"); + } + const babel2 = await loadBabel(); + const result = await babel2.transformAsync(code, { + ...babelOptions, + root: projectRoot, + filename: id, + sourceFileName: filepath, + // Required for esbuild.jsxDev to provide correct line numbers + retainLines: !isProduction && isJSX && opts.jsxRuntime !== "classic", + parserOpts: { + ...babelOptions.parserOpts, + sourceType: "module", + allowAwaitOutsideFunction: true, + plugins: parserPlugins + }, + generatorOpts: { + ...babelOptions.generatorOpts, + decoratorsBeforeExport: true + }, + plugins, + sourceMaps: true + }); + if (result) { + let code2 = result.code; + if (useFastRefresh && refreshContentRE.test(code2)) { + code2 = addRefreshWrapper(code2, id); + } + return { code: code2, map: result.map }; + } + } + }; + const viteReactRefresh = { + name: "vite:react-refresh", + enforce: "pre", + config: (userConfig) => ({ + build: silenceUseClientWarning(userConfig), + optimizeDeps: { + // We can't add `react-dom` because the dependency is `react-dom/client` + // for React 18 while it's `react-dom` for React 17. We'd need to detect + // what React version the user has installed. + include: ["react", jsxImportDevRuntime, jsxImportRuntime] + }, + resolve: { + dedupe: ["react", "react-dom"] + } + }), + resolveId(id) { + if (id === runtimePublicPath) { + return id; + } + }, + load(id) { + if (id === runtimePublicPath) { + return runtimeCode; + } + }, + transformIndexHtml() { + if (!skipFastRefresh) + return [ + { + tag: "script", + attrs: { type: "module" }, + children: preambleCode.replace(`__BASE__`, devBase) + } + ]; + } + }; + return [viteBabel, viteReactRefresh]; +} +viteReact.preambleCode = preambleCode; +const silenceUseClientWarning = (userConfig) => ({ + rollupOptions: { + onwarn(warning, defaultHandler) { + if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) { + return; + } + if (userConfig.build?.rollupOptions?.onwarn) { + userConfig.build.rollupOptions.onwarn(warning, defaultHandler); + } else { + defaultHandler(warning); + } + } + } +}); +const loadedPlugin = /* @__PURE__ */ new Map(); +function loadPlugin(path) { + const cached = loadedPlugin.get(path); + if (cached) + return cached; + const promise = import(path).then((module) => { + const value = module.default || module; + loadedPlugin.set(path, value); + return value; + }); + loadedPlugin.set(path, promise); + return promise; +} +function createBabelOptions(rawOptions) { + var _a; + const babelOptions = { + babelrc: false, + configFile: false, + ...rawOptions + }; + babelOptions.plugins || (babelOptions.plugins = []); + babelOptions.presets || (babelOptions.presets = []); + babelOptions.overrides || (babelOptions.overrides = []); + babelOptions.parserOpts || (babelOptions.parserOpts = {}); + (_a = babelOptions.parserOpts).plugins || (_a.plugins = []); + return babelOptions; +} +function defined(value) { + return value !== void 0; +} + +module.exports = viteReact; +module.exports.default = viteReact; diff --git a/node_modules/@vitejs/plugin-react/dist/index.d.cts b/node_modules/@vitejs/plugin-react/dist/index.d.cts new file mode 100644 index 0000000..b5d125d --- /dev/null +++ b/node_modules/@vitejs/plugin-react/dist/index.d.cts @@ -0,0 +1,54 @@ +import { TransformOptions, ParserOptions } from '@babel/core'; +import { PluginOption, ResolvedConfig } from 'vite'; + +interface Options { + include?: string | RegExp | Array; + exclude?: string | RegExp | Array; + /** + * Control where the JSX factory is imported from. + * https://esbuild.github.io/api/#jsx-import-source + * @default 'react' + */ + jsxImportSource?: string; + /** + * Note: Skipping React import with classic runtime is not supported from v4 + * @default "automatic" + */ + jsxRuntime?: 'classic' | 'automatic'; + /** + * Babel configuration applied in both dev and prod. + */ + babel?: BabelOptions | ((id: string, options: { + ssr?: boolean; + }) => BabelOptions); +} +type BabelOptions = Omit; +/** + * The object type used by the `options` passed to plugins with + * an `api.reactBabel` method. + */ +interface ReactBabelOptions extends BabelOptions { + plugins: Extract; + presets: Extract; + overrides: Extract; + parserOpts: ParserOptions & { + plugins: Extract; + }; +} +type ReactBabelHook = (babelConfig: ReactBabelOptions, context: ReactBabelHookContext, config: ResolvedConfig) => void; +type ReactBabelHookContext = { + ssr: boolean; + id: string; +}; +type ViteReactPluginApi = { + /** + * Manipulate the Babel options of `@vitejs/plugin-react` + */ + reactBabel?: ReactBabelHook; +}; +declare function viteReact(opts?: Options): PluginOption[]; +declare namespace viteReact { + var preambleCode: string; +} + +export { type BabelOptions, type Options, type ReactBabelOptions, type ViteReactPluginApi, viteReact as default }; diff --git a/node_modules/@vitejs/plugin-react/dist/index.d.mts b/node_modules/@vitejs/plugin-react/dist/index.d.mts new file mode 100644 index 0000000..b5d125d --- /dev/null +++ b/node_modules/@vitejs/plugin-react/dist/index.d.mts @@ -0,0 +1,54 @@ +import { TransformOptions, ParserOptions } from '@babel/core'; +import { PluginOption, ResolvedConfig } from 'vite'; + +interface Options { + include?: string | RegExp | Array; + exclude?: string | RegExp | Array; + /** + * Control where the JSX factory is imported from. + * https://esbuild.github.io/api/#jsx-import-source + * @default 'react' + */ + jsxImportSource?: string; + /** + * Note: Skipping React import with classic runtime is not supported from v4 + * @default "automatic" + */ + jsxRuntime?: 'classic' | 'automatic'; + /** + * Babel configuration applied in both dev and prod. + */ + babel?: BabelOptions | ((id: string, options: { + ssr?: boolean; + }) => BabelOptions); +} +type BabelOptions = Omit; +/** + * The object type used by the `options` passed to plugins with + * an `api.reactBabel` method. + */ +interface ReactBabelOptions extends BabelOptions { + plugins: Extract; + presets: Extract; + overrides: Extract; + parserOpts: ParserOptions & { + plugins: Extract; + }; +} +type ReactBabelHook = (babelConfig: ReactBabelOptions, context: ReactBabelHookContext, config: ResolvedConfig) => void; +type ReactBabelHookContext = { + ssr: boolean; + id: string; +}; +type ViteReactPluginApi = { + /** + * Manipulate the Babel options of `@vitejs/plugin-react` + */ + reactBabel?: ReactBabelHook; +}; +declare function viteReact(opts?: Options): PluginOption[]; +declare namespace viteReact { + var preambleCode: string; +} + +export { type BabelOptions, type Options, type ReactBabelOptions, type ViteReactPluginApi, viteReact as default }; diff --git a/node_modules/@vitejs/plugin-react/dist/index.d.ts b/node_modules/@vitejs/plugin-react/dist/index.d.ts new file mode 100644 index 0000000..b5d125d --- /dev/null +++ b/node_modules/@vitejs/plugin-react/dist/index.d.ts @@ -0,0 +1,54 @@ +import { TransformOptions, ParserOptions } from '@babel/core'; +import { PluginOption, ResolvedConfig } from 'vite'; + +interface Options { + include?: string | RegExp | Array; + exclude?: string | RegExp | Array; + /** + * Control where the JSX factory is imported from. + * https://esbuild.github.io/api/#jsx-import-source + * @default 'react' + */ + jsxImportSource?: string; + /** + * Note: Skipping React import with classic runtime is not supported from v4 + * @default "automatic" + */ + jsxRuntime?: 'classic' | 'automatic'; + /** + * Babel configuration applied in both dev and prod. + */ + babel?: BabelOptions | ((id: string, options: { + ssr?: boolean; + }) => BabelOptions); +} +type BabelOptions = Omit; +/** + * The object type used by the `options` passed to plugins with + * an `api.reactBabel` method. + */ +interface ReactBabelOptions extends BabelOptions { + plugins: Extract; + presets: Extract; + overrides: Extract; + parserOpts: ParserOptions & { + plugins: Extract; + }; +} +type ReactBabelHook = (babelConfig: ReactBabelOptions, context: ReactBabelHookContext, config: ResolvedConfig) => void; +type ReactBabelHookContext = { + ssr: boolean; + id: string; +}; +type ViteReactPluginApi = { + /** + * Manipulate the Babel options of `@vitejs/plugin-react` + */ + reactBabel?: ReactBabelHook; +}; +declare function viteReact(opts?: Options): PluginOption[]; +declare namespace viteReact { + var preambleCode: string; +} + +export { type BabelOptions, type Options, type ReactBabelOptions, type ViteReactPluginApi, viteReact as default }; diff --git a/node_modules/@vitejs/plugin-react/dist/index.mjs b/node_modules/@vitejs/plugin-react/dist/index.mjs new file mode 100644 index 0000000..9074233 --- /dev/null +++ b/node_modules/@vitejs/plugin-react/dist/index.mjs @@ -0,0 +1,286 @@ +import { createFilter } from 'vite'; +import fs from 'node:fs'; +import path from 'node:path'; +import { createRequire } from 'node:module'; + +const runtimePublicPath = "/@react-refresh"; +const _require = createRequire(import.meta.url); +const reactRefreshDir = path.dirname( + _require.resolve("react-refresh/package.json") +); +const runtimeFilePath = path.join( + reactRefreshDir, + "cjs/react-refresh-runtime.development.js" +); +const runtimeCode = ` +const exports = {} +${fs.readFileSync(runtimeFilePath, "utf-8")} +${fs.readFileSync(_require.resolve("./refreshUtils.js"), "utf-8")} +export default exports +`; +const preambleCode = ` +import RefreshRuntime from "__BASE__${runtimePublicPath.slice(1)}" +RefreshRuntime.injectIntoGlobalHook(window) +window.$RefreshReg$ = () => {} +window.$RefreshSig$ = () => (type) => type +window.__vite_plugin_react_preamble_installed__ = true +`; +const header = ` +import RefreshRuntime from "${runtimePublicPath}"; + +const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope; +let prevRefreshReg; +let prevRefreshSig; + +if (import.meta.hot && !inWebWorker) { + if (!window.__vite_plugin_react_preamble_installed__) { + throw new Error( + "@vitejs/plugin-react can't detect preamble. Something is wrong. " + + "See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201" + ); + } + + prevRefreshReg = window.$RefreshReg$; + prevRefreshSig = window.$RefreshSig$; + window.$RefreshReg$ = (type, id) => { + RefreshRuntime.register(type, __SOURCE__ + " " + id) + }; + window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform; +}`.replace(/\n+/g, ""); +const footer = ` +if (import.meta.hot && !inWebWorker) { + window.$RefreshReg$ = prevRefreshReg; + window.$RefreshSig$ = prevRefreshSig; + + RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => { + RefreshRuntime.registerExportsForReactRefresh(__SOURCE__, currentExports); + import.meta.hot.accept((nextExports) => { + if (!nextExports) return; + const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(currentExports, nextExports); + if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage); + }); + }); +}`; +function addRefreshWrapper(code, id) { + return header.replace("__SOURCE__", JSON.stringify(id)) + code + footer.replace("__SOURCE__", JSON.stringify(id)); +} + +let babel; +async function loadBabel() { + if (!babel) { + babel = await import('@babel/core'); + } + return babel; +} +const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/; +const defaultIncludeRE = /\.[tj]sx?$/; +const tsRE = /\.tsx?$/; +function viteReact(opts = {}) { + let devBase = "/"; + const filter = createFilter(opts.include ?? defaultIncludeRE, opts.exclude); + const jsxImportSource = opts.jsxImportSource ?? "react"; + const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`; + const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`; + let isProduction = true; + let projectRoot = process.cwd(); + let skipFastRefresh = false; + let runPluginOverrides; + let staticBabelOptions; + const importReactRE = /\bimport\s+(?:\*\s+as\s+)?React\b/; + const viteBabel = { + name: "vite:react-babel", + enforce: "pre", + config() { + if (opts.jsxRuntime === "classic") { + return { + esbuild: { + jsx: "transform" + } + }; + } else { + return { + esbuild: { + jsx: "automatic", + jsxImportSource: opts.jsxImportSource + }, + optimizeDeps: { esbuildOptions: { jsx: "automatic" } } + }; + } + }, + configResolved(config) { + devBase = config.base; + projectRoot = config.root; + isProduction = config.isProduction; + skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false; + if ("jsxPure" in opts) { + config.logger.warnOnce( + "[@vitejs/plugin-react] jsxPure was removed. You can configure esbuild.jsxSideEffects directly." + ); + } + const hooks = config.plugins.map((plugin) => plugin.api?.reactBabel).filter(defined); + if (hooks.length > 0) { + runPluginOverrides = (babelOptions, context) => { + hooks.forEach((hook) => hook(babelOptions, context, config)); + }; + } else if (typeof opts.babel !== "function") { + staticBabelOptions = createBabelOptions(opts.babel); + } + }, + async transform(code, id, options) { + if (id.includes("/node_modules/")) + return; + const [filepath] = id.split("?"); + if (!filter(filepath)) + return; + const ssr = options?.ssr === true; + const babelOptions = (() => { + if (staticBabelOptions) + return staticBabelOptions; + const newBabelOptions = createBabelOptions( + typeof opts.babel === "function" ? opts.babel(id, { ssr }) : opts.babel + ); + runPluginOverrides?.(newBabelOptions, { id, ssr }); + return newBabelOptions; + })(); + const plugins = [...babelOptions.plugins]; + const isJSX = filepath.endsWith("x"); + const useFastRefresh = !skipFastRefresh && !ssr && (isJSX || (opts.jsxRuntime === "classic" ? importReactRE.test(code) : code.includes(jsxImportDevRuntime) || code.includes(jsxImportRuntime))); + if (useFastRefresh) { + plugins.push([ + await loadPlugin("react-refresh/babel"), + { skipEnvCheck: true } + ]); + } + if (opts.jsxRuntime === "classic" && isJSX) { + if (!isProduction) { + plugins.push( + await loadPlugin("@babel/plugin-transform-react-jsx-self"), + await loadPlugin("@babel/plugin-transform-react-jsx-source") + ); + } + } + if (!plugins.length && !babelOptions.presets.length && !babelOptions.configFile && !babelOptions.babelrc) { + return; + } + const parserPlugins = [...babelOptions.parserOpts.plugins]; + if (!filepath.endsWith(".ts")) { + parserPlugins.push("jsx"); + } + if (tsRE.test(filepath)) { + parserPlugins.push("typescript"); + } + const babel2 = await loadBabel(); + const result = await babel2.transformAsync(code, { + ...babelOptions, + root: projectRoot, + filename: id, + sourceFileName: filepath, + // Required for esbuild.jsxDev to provide correct line numbers + retainLines: !isProduction && isJSX && opts.jsxRuntime !== "classic", + parserOpts: { + ...babelOptions.parserOpts, + sourceType: "module", + allowAwaitOutsideFunction: true, + plugins: parserPlugins + }, + generatorOpts: { + ...babelOptions.generatorOpts, + decoratorsBeforeExport: true + }, + plugins, + sourceMaps: true + }); + if (result) { + let code2 = result.code; + if (useFastRefresh && refreshContentRE.test(code2)) { + code2 = addRefreshWrapper(code2, id); + } + return { code: code2, map: result.map }; + } + } + }; + const viteReactRefresh = { + name: "vite:react-refresh", + enforce: "pre", + config: (userConfig) => ({ + build: silenceUseClientWarning(userConfig), + optimizeDeps: { + // We can't add `react-dom` because the dependency is `react-dom/client` + // for React 18 while it's `react-dom` for React 17. We'd need to detect + // what React version the user has installed. + include: ["react", jsxImportDevRuntime, jsxImportRuntime] + }, + resolve: { + dedupe: ["react", "react-dom"] + } + }), + resolveId(id) { + if (id === runtimePublicPath) { + return id; + } + }, + load(id) { + if (id === runtimePublicPath) { + return runtimeCode; + } + }, + transformIndexHtml() { + if (!skipFastRefresh) + return [ + { + tag: "script", + attrs: { type: "module" }, + children: preambleCode.replace(`__BASE__`, devBase) + } + ]; + } + }; + return [viteBabel, viteReactRefresh]; +} +viteReact.preambleCode = preambleCode; +const silenceUseClientWarning = (userConfig) => ({ + rollupOptions: { + onwarn(warning, defaultHandler) { + if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) { + return; + } + if (userConfig.build?.rollupOptions?.onwarn) { + userConfig.build.rollupOptions.onwarn(warning, defaultHandler); + } else { + defaultHandler(warning); + } + } + } +}); +const loadedPlugin = /* @__PURE__ */ new Map(); +function loadPlugin(path) { + const cached = loadedPlugin.get(path); + if (cached) + return cached; + const promise = import(path).then((module) => { + const value = module.default || module; + loadedPlugin.set(path, value); + return value; + }); + loadedPlugin.set(path, promise); + return promise; +} +function createBabelOptions(rawOptions) { + var _a; + const babelOptions = { + babelrc: false, + configFile: false, + ...rawOptions + }; + babelOptions.plugins || (babelOptions.plugins = []); + babelOptions.presets || (babelOptions.presets = []); + babelOptions.overrides || (babelOptions.overrides = []); + babelOptions.parserOpts || (babelOptions.parserOpts = {}); + (_a = babelOptions.parserOpts).plugins || (_a.plugins = []); + return babelOptions; +} +function defined(value) { + return value !== void 0; +} + +export { viteReact as default }; diff --git a/node_modules/@vitejs/plugin-react/dist/refreshUtils.js b/node_modules/@vitejs/plugin-react/dist/refreshUtils.js new file mode 100644 index 0000000..0ca2b01 --- /dev/null +++ b/node_modules/@vitejs/plugin-react/dist/refreshUtils.js @@ -0,0 +1,71 @@ +function debounce(fn, delay) { + let handle + return () => { + clearTimeout(handle) + handle = setTimeout(fn, delay) + } +} + +/* eslint-disable no-undef */ +const enqueueUpdate = debounce(exports.performReactRefresh, 16) + +// Taken from https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/main/lib/runtime/RefreshUtils.js#L141 +// This allows to resister components not detected by SWC like styled component +function registerExportsForReactRefresh(filename, moduleExports) { + for (const key in moduleExports) { + if (key === '__esModule') continue + const exportValue = moduleExports[key] + if (exports.isLikelyComponentType(exportValue)) { + // 'export' is required to avoid key collision when renamed exports that + // shadow a local component name: https://github.com/vitejs/vite-plugin-react/issues/116 + // The register function has an identity check to not register twice the same component, + // so this is safe to not used the same key here. + exports.register(exportValue, filename + ' export ' + key) + } + } +} + +function validateRefreshBoundaryAndEnqueueUpdate(prevExports, nextExports) { + if (!predicateOnExport(prevExports, (key) => key in nextExports)) { + return 'Could not Fast Refresh (export removed)' + } + if (!predicateOnExport(nextExports, (key) => key in prevExports)) { + return 'Could not Fast Refresh (new export)' + } + + let hasExports = false + const allExportsAreComponentsOrUnchanged = predicateOnExport( + nextExports, + (key, value) => { + hasExports = true + if (exports.isLikelyComponentType(value)) return true + return prevExports[key] === nextExports[key] + }, + ) + if (hasExports && allExportsAreComponentsOrUnchanged) { + enqueueUpdate() + } else { + return 'Could not Fast Refresh. Learn more at https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react#consistent-components-exports' + } +} + +function predicateOnExport(moduleExports, predicate) { + for (const key in moduleExports) { + if (key === '__esModule') continue + const desc = Object.getOwnPropertyDescriptor(moduleExports, key) + if (desc && desc.get) return false + if (!predicate(key, moduleExports[key])) return false + } + return true +} + +// Hides vite-ignored dynamic import so that Vite can skip analysis if no other +// dynamic import is present (https://github.com/vitejs/vite/pull/12732) +function __hmr_import(module) { + return import(/* @vite-ignore */ module) +} + +exports.__hmr_import = __hmr_import +exports.registerExportsForReactRefresh = registerExportsForReactRefresh +exports.validateRefreshBoundaryAndEnqueueUpdate = + validateRefreshBoundaryAndEnqueueUpdate diff --git a/node_modules/acorn/dist/acorn.d.mts b/node_modules/acorn/dist/acorn.d.mts new file mode 100644 index 0000000..6ad5812 --- /dev/null +++ b/node_modules/acorn/dist/acorn.d.mts @@ -0,0 +1,857 @@ +export interface Node { + start: number + end: number + type: string + range?: [number, number] + loc?: SourceLocation | null +} + +export interface SourceLocation { + source?: string | null + start: Position + end: Position +} + +export interface Position { + /** 1-based */ + line: number + /** 0-based */ + column: number +} + +export interface Identifier extends Node { + type: "Identifier" + name: string +} + +export interface Literal extends Node { + type: "Literal" + value?: string | boolean | null | number | RegExp | bigint + raw?: string + regex?: { + pattern: string + flags: string + } + bigint?: string +} + +export interface Program extends Node { + type: "Program" + body: Array + sourceType: "script" | "module" +} + +export interface Function extends Node { + id?: Identifier | null + params: Array + body: BlockStatement | Expression + generator: boolean + expression: boolean + async: boolean +} + +export interface ExpressionStatement extends Node { + type: "ExpressionStatement" + expression: Expression | Literal + directive?: string +} + +export interface BlockStatement extends Node { + type: "BlockStatement" + body: Array +} + +export interface EmptyStatement extends Node { + type: "EmptyStatement" +} + +export interface DebuggerStatement extends Node { + type: "DebuggerStatement" +} + +export interface WithStatement extends Node { + type: "WithStatement" + object: Expression + body: Statement +} + +export interface ReturnStatement extends Node { + type: "ReturnStatement" + argument?: Expression | null +} + +export interface LabeledStatement extends Node { + type: "LabeledStatement" + label: Identifier + body: Statement +} + +export interface BreakStatement extends Node { + type: "BreakStatement" + label?: Identifier | null +} + +export interface ContinueStatement extends Node { + type: "ContinueStatement" + label?: Identifier | null +} + +export interface IfStatement extends Node { + type: "IfStatement" + test: Expression + consequent: Statement + alternate?: Statement | null +} + +export interface SwitchStatement extends Node { + type: "SwitchStatement" + discriminant: Expression + cases: Array +} + +export interface SwitchCase extends Node { + type: "SwitchCase" + test?: Expression | null + consequent: Array +} + +export interface ThrowStatement extends Node { + type: "ThrowStatement" + argument: Expression +} + +export interface TryStatement extends Node { + type: "TryStatement" + block: BlockStatement + handler?: CatchClause | null + finalizer?: BlockStatement | null +} + +export interface CatchClause extends Node { + type: "CatchClause" + param?: Pattern | null + body: BlockStatement +} + +export interface WhileStatement extends Node { + type: "WhileStatement" + test: Expression + body: Statement +} + +export interface DoWhileStatement extends Node { + type: "DoWhileStatement" + body: Statement + test: Expression +} + +export interface ForStatement extends Node { + type: "ForStatement" + init?: VariableDeclaration | Expression | null + test?: Expression | null + update?: Expression | null + body: Statement +} + +export interface ForInStatement extends Node { + type: "ForInStatement" + left: VariableDeclaration | Pattern + right: Expression + body: Statement +} + +export interface FunctionDeclaration extends Function { + type: "FunctionDeclaration" + id: Identifier + body: BlockStatement +} + +export interface VariableDeclaration extends Node { + type: "VariableDeclaration" + declarations: Array + kind: "var" | "let" | "const" +} + +export interface VariableDeclarator extends Node { + type: "VariableDeclarator" + id: Pattern + init?: Expression | null +} + +export interface ThisExpression extends Node { + type: "ThisExpression" +} + +export interface ArrayExpression extends Node { + type: "ArrayExpression" + elements: Array +} + +export interface ObjectExpression extends Node { + type: "ObjectExpression" + properties: Array +} + +export interface Property extends Node { + type: "Property" + key: Expression + value: Expression + kind: "init" | "get" | "set" + method: boolean + shorthand: boolean + computed: boolean +} + +export interface FunctionExpression extends Function { + type: "FunctionExpression" + body: BlockStatement +} + +export interface UnaryExpression extends Node { + type: "UnaryExpression" + operator: UnaryOperator + prefix: boolean + argument: Expression +} + +export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete" + +export interface UpdateExpression extends Node { + type: "UpdateExpression" + operator: UpdateOperator + argument: Expression + prefix: boolean +} + +export type UpdateOperator = "++" | "--" + +export interface BinaryExpression extends Node { + type: "BinaryExpression" + operator: BinaryOperator + left: Expression | PrivateIdentifier + right: Expression +} + +export type BinaryOperator = "==" | "!=" | "===" | "!==" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in" | "instanceof" | "**" + +export interface AssignmentExpression extends Node { + type: "AssignmentExpression" + operator: AssignmentOperator + left: Pattern + right: Expression +} + +export type AssignmentOperator = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&=" | "**=" | "||=" | "&&=" | "??=" + +export interface LogicalExpression extends Node { + type: "LogicalExpression" + operator: LogicalOperator + left: Expression + right: Expression +} + +export type LogicalOperator = "||" | "&&" | "??" + +export interface MemberExpression extends Node { + type: "MemberExpression" + object: Expression | Super + property: Expression | PrivateIdentifier + computed: boolean + optional: boolean +} + +export interface ConditionalExpression extends Node { + type: "ConditionalExpression" + test: Expression + alternate: Expression + consequent: Expression +} + +export interface CallExpression extends Node { + type: "CallExpression" + callee: Expression | Super + arguments: Array + optional: boolean +} + +export interface NewExpression extends Node { + type: "NewExpression" + callee: Expression + arguments: Array +} + +export interface SequenceExpression extends Node { + type: "SequenceExpression" + expressions: Array +} + +export interface ForOfStatement extends Node { + type: "ForOfStatement" + left: VariableDeclaration | Pattern + right: Expression + body: Statement + await: boolean +} + +export interface Super extends Node { + type: "Super" +} + +export interface SpreadElement extends Node { + type: "SpreadElement" + argument: Expression +} + +export interface ArrowFunctionExpression extends Function { + type: "ArrowFunctionExpression" +} + +export interface YieldExpression extends Node { + type: "YieldExpression" + argument?: Expression | null + delegate: boolean +} + +export interface TemplateLiteral extends Node { + type: "TemplateLiteral" + quasis: Array + expressions: Array +} + +export interface TaggedTemplateExpression extends Node { + type: "TaggedTemplateExpression" + tag: Expression + quasi: TemplateLiteral +} + +export interface TemplateElement extends Node { + type: "TemplateElement" + tail: boolean + value: { + cooked?: string | null + raw: string + } +} + +export interface AssignmentProperty extends Node { + type: "Property" + key: Expression + value: Pattern + kind: "init" + method: false + shorthand: boolean + computed: boolean +} + +export interface ObjectPattern extends Node { + type: "ObjectPattern" + properties: Array +} + +export interface ArrayPattern extends Node { + type: "ArrayPattern" + elements: Array +} + +export interface RestElement extends Node { + type: "RestElement" + argument: Pattern +} + +export interface AssignmentPattern extends Node { + type: "AssignmentPattern" + left: Pattern + right: Expression +} + +export interface Class extends Node { + id?: Identifier | null + superClass?: Expression | null + body: ClassBody +} + +export interface ClassBody extends Node { + type: "ClassBody" + body: Array +} + +export interface MethodDefinition extends Node { + type: "MethodDefinition" + key: Expression | PrivateIdentifier + value: FunctionExpression + kind: "constructor" | "method" | "get" | "set" + computed: boolean + static: boolean +} + +export interface ClassDeclaration extends Class { + type: "ClassDeclaration" + id: Identifier +} + +export interface ClassExpression extends Class { + type: "ClassExpression" +} + +export interface MetaProperty extends Node { + type: "MetaProperty" + meta: Identifier + property: Identifier +} + +export interface ImportDeclaration extends Node { + type: "ImportDeclaration" + specifiers: Array + source: Literal +} + +export interface ImportSpecifier extends Node { + type: "ImportSpecifier" + imported: Identifier | Literal + local: Identifier +} + +export interface ImportDefaultSpecifier extends Node { + type: "ImportDefaultSpecifier" + local: Identifier +} + +export interface ImportNamespaceSpecifier extends Node { + type: "ImportNamespaceSpecifier" + local: Identifier +} + +export interface ExportNamedDeclaration extends Node { + type: "ExportNamedDeclaration" + declaration?: Declaration | null + specifiers: Array + source?: Literal | null +} + +export interface ExportSpecifier extends Node { + type: "ExportSpecifier" + exported: Identifier | Literal + local: Identifier | Literal +} + +export interface AnonymousFunctionDeclaration extends Function { + type: "FunctionDeclaration" + id: null + body: BlockStatement +} + +export interface AnonymousClassDeclaration extends Class { + type: "ClassDeclaration" + id: null +} + +export interface ExportDefaultDeclaration extends Node { + type: "ExportDefaultDeclaration" + declaration: AnonymousFunctionDeclaration | FunctionDeclaration | AnonymousClassDeclaration | ClassDeclaration | Expression +} + +export interface ExportAllDeclaration extends Node { + type: "ExportAllDeclaration" + source: Literal + exported?: Identifier | Literal | null +} + +export interface AwaitExpression extends Node { + type: "AwaitExpression" + argument: Expression +} + +export interface ChainExpression extends Node { + type: "ChainExpression" + expression: MemberExpression | CallExpression +} + +export interface ImportExpression extends Node { + type: "ImportExpression" + source: Expression +} + +export interface ParenthesizedExpression extends Node { + type: "ParenthesizedExpression" + expression: Expression +} + +export interface PropertyDefinition extends Node { + type: "PropertyDefinition" + key: Expression | PrivateIdentifier + value?: Expression | null + computed: boolean + static: boolean +} + +export interface PrivateIdentifier extends Node { + type: "PrivateIdentifier" + name: string +} + +export interface StaticBlock extends Node { + type: "StaticBlock" + body: Array +} + +export type Statement = +| ExpressionStatement +| BlockStatement +| EmptyStatement +| DebuggerStatement +| WithStatement +| ReturnStatement +| LabeledStatement +| BreakStatement +| ContinueStatement +| IfStatement +| SwitchStatement +| ThrowStatement +| TryStatement +| WhileStatement +| DoWhileStatement +| ForStatement +| ForInStatement +| ForOfStatement +| Declaration + +export type Declaration = +| FunctionDeclaration +| VariableDeclaration +| ClassDeclaration + +export type Expression = +| Identifier +| Literal +| ThisExpression +| ArrayExpression +| ObjectExpression +| FunctionExpression +| UnaryExpression +| UpdateExpression +| BinaryExpression +| AssignmentExpression +| LogicalExpression +| MemberExpression +| ConditionalExpression +| CallExpression +| NewExpression +| SequenceExpression +| ArrowFunctionExpression +| YieldExpression +| TemplateLiteral +| TaggedTemplateExpression +| ClassExpression +| MetaProperty +| AwaitExpression +| ChainExpression +| ImportExpression +| ParenthesizedExpression + +export type Pattern = +| Identifier +| MemberExpression +| ObjectPattern +| ArrayPattern +| RestElement +| AssignmentPattern + +export type ModuleDeclaration = +| ImportDeclaration +| ExportNamedDeclaration +| ExportDefaultDeclaration +| ExportAllDeclaration + +export type AnyNode = Statement | Expression | Declaration | ModuleDeclaration | Literal | Program | SwitchCase | CatchClause | Property | Super | SpreadElement | TemplateElement | AssignmentProperty | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | ClassBody | MethodDefinition | MetaProperty | ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier | AnonymousFunctionDeclaration | AnonymousClassDeclaration | PropertyDefinition | PrivateIdentifier | StaticBlock + +export function parse(input: string, options: Options): Program + +export function parseExpressionAt(input: string, pos: number, options: Options): Expression + +export function tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator +} + +export type ecmaVersion = 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | "latest" + +export interface Options { + /** + * `ecmaVersion` indicates the ECMAScript version to parse. Must be + * either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + * (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` + * (the latest version the library supports). This influences + * support for strict mode, the set of reserved words, and support + * for new syntax features. + */ + ecmaVersion: ecmaVersion + + /** + * `sourceType` indicates the mode the code should be parsed in. + * Can be either `"script"` or `"module"`. This influences global + * strict mode and parsing of `import` and `export` declarations. + */ + sourceType?: "script" | "module" + + /** + * a callback that will be called when a semicolon is automatically inserted. + * @param lastTokEnd the position of the comma as an offset + * @param lastTokEndLoc location if {@link locations} is enabled + */ + onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + + /** + * similar to `onInsertedSemicolon`, but for trailing commas + * @param lastTokEnd the position of the comma as an offset + * @param lastTokEndLoc location if `locations` is enabled + */ + onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + + /** + * By default, reserved words are only enforced if ecmaVersion >= 5. + * Set `allowReserved` to a boolean value to explicitly turn this on + * an off. When this option has the value "never", reserved words + * and keywords can also not be used as property names. + */ + allowReserved?: boolean | "never" + + /** + * When enabled, a return at the top level is not considered an error. + */ + allowReturnOutsideFunction?: boolean + + /** + * When enabled, import/export statements are not constrained to + * appearing at the top of the program, and an import.meta expression + * in a script isn't considered an error. + */ + allowImportExportEverywhere?: boolean + + /** + * By default, `await` identifiers are allowed to appear at the top-level scope only if {@link ecmaVersion} >= 2022. + * When enabled, await identifiers are allowed to appear at the top-level scope, + * but they are still not allowed in non-async functions. + */ + allowAwaitOutsideFunction?: boolean + + /** + * When enabled, super identifiers are not constrained to + * appearing in methods and do not raise an error when they appear elsewhere. + */ + allowSuperOutsideMethod?: boolean + + /** + * When enabled, hashbang directive in the beginning of file is + * allowed and treated as a line comment. Enabled by default when + * {@link ecmaVersion} >= 2023. + */ + allowHashBang?: boolean + + /** + * By default, the parser will verify that private properties are + * only used in places where they are valid and have been declared. + * Set this to false to turn such checks off. + */ + checkPrivateFields?: boolean + + /** + * When `locations` is on, `loc` properties holding objects with + * `start` and `end` properties as {@link Position} objects will be attached to the + * nodes. + */ + locations?: boolean + + /** + * a callback that will cause Acorn to call that export function with object in the same + * format as tokens returned from `tokenizer().getToken()`. Note + * that you are not allowed to call the parser from the + * callback—that will corrupt its internal state. + */ + onToken?: ((token: Token) => void) | Token[] + + + /** + * This takes a export function or an array. + * + * When a export function is passed, Acorn will call that export function with `(block, text, start, + * end)` parameters whenever a comment is skipped. `block` is a + * boolean indicating whether this is a block (`/* *\/`) comment, + * `text` is the content of the comment, and `start` and `end` are + * character offsets that denote the start and end of the comment. + * When the {@link locations} option is on, two more parameters are + * passed, the full locations of {@link Position} export type of the start and + * end of the comments. + * + * When a array is passed, each found comment of {@link Comment} export type is pushed to the array. + * + * Note that you are not allowed to call the + * parser from the callback—that will corrupt its internal state. + */ + onComment?: (( + isBlock: boolean, text: string, start: number, end: number, startLoc?: Position, + endLoc?: Position + ) => void) | Comment[] + + /** + * Nodes have their start and end characters offsets recorded in + * `start` and `end` properties (directly on the node, rather than + * the `loc` object, which holds line/column data. To also add a + * [semi-standardized][range] `range` property holding a `[start, + * end]` array with the same numbers, set the `ranges` option to + * `true`. + */ + ranges?: boolean + + /** + * It is possible to parse multiple files into a single AST by + * passing the tree produced by parsing the first file as + * `program` option in subsequent parses. This will add the + * toplevel forms of the parsed file to the `Program` (top) node + * of an existing parse tree. + */ + program?: Node + + /** + * When {@link locations} is on, you can pass this to record the source + * file in every node's `loc` object. + */ + sourceFile?: string + + /** + * This value, if given, is stored in every node, whether {@link locations} is on or off. + */ + directSourceFile?: string + + /** + * When enabled, parenthesized expressions are represented by + * (non-standard) ParenthesizedExpression nodes + */ + preserveParens?: boolean +} + +export class Parser { + options: Options + input: string + + private constructor(options: Options, input: string, startPos?: number) + parse(): Program + + static parse(input: string, options: Options): Program + static parseExpressionAt(input: string, pos: number, options: Options): Expression + static tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator + } + static extend(...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser +} + +export const defaultOptions: Options + +export function getLineInfo(input: string, offset: number): Position + +export class TokenType { + label: string + keyword: string | undefined +} + +export const tokTypes: { + num: TokenType + regexp: TokenType + string: TokenType + name: TokenType + privateId: TokenType + eof: TokenType + + bracketL: TokenType + bracketR: TokenType + braceL: TokenType + braceR: TokenType + parenL: TokenType + parenR: TokenType + comma: TokenType + semi: TokenType + colon: TokenType + dot: TokenType + question: TokenType + questionDot: TokenType + arrow: TokenType + template: TokenType + invalidTemplate: TokenType + ellipsis: TokenType + backQuote: TokenType + dollarBraceL: TokenType + + eq: TokenType + assign: TokenType + incDec: TokenType + prefix: TokenType + logicalOR: TokenType + logicalAND: TokenType + bitwiseOR: TokenType + bitwiseXOR: TokenType + bitwiseAND: TokenType + equality: TokenType + relational: TokenType + bitShift: TokenType + plusMin: TokenType + modulo: TokenType + star: TokenType + slash: TokenType + starstar: TokenType + coalesce: TokenType + + _break: TokenType + _case: TokenType + _catch: TokenType + _continue: TokenType + _debugger: TokenType + _default: TokenType + _do: TokenType + _else: TokenType + _finally: TokenType + _for: TokenType + _function: TokenType + _if: TokenType + _return: TokenType + _switch: TokenType + _throw: TokenType + _try: TokenType + _var: TokenType + _const: TokenType + _while: TokenType + _with: TokenType + _new: TokenType + _this: TokenType + _super: TokenType + _class: TokenType + _extends: TokenType + _export: TokenType + _import: TokenType + _null: TokenType + _true: TokenType + _false: TokenType + _in: TokenType + _instanceof: TokenType + _typeof: TokenType + _void: TokenType + _delete: TokenType +} + +export interface Comment { + type: "Line" | "Block" + value: string + start: number + end: number + loc?: SourceLocation + range?: [number, number] +} + +export class Token { + type: TokenType + start: number + end: number + loc?: SourceLocation + range?: [number, number] +} + +export const version: string diff --git a/node_modules/acorn/dist/acorn.d.ts b/node_modules/acorn/dist/acorn.d.ts new file mode 100644 index 0000000..6ad5812 --- /dev/null +++ b/node_modules/acorn/dist/acorn.d.ts @@ -0,0 +1,857 @@ +export interface Node { + start: number + end: number + type: string + range?: [number, number] + loc?: SourceLocation | null +} + +export interface SourceLocation { + source?: string | null + start: Position + end: Position +} + +export interface Position { + /** 1-based */ + line: number + /** 0-based */ + column: number +} + +export interface Identifier extends Node { + type: "Identifier" + name: string +} + +export interface Literal extends Node { + type: "Literal" + value?: string | boolean | null | number | RegExp | bigint + raw?: string + regex?: { + pattern: string + flags: string + } + bigint?: string +} + +export interface Program extends Node { + type: "Program" + body: Array + sourceType: "script" | "module" +} + +export interface Function extends Node { + id?: Identifier | null + params: Array + body: BlockStatement | Expression + generator: boolean + expression: boolean + async: boolean +} + +export interface ExpressionStatement extends Node { + type: "ExpressionStatement" + expression: Expression | Literal + directive?: string +} + +export interface BlockStatement extends Node { + type: "BlockStatement" + body: Array +} + +export interface EmptyStatement extends Node { + type: "EmptyStatement" +} + +export interface DebuggerStatement extends Node { + type: "DebuggerStatement" +} + +export interface WithStatement extends Node { + type: "WithStatement" + object: Expression + body: Statement +} + +export interface ReturnStatement extends Node { + type: "ReturnStatement" + argument?: Expression | null +} + +export interface LabeledStatement extends Node { + type: "LabeledStatement" + label: Identifier + body: Statement +} + +export interface BreakStatement extends Node { + type: "BreakStatement" + label?: Identifier | null +} + +export interface ContinueStatement extends Node { + type: "ContinueStatement" + label?: Identifier | null +} + +export interface IfStatement extends Node { + type: "IfStatement" + test: Expression + consequent: Statement + alternate?: Statement | null +} + +export interface SwitchStatement extends Node { + type: "SwitchStatement" + discriminant: Expression + cases: Array +} + +export interface SwitchCase extends Node { + type: "SwitchCase" + test?: Expression | null + consequent: Array +} + +export interface ThrowStatement extends Node { + type: "ThrowStatement" + argument: Expression +} + +export interface TryStatement extends Node { + type: "TryStatement" + block: BlockStatement + handler?: CatchClause | null + finalizer?: BlockStatement | null +} + +export interface CatchClause extends Node { + type: "CatchClause" + param?: Pattern | null + body: BlockStatement +} + +export interface WhileStatement extends Node { + type: "WhileStatement" + test: Expression + body: Statement +} + +export interface DoWhileStatement extends Node { + type: "DoWhileStatement" + body: Statement + test: Expression +} + +export interface ForStatement extends Node { + type: "ForStatement" + init?: VariableDeclaration | Expression | null + test?: Expression | null + update?: Expression | null + body: Statement +} + +export interface ForInStatement extends Node { + type: "ForInStatement" + left: VariableDeclaration | Pattern + right: Expression + body: Statement +} + +export interface FunctionDeclaration extends Function { + type: "FunctionDeclaration" + id: Identifier + body: BlockStatement +} + +export interface VariableDeclaration extends Node { + type: "VariableDeclaration" + declarations: Array + kind: "var" | "let" | "const" +} + +export interface VariableDeclarator extends Node { + type: "VariableDeclarator" + id: Pattern + init?: Expression | null +} + +export interface ThisExpression extends Node { + type: "ThisExpression" +} + +export interface ArrayExpression extends Node { + type: "ArrayExpression" + elements: Array +} + +export interface ObjectExpression extends Node { + type: "ObjectExpression" + properties: Array +} + +export interface Property extends Node { + type: "Property" + key: Expression + value: Expression + kind: "init" | "get" | "set" + method: boolean + shorthand: boolean + computed: boolean +} + +export interface FunctionExpression extends Function { + type: "FunctionExpression" + body: BlockStatement +} + +export interface UnaryExpression extends Node { + type: "UnaryExpression" + operator: UnaryOperator + prefix: boolean + argument: Expression +} + +export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete" + +export interface UpdateExpression extends Node { + type: "UpdateExpression" + operator: UpdateOperator + argument: Expression + prefix: boolean +} + +export type UpdateOperator = "++" | "--" + +export interface BinaryExpression extends Node { + type: "BinaryExpression" + operator: BinaryOperator + left: Expression | PrivateIdentifier + right: Expression +} + +export type BinaryOperator = "==" | "!=" | "===" | "!==" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in" | "instanceof" | "**" + +export interface AssignmentExpression extends Node { + type: "AssignmentExpression" + operator: AssignmentOperator + left: Pattern + right: Expression +} + +export type AssignmentOperator = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&=" | "**=" | "||=" | "&&=" | "??=" + +export interface LogicalExpression extends Node { + type: "LogicalExpression" + operator: LogicalOperator + left: Expression + right: Expression +} + +export type LogicalOperator = "||" | "&&" | "??" + +export interface MemberExpression extends Node { + type: "MemberExpression" + object: Expression | Super + property: Expression | PrivateIdentifier + computed: boolean + optional: boolean +} + +export interface ConditionalExpression extends Node { + type: "ConditionalExpression" + test: Expression + alternate: Expression + consequent: Expression +} + +export interface CallExpression extends Node { + type: "CallExpression" + callee: Expression | Super + arguments: Array + optional: boolean +} + +export interface NewExpression extends Node { + type: "NewExpression" + callee: Expression + arguments: Array +} + +export interface SequenceExpression extends Node { + type: "SequenceExpression" + expressions: Array +} + +export interface ForOfStatement extends Node { + type: "ForOfStatement" + left: VariableDeclaration | Pattern + right: Expression + body: Statement + await: boolean +} + +export interface Super extends Node { + type: "Super" +} + +export interface SpreadElement extends Node { + type: "SpreadElement" + argument: Expression +} + +export interface ArrowFunctionExpression extends Function { + type: "ArrowFunctionExpression" +} + +export interface YieldExpression extends Node { + type: "YieldExpression" + argument?: Expression | null + delegate: boolean +} + +export interface TemplateLiteral extends Node { + type: "TemplateLiteral" + quasis: Array + expressions: Array +} + +export interface TaggedTemplateExpression extends Node { + type: "TaggedTemplateExpression" + tag: Expression + quasi: TemplateLiteral +} + +export interface TemplateElement extends Node { + type: "TemplateElement" + tail: boolean + value: { + cooked?: string | null + raw: string + } +} + +export interface AssignmentProperty extends Node { + type: "Property" + key: Expression + value: Pattern + kind: "init" + method: false + shorthand: boolean + computed: boolean +} + +export interface ObjectPattern extends Node { + type: "ObjectPattern" + properties: Array +} + +export interface ArrayPattern extends Node { + type: "ArrayPattern" + elements: Array +} + +export interface RestElement extends Node { + type: "RestElement" + argument: Pattern +} + +export interface AssignmentPattern extends Node { + type: "AssignmentPattern" + left: Pattern + right: Expression +} + +export interface Class extends Node { + id?: Identifier | null + superClass?: Expression | null + body: ClassBody +} + +export interface ClassBody extends Node { + type: "ClassBody" + body: Array +} + +export interface MethodDefinition extends Node { + type: "MethodDefinition" + key: Expression | PrivateIdentifier + value: FunctionExpression + kind: "constructor" | "method" | "get" | "set" + computed: boolean + static: boolean +} + +export interface ClassDeclaration extends Class { + type: "ClassDeclaration" + id: Identifier +} + +export interface ClassExpression extends Class { + type: "ClassExpression" +} + +export interface MetaProperty extends Node { + type: "MetaProperty" + meta: Identifier + property: Identifier +} + +export interface ImportDeclaration extends Node { + type: "ImportDeclaration" + specifiers: Array + source: Literal +} + +export interface ImportSpecifier extends Node { + type: "ImportSpecifier" + imported: Identifier | Literal + local: Identifier +} + +export interface ImportDefaultSpecifier extends Node { + type: "ImportDefaultSpecifier" + local: Identifier +} + +export interface ImportNamespaceSpecifier extends Node { + type: "ImportNamespaceSpecifier" + local: Identifier +} + +export interface ExportNamedDeclaration extends Node { + type: "ExportNamedDeclaration" + declaration?: Declaration | null + specifiers: Array + source?: Literal | null +} + +export interface ExportSpecifier extends Node { + type: "ExportSpecifier" + exported: Identifier | Literal + local: Identifier | Literal +} + +export interface AnonymousFunctionDeclaration extends Function { + type: "FunctionDeclaration" + id: null + body: BlockStatement +} + +export interface AnonymousClassDeclaration extends Class { + type: "ClassDeclaration" + id: null +} + +export interface ExportDefaultDeclaration extends Node { + type: "ExportDefaultDeclaration" + declaration: AnonymousFunctionDeclaration | FunctionDeclaration | AnonymousClassDeclaration | ClassDeclaration | Expression +} + +export interface ExportAllDeclaration extends Node { + type: "ExportAllDeclaration" + source: Literal + exported?: Identifier | Literal | null +} + +export interface AwaitExpression extends Node { + type: "AwaitExpression" + argument: Expression +} + +export interface ChainExpression extends Node { + type: "ChainExpression" + expression: MemberExpression | CallExpression +} + +export interface ImportExpression extends Node { + type: "ImportExpression" + source: Expression +} + +export interface ParenthesizedExpression extends Node { + type: "ParenthesizedExpression" + expression: Expression +} + +export interface PropertyDefinition extends Node { + type: "PropertyDefinition" + key: Expression | PrivateIdentifier + value?: Expression | null + computed: boolean + static: boolean +} + +export interface PrivateIdentifier extends Node { + type: "PrivateIdentifier" + name: string +} + +export interface StaticBlock extends Node { + type: "StaticBlock" + body: Array +} + +export type Statement = +| ExpressionStatement +| BlockStatement +| EmptyStatement +| DebuggerStatement +| WithStatement +| ReturnStatement +| LabeledStatement +| BreakStatement +| ContinueStatement +| IfStatement +| SwitchStatement +| ThrowStatement +| TryStatement +| WhileStatement +| DoWhileStatement +| ForStatement +| ForInStatement +| ForOfStatement +| Declaration + +export type Declaration = +| FunctionDeclaration +| VariableDeclaration +| ClassDeclaration + +export type Expression = +| Identifier +| Literal +| ThisExpression +| ArrayExpression +| ObjectExpression +| FunctionExpression +| UnaryExpression +| UpdateExpression +| BinaryExpression +| AssignmentExpression +| LogicalExpression +| MemberExpression +| ConditionalExpression +| CallExpression +| NewExpression +| SequenceExpression +| ArrowFunctionExpression +| YieldExpression +| TemplateLiteral +| TaggedTemplateExpression +| ClassExpression +| MetaProperty +| AwaitExpression +| ChainExpression +| ImportExpression +| ParenthesizedExpression + +export type Pattern = +| Identifier +| MemberExpression +| ObjectPattern +| ArrayPattern +| RestElement +| AssignmentPattern + +export type ModuleDeclaration = +| ImportDeclaration +| ExportNamedDeclaration +| ExportDefaultDeclaration +| ExportAllDeclaration + +export type AnyNode = Statement | Expression | Declaration | ModuleDeclaration | Literal | Program | SwitchCase | CatchClause | Property | Super | SpreadElement | TemplateElement | AssignmentProperty | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | ClassBody | MethodDefinition | MetaProperty | ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier | AnonymousFunctionDeclaration | AnonymousClassDeclaration | PropertyDefinition | PrivateIdentifier | StaticBlock + +export function parse(input: string, options: Options): Program + +export function parseExpressionAt(input: string, pos: number, options: Options): Expression + +export function tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator +} + +export type ecmaVersion = 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | "latest" + +export interface Options { + /** + * `ecmaVersion` indicates the ECMAScript version to parse. Must be + * either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + * (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` + * (the latest version the library supports). This influences + * support for strict mode, the set of reserved words, and support + * for new syntax features. + */ + ecmaVersion: ecmaVersion + + /** + * `sourceType` indicates the mode the code should be parsed in. + * Can be either `"script"` or `"module"`. This influences global + * strict mode and parsing of `import` and `export` declarations. + */ + sourceType?: "script" | "module" + + /** + * a callback that will be called when a semicolon is automatically inserted. + * @param lastTokEnd the position of the comma as an offset + * @param lastTokEndLoc location if {@link locations} is enabled + */ + onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + + /** + * similar to `onInsertedSemicolon`, but for trailing commas + * @param lastTokEnd the position of the comma as an offset + * @param lastTokEndLoc location if `locations` is enabled + */ + onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void + + /** + * By default, reserved words are only enforced if ecmaVersion >= 5. + * Set `allowReserved` to a boolean value to explicitly turn this on + * an off. When this option has the value "never", reserved words + * and keywords can also not be used as property names. + */ + allowReserved?: boolean | "never" + + /** + * When enabled, a return at the top level is not considered an error. + */ + allowReturnOutsideFunction?: boolean + + /** + * When enabled, import/export statements are not constrained to + * appearing at the top of the program, and an import.meta expression + * in a script isn't considered an error. + */ + allowImportExportEverywhere?: boolean + + /** + * By default, `await` identifiers are allowed to appear at the top-level scope only if {@link ecmaVersion} >= 2022. + * When enabled, await identifiers are allowed to appear at the top-level scope, + * but they are still not allowed in non-async functions. + */ + allowAwaitOutsideFunction?: boolean + + /** + * When enabled, super identifiers are not constrained to + * appearing in methods and do not raise an error when they appear elsewhere. + */ + allowSuperOutsideMethod?: boolean + + /** + * When enabled, hashbang directive in the beginning of file is + * allowed and treated as a line comment. Enabled by default when + * {@link ecmaVersion} >= 2023. + */ + allowHashBang?: boolean + + /** + * By default, the parser will verify that private properties are + * only used in places where they are valid and have been declared. + * Set this to false to turn such checks off. + */ + checkPrivateFields?: boolean + + /** + * When `locations` is on, `loc` properties holding objects with + * `start` and `end` properties as {@link Position} objects will be attached to the + * nodes. + */ + locations?: boolean + + /** + * a callback that will cause Acorn to call that export function with object in the same + * format as tokens returned from `tokenizer().getToken()`. Note + * that you are not allowed to call the parser from the + * callback—that will corrupt its internal state. + */ + onToken?: ((token: Token) => void) | Token[] + + + /** + * This takes a export function or an array. + * + * When a export function is passed, Acorn will call that export function with `(block, text, start, + * end)` parameters whenever a comment is skipped. `block` is a + * boolean indicating whether this is a block (`/* *\/`) comment, + * `text` is the content of the comment, and `start` and `end` are + * character offsets that denote the start and end of the comment. + * When the {@link locations} option is on, two more parameters are + * passed, the full locations of {@link Position} export type of the start and + * end of the comments. + * + * When a array is passed, each found comment of {@link Comment} export type is pushed to the array. + * + * Note that you are not allowed to call the + * parser from the callback—that will corrupt its internal state. + */ + onComment?: (( + isBlock: boolean, text: string, start: number, end: number, startLoc?: Position, + endLoc?: Position + ) => void) | Comment[] + + /** + * Nodes have their start and end characters offsets recorded in + * `start` and `end` properties (directly on the node, rather than + * the `loc` object, which holds line/column data. To also add a + * [semi-standardized][range] `range` property holding a `[start, + * end]` array with the same numbers, set the `ranges` option to + * `true`. + */ + ranges?: boolean + + /** + * It is possible to parse multiple files into a single AST by + * passing the tree produced by parsing the first file as + * `program` option in subsequent parses. This will add the + * toplevel forms of the parsed file to the `Program` (top) node + * of an existing parse tree. + */ + program?: Node + + /** + * When {@link locations} is on, you can pass this to record the source + * file in every node's `loc` object. + */ + sourceFile?: string + + /** + * This value, if given, is stored in every node, whether {@link locations} is on or off. + */ + directSourceFile?: string + + /** + * When enabled, parenthesized expressions are represented by + * (non-standard) ParenthesizedExpression nodes + */ + preserveParens?: boolean +} + +export class Parser { + options: Options + input: string + + private constructor(options: Options, input: string, startPos?: number) + parse(): Program + + static parse(input: string, options: Options): Program + static parseExpressionAt(input: string, pos: number, options: Options): Expression + static tokenizer(input: string, options: Options): { + getToken(): Token + [Symbol.iterator](): Iterator + } + static extend(...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser +} + +export const defaultOptions: Options + +export function getLineInfo(input: string, offset: number): Position + +export class TokenType { + label: string + keyword: string | undefined +} + +export const tokTypes: { + num: TokenType + regexp: TokenType + string: TokenType + name: TokenType + privateId: TokenType + eof: TokenType + + bracketL: TokenType + bracketR: TokenType + braceL: TokenType + braceR: TokenType + parenL: TokenType + parenR: TokenType + comma: TokenType + semi: TokenType + colon: TokenType + dot: TokenType + question: TokenType + questionDot: TokenType + arrow: TokenType + template: TokenType + invalidTemplate: TokenType + ellipsis: TokenType + backQuote: TokenType + dollarBraceL: TokenType + + eq: TokenType + assign: TokenType + incDec: TokenType + prefix: TokenType + logicalOR: TokenType + logicalAND: TokenType + bitwiseOR: TokenType + bitwiseXOR: TokenType + bitwiseAND: TokenType + equality: TokenType + relational: TokenType + bitShift: TokenType + plusMin: TokenType + modulo: TokenType + star: TokenType + slash: TokenType + starstar: TokenType + coalesce: TokenType + + _break: TokenType + _case: TokenType + _catch: TokenType + _continue: TokenType + _debugger: TokenType + _default: TokenType + _do: TokenType + _else: TokenType + _finally: TokenType + _for: TokenType + _function: TokenType + _if: TokenType + _return: TokenType + _switch: TokenType + _throw: TokenType + _try: TokenType + _var: TokenType + _const: TokenType + _while: TokenType + _with: TokenType + _new: TokenType + _this: TokenType + _super: TokenType + _class: TokenType + _extends: TokenType + _export: TokenType + _import: TokenType + _null: TokenType + _true: TokenType + _false: TokenType + _in: TokenType + _instanceof: TokenType + _typeof: TokenType + _void: TokenType + _delete: TokenType +} + +export interface Comment { + type: "Line" | "Block" + value: string + start: number + end: number + loc?: SourceLocation + range?: [number, number] +} + +export class Token { + type: TokenType + start: number + end: number + loc?: SourceLocation + range?: [number, number] +} + +export const version: string diff --git a/node_modules/acorn/dist/acorn.js b/node_modules/acorn/dist/acorn.js new file mode 100644 index 0000000..3a6a3a2 --- /dev/null +++ b/node_modules/acorn/dist/acorn.js @@ -0,0 +1,6002 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.acorn = {})); +})(this, (function (exports) { 'use strict'; + + // This file was generated. Do not modify manually! + var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + + // This file was generated. Do not modify manually! + var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191]; + + // This file was generated. Do not modify manually! + var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65"; + + // This file was generated. Do not modify manually! + var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; + + // These are a run-length and offset encoded representation of the + // >0xffff code points that are a valid part of identifiers. The + // offset starts at 0x10000, and each pair of numbers represents an + // offset to the next range, and then a size of the range. + + // Reserved word lists for various dialects of the language + + var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" + }; + + // And the keywords + + var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; + + var keywords$1 = { + 5: ecma5AndLessKeywords, + "5module": ecma5AndLessKeywords + " export import", + 6: ecma5AndLessKeywords + " const class extends export import super" + }; + + var keywordRelationalOperator = /^in(stanceof)?$/; + + // ## Character categories + + var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + + // This has a complexity linear to the value of the code. The + // assumption is that looking up astral identifier characters is + // rare. + function isInAstralSet(code, set) { + var pos = 0x10000; + for (var i = 0; i < set.length; i += 2) { + pos += set[i]; + if (pos > code) { return false } + pos += set[i + 1]; + if (pos >= code) { return true } + } + return false + } + + // Test whether a given character code starts an identifier. + + function isIdentifierStart(code, astral) { + if (code < 65) { return code === 36 } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) + } + + // Test whether a given character is part of an identifier. + + function isIdentifierChar(code, astral) { + if (code < 48) { return code === 36 } + if (code < 58) { return true } + if (code < 65) { return false } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) + } + + // ## Token types + + // The assignment of fine-grained, information-carrying type objects + // allows the tokenizer to store the information it has about a + // token in a way that is very cheap for the parser to look up. + + // All token type variables start with an underscore, to make them + // easy to recognize. + + // The `beforeExpr` property is used to disambiguate between regular + // expressions and divisions. It is set on all token types that can + // be followed by an expression (thus, a slash after them would be a + // regular expression). + // + // The `startsExpr` property is used to check if the token ends a + // `yield` expression. It is set on all token types that either can + // directly start an expression (like a quotation mark) or can + // continue an expression (like the body of a string). + // + // `isLoop` marks a keyword as starting a loop, which is important + // to know when parsing a label, in order to allow or disallow + // continue jumps to that label. + + var TokenType = function TokenType(label, conf) { + if ( conf === void 0 ) conf = {}; + + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop || null; + this.updateContext = null; + }; + + function binop(name, prec) { + return new TokenType(name, {beforeExpr: true, binop: prec}) + } + var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; + + // Map keyword names to token types. + + var keywords = {}; + + // Succinct definitions of keyword token types + function kw(name, options) { + if ( options === void 0 ) options = {}; + + options.keyword = name; + return keywords[name] = new TokenType(name, options) + } + + var types$1 = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + privateId: new TokenType("privateId", startsExpr), + eof: new TokenType("eof"), + + // Punctuation token types. + bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), + bracketR: new TokenType("]"), + braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), + braceR: new TokenType("}"), + parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + invalidTemplate: new TokenType("invalidTemplate"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + eq: new TokenType("=", {beforeExpr: true, isAssign: true}), + assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), + incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), + prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=/===/!==", 6), + relational: binop("/<=/>=", 7), + bitShift: binop("<>/>>>", 8), + plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", {beforeExpr: true}), + coalesce: binop("??", 1), + + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", {isLoop: true, beforeExpr: true}), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", {isLoop: true}), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", {isLoop: true}), + _with: kw("with"), + _new: kw("new", {beforeExpr: true, startsExpr: true}), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class", startsExpr), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import", startsExpr), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", {beforeExpr: true, binop: 7}), + _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), + _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), + _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), + _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) + }; + + // Matches a whole line break (where CRLF is considered a single + // line break). Used to count lines. + + var lineBreak = /\r\n?|\n|\u2028|\u2029/; + var lineBreakG = new RegExp(lineBreak.source, "g"); + + function isNewLine(code) { + return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 + } + + function nextLineBreak(code, from, end) { + if ( end === void 0 ) end = code.length; + + for (var i = from; i < end; i++) { + var next = code.charCodeAt(i); + if (isNewLine(next)) + { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 } + } + return -1 + } + + var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; + + var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; + + var ref = Object.prototype; + var hasOwnProperty = ref.hasOwnProperty; + var toString = ref.toString; + + var hasOwn = Object.hasOwn || (function (obj, propName) { return ( + hasOwnProperty.call(obj, propName) + ); }); + + var isArray = Array.isArray || (function (obj) { return ( + toString.call(obj) === "[object Array]" + ); }); + + var regexpCache = Object.create(null); + + function wordsRegexp(words) { + return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")) + } + + function codePointToString(code) { + // UTF-16 Decoding + if (code <= 0xFFFF) { return String.fromCharCode(code) } + code -= 0x10000; + return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) + } + + var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; + + // These are used when `options.locations` is on, for the + // `startLoc` and `endLoc` properties. + + var Position = function Position(line, col) { + this.line = line; + this.column = col; + }; + + Position.prototype.offset = function offset (n) { + return new Position(this.line, this.column + n) + }; + + var SourceLocation = function SourceLocation(p, start, end) { + this.start = start; + this.end = end; + if (p.sourceFile !== null) { this.source = p.sourceFile; } + }; + + // The `getLineInfo` function is mostly useful when the + // `locations` option is off (for performance reasons) and you + // want to find the line/column position for a given character + // offset. `input` should be the code string that the offset refers + // into. + + function getLineInfo(input, offset) { + for (var line = 1, cur = 0;;) { + var nextBreak = nextLineBreak(input, cur, offset); + if (nextBreak < 0) { return new Position(line, offset - cur) } + ++line; + cur = nextBreak; + } + } + + // A second argument must be given to configure the parser process. + // These options are recognized (only `ecmaVersion` is required): + + var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` + // (the latest version the library supports). This influences + // support for strict mode, the set of reserved words, and support + // for new syntax features. + ecmaVersion: null, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"` or `"module"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // `onInsertedSemicolon` can be a callback that will be called when + // a semicolon is automatically inserted. It will be passed the + // position of the inserted semicolon as an offset, and if + // `locations` is enabled, it is given the location as a `{line, + // column}` object as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program, and an import.meta expression + // in a script isn't considered an error. + allowImportExportEverywhere: false, + // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: null, + // When enabled, super identifiers are not constrained to + // appearing in methods and do not raise an error when they appear elsewhere. + allowSuperOutsideMethod: null, + // When enabled, hashbang directive in the beginning of file is + // allowed and treated as a line comment. Enabled by default when + // `ecmaVersion` >= 2023. + allowHashBang: false, + // By default, the parser will verify that private properties are + // only used in places where they are valid and have been declared. + // Set this to false to turn such checks off. + checkPrivateFields: true, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + // When this option has an array as value, objects representing the + // comments are pushed to it. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false + }; + + // Interpret and default an options object + + var warnedAboutEcmaVersion = false; + + function getOptions(opts) { + var options = {}; + + for (var opt in defaultOptions) + { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; } + + if (options.ecmaVersion === "latest") { + options.ecmaVersion = 1e8; + } else if (options.ecmaVersion == null) { + if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { + warnedAboutEcmaVersion = true; + console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); + } + options.ecmaVersion = 11; + } else if (options.ecmaVersion >= 2015) { + options.ecmaVersion -= 2009; + } + + if (options.allowReserved == null) + { options.allowReserved = options.ecmaVersion < 5; } + + if (!opts || opts.allowHashBang == null) + { options.allowHashBang = options.ecmaVersion >= 14; } + + if (isArray(options.onToken)) { + var tokens = options.onToken; + options.onToken = function (token) { return tokens.push(token); }; + } + if (isArray(options.onComment)) + { options.onComment = pushComment(options, options.onComment); } + + return options + } + + function pushComment(options, array) { + return function(block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? "Block" : "Line", + value: text, + start: start, + end: end + }; + if (options.locations) + { comment.loc = new SourceLocation(this, startLoc, endLoc); } + if (options.ranges) + { comment.range = [start, end]; } + array.push(comment); + } + } + + // Each scope gets a bitset that may contain these flags + var + SCOPE_TOP = 1, + SCOPE_FUNCTION = 2, + SCOPE_ASYNC = 4, + SCOPE_GENERATOR = 8, + SCOPE_ARROW = 16, + SCOPE_SIMPLE_CATCH = 32, + SCOPE_SUPER = 64, + SCOPE_DIRECT_SUPER = 128, + SCOPE_CLASS_STATIC_BLOCK = 256, + SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; + + function functionFlags(async, generator) { + return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) + } + + // Used in checkLVal* and declareName to determine the type of a binding + var + BIND_NONE = 0, // Not a binding + BIND_VAR = 1, // Var-style binding + BIND_LEXICAL = 2, // Let- or const-style binding + BIND_FUNCTION = 3, // Function declaration + BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding + BIND_OUTSIDE = 5; // Special case for function names as bound inside the function + + var Parser = function Parser(options, input, startPos) { + this.options = options = getOptions(options); + this.sourceFile = options.sourceFile; + this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); + var reserved = ""; + if (options.allowReserved !== true) { + reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; + if (options.sourceType === "module") { reserved += " await"; } + } + this.reservedWords = wordsRegexp(reserved); + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; + this.reservedWordsStrict = wordsRegexp(reservedStrict); + this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); + this.input = String(input); + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + this.containsEsc = false; + + // Set up token state + + // The current position of the tokenizer in the input. + if (startPos) { + this.pos = startPos; + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; + } else { + this.pos = this.lineStart = 0; + this.curLine = 1; + } + + // Properties of the current token: + // Its type + this.type = types$1.eof; + // For tokens that include more information than their type, the value + this.value = null; + // Its start and end offset + this.start = this.end = this.pos; + // And, if locations are used, the {line, column} object + // corresponding to those offsets + this.startLoc = this.endLoc = this.curPosition(); + + // Position information for the previous token + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; + + // The context stack is used to superficially track syntactic + // context to predict whether a regular expression is allowed in a + // given position. + this.context = this.initialContext(); + this.exprAllowed = true; + + // Figure out if it's a module code. + this.inModule = options.sourceType === "module"; + this.strict = this.inModule || this.strictDirective(this.pos); + + // Used to signify the start of a potential arrow function + this.potentialArrowAt = -1; + this.potentialArrowInForAwait = false; + + // Positions to delayed-check that yield/await does not exist in default parameters. + this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; + // Labels in scope. + this.labels = []; + // Thus-far undefined exports. + this.undefinedExports = Object.create(null); + + // If enabled, skip leading hashbang line. + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") + { this.skipLineComment(2); } + + // Scope tracking for duplicate variable names (see scope.js) + this.scopeStack = []; + this.enterScope(SCOPE_TOP); + + // For RegExp validation + this.regexpState = null; + + // The stack of private names. + // Each element has two properties: 'declared' and 'used'. + // When it exited from the outermost class definition, all used private names must be declared. + this.privateNameStack = []; + }; + + var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; + + Parser.prototype.parse = function parse () { + var node = this.options.program || this.startNode(); + this.nextToken(); + return this.parseTopLevel(node) + }; + + prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; + + prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit }; + + prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }; + + prototypeAccessors.canAwait.get = function () { + for (var i = this.scopeStack.length - 1; i >= 0; i--) { + var scope = this.scopeStack[i]; + if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false } + if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 } + } + return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction + }; + + prototypeAccessors.allowSuper.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod + }; + + prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; + + prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; + + prototypeAccessors.allowNewDotTarget.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit + }; + + prototypeAccessors.inClassStaticBlock.get = function () { + return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0 + }; + + Parser.extend = function extend () { + var plugins = [], len = arguments.length; + while ( len-- ) plugins[ len ] = arguments[ len ]; + + var cls = this; + for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } + return cls + }; + + Parser.parse = function parse (input, options) { + return new this(options, input).parse() + }; + + Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { + var parser = new this(options, input, pos); + parser.nextToken(); + return parser.parseExpression() + }; + + Parser.tokenizer = function tokenizer (input, options) { + return new this(options, input) + }; + + Object.defineProperties( Parser.prototype, prototypeAccessors ); + + var pp$9 = Parser.prototype; + + // ## Parser utilities + + var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; + pp$9.strictDirective = function(start) { + if (this.options.ecmaVersion < 5) { return false } + for (;;) { + // Try to find string literal. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + var match = literal.exec(this.input.slice(start)); + if (!match) { return false } + if ((match[1] || match[2]) === "use strict") { + skipWhiteSpace.lastIndex = start + match[0].length; + var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; + var next = this.input.charAt(end); + return next === ";" || next === "}" || + (lineBreak.test(spaceAfter[0]) && + !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) + } + start += match[0].length; + + // Skip semicolon, if any. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + if (this.input[start] === ";") + { start++; } + } + }; + + // Predicate that tests whether the next token is of the given + // type, and if yes, consumes it as a side effect. + + pp$9.eat = function(type) { + if (this.type === type) { + this.next(); + return true + } else { + return false + } + }; + + // Tests whether parsed token is a contextual keyword. + + pp$9.isContextual = function(name) { + return this.type === types$1.name && this.value === name && !this.containsEsc + }; + + // Consumes contextual keyword if possible. + + pp$9.eatContextual = function(name) { + if (!this.isContextual(name)) { return false } + this.next(); + return true + }; + + // Asserts that following token is given contextual keyword. + + pp$9.expectContextual = function(name) { + if (!this.eatContextual(name)) { this.unexpected(); } + }; + + // Test whether a semicolon can be inserted at the current position. + + pp$9.canInsertSemicolon = function() { + return this.type === types$1.eof || + this.type === types$1.braceR || + lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; + + pp$9.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) + { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } + return true + } + }; + + // Consume a semicolon, or, failing that, see if we are allowed to + // pretend that there is a semicolon at this position. + + pp$9.semicolon = function() { + if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); } + }; + + pp$9.afterTrailingComma = function(tokType, notNext) { + if (this.type === tokType) { + if (this.options.onTrailingComma) + { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } + if (!notNext) + { this.next(); } + return true + } + }; + + // Expect a token of a given type. If found, consume it, otherwise, + // raise an unexpected token error. + + pp$9.expect = function(type) { + this.eat(type) || this.unexpected(); + }; + + // Raise an unexpected token error. + + pp$9.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); + }; + + var DestructuringErrors = function DestructuringErrors() { + this.shorthandAssign = + this.trailingComma = + this.parenthesizedAssign = + this.parenthesizedBind = + this.doubleProto = + -1; + }; + + pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) { + if (!refDestructuringErrors) { return } + if (refDestructuringErrors.trailingComma > -1) + { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } + var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; + if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); } + }; + + pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + if (!refDestructuringErrors) { return false } + var shorthandAssign = refDestructuringErrors.shorthandAssign; + var doubleProto = refDestructuringErrors.doubleProto; + if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } + if (shorthandAssign >= 0) + { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } + if (doubleProto >= 0) + { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } + }; + + pp$9.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) + { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } + if (this.awaitPos) + { this.raise(this.awaitPos, "Await expression cannot be a default value"); } + }; + + pp$9.isSimpleAssignTarget = function(expr) { + if (expr.type === "ParenthesizedExpression") + { return this.isSimpleAssignTarget(expr.expression) } + return expr.type === "Identifier" || expr.type === "MemberExpression" + }; + + var pp$8 = Parser.prototype; + + // ### Statement parsing + + // Parse a program. Initializes the parser, reads any number of + // statements, and wraps them in a Program node. Optionally takes a + // `program` argument. If present, the statements will be appended + // to its body instead of creating a new node. + + pp$8.parseTopLevel = function(node) { + var exports = Object.create(null); + if (!node.body) { node.body = []; } + while (this.type !== types$1.eof) { + var stmt = this.parseStatement(null, true, exports); + node.body.push(stmt); + } + if (this.inModule) + { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) + { + var name = list[i]; + + this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); + } } + this.adaptDirectivePrologue(node.body); + this.next(); + node.sourceType = this.options.sourceType; + return this.finishNode(node, "Program") + }; + + var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; + + pp$8.isLet = function(context) { + if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + // For ambiguous cases, determine if a LexicalDeclaration (or only a + // Statement) is allowed here. If context is not empty then only a Statement + // is allowed. However, `let [` is an explicit negative lookahead for + // ExpressionStatement, so special-case it first. + if (nextCh === 91 || nextCh === 92) { return true } // '[', '/' + if (context) { return false } + + if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } + if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } + var ident = this.input.slice(next, pos); + if (!keywordRelationalOperator.test(ident)) { return true } + } + return false + }; + + // check 'async [no LineTerminator here] function' + // - 'async /*foo*/ function' is OK. + // - 'async /*\n*/ function' is invalid. + pp$8.isAsyncFunction = function() { + if (this.options.ecmaVersion < 8 || !this.isContextual("async")) + { return false } + + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, after; + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 === this.input.length || + !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) + }; + + // Parse a single statement. + // + // If expecting a statement and finding a slash operator, parse a + // regular expression literal. This is to handle cases like + // `if (foo) /blah/.exec(foo)`, where looking at the previous token + // does not help. + + pp$8.parseStatement = function(context, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind; + + if (this.isLet(context)) { + starttype = types$1._var; + kind = "let"; + } + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword) + case types$1._debugger: return this.parseDebuggerStatement(node) + case types$1._do: return this.parseDoStatement(node) + case types$1._for: return this.parseForStatement(node) + case types$1._function: + // Function as sole body of either an if statement or a labeled statement + // works, but not when it is part of a labeled statement that is the sole + // body of an if statement. + if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } + return this.parseFunctionStatement(node, false, !context) + case types$1._class: + if (context) { this.unexpected(); } + return this.parseClass(node, true) + case types$1._if: return this.parseIfStatement(node) + case types$1._return: return this.parseReturnStatement(node) + case types$1._switch: return this.parseSwitchStatement(node) + case types$1._throw: return this.parseThrowStatement(node) + case types$1._try: return this.parseTryStatement(node) + case types$1._const: case types$1._var: + kind = kind || this.value; + if (context && kind !== "var") { this.unexpected(); } + return this.parseVarStatement(node, kind) + case types$1._while: return this.parseWhileStatement(node) + case types$1._with: return this.parseWithStatement(node) + case types$1.braceL: return this.parseBlock(true, node) + case types$1.semi: return this.parseEmptyStatement(node) + case types$1._export: + case types$1._import: + if (this.options.ecmaVersion > 10 && starttype === types$1._import) { + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 40 || nextCh === 46) // '(' or '.' + { return this.parseExpressionStatement(node, this.parseExpression()) } + } + + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) + { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } + if (!this.inModule) + { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } + } + return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports) + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction()) { + if (context) { this.unexpected(); } + this.next(); + return this.parseFunctionStatement(node, true, !context) + } + + var maybeName = this.value, expr = this.parseExpression(); + if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) + { return this.parseLabeledStatement(node, maybeName, expr, context) } + else { return this.parseExpressionStatement(node, expr) } + } + }; + + pp$8.parseBreakContinueStatement = function(node, keyword) { + var isBreak = keyword === "break"; + this.next(); + if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; } + else if (this.type !== types$1.name) { this.unexpected(); } + else { + node.label = this.parseIdent(); + this.semicolon(); + } + + // Verify that there is an actual destination to break or + // continue to. + var i = 0; + for (; i < this.labels.length; ++i) { + var lab = this.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } + if (node.label && isBreak) { break } + } + } + if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") + }; + + pp$8.parseDebuggerStatement = function(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement") + }; + + pp$8.parseDoStatement = function(node) { + this.next(); + this.labels.push(loopLabel); + node.body = this.parseStatement("do"); + this.labels.pop(); + this.expect(types$1._while); + node.test = this.parseParenExpression(); + if (this.options.ecmaVersion >= 6) + { this.eat(types$1.semi); } + else + { this.semicolon(); } + return this.finishNode(node, "DoWhileStatement") + }; + + // Disambiguating between a `for` and a `for`/`in` or `for`/`of` + // loop is non-trivial. Basically, we have to parse the init `var` + // statement or expression, disallowing the `in` operator (see + // the second parameter to `parseExpression`), and then check + // whether the next token is `in` or `of`. When there is no init + // part (semicolon immediately after the opening parenthesis), it + // is a regular `for` loop. + + pp$8.parseForStatement = function(node) { + this.next(); + var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; + this.labels.push(loopLabel); + this.enterScope(0); + this.expect(types$1.parenL); + if (this.type === types$1.semi) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, null) + } + var isLet = this.isLet(); + if (this.type === types$1._var || this.type === types$1._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value; + this.next(); + this.parseVar(init$1, true, kind); + this.finishNode(init$1, "VariableDeclaration"); + if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + return this.parseForIn(node, init$1) + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init$1) + } + var startsWithLet = this.isContextual("let"), isForOf = false; + var refDestructuringErrors = new DestructuringErrors; + var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); + if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } + this.toAssignable(init, false, refDestructuringErrors); + this.checkLValPattern(init); + return this.parseForIn(node, init) + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init) + }; + + pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) + }; + + pp$8.parseIfStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + // allow function declarations in branches, but only in non-strict mode + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement") + }; + + pp$8.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) + { this.raise(this.start, "'return' outside of function"); } + this.next(); + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; } + else { node.argument = this.parseExpression(); this.semicolon(); } + return this.finishNode(node, "ReturnStatement") + }; + + pp$8.parseSwitchStatement = function(node) { + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(types$1.braceL); + this.labels.push(switchLabel); + this.enterScope(0); + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + var cur; + for (var sawDefault = false; this.type !== types$1.braceR;) { + if (this.type === types$1._case || this.type === types$1._default) { + var isCase = this.type === types$1._case; + if (cur) { this.finishNode(cur, "SwitchCase"); } + node.cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } + sawDefault = true; + cur.test = null; + } + this.expect(types$1.colon); + } else { + if (!cur) { this.unexpected(); } + cur.consequent.push(this.parseStatement(null)); + } + } + this.exitScope(); + if (cur) { this.finishNode(cur, "SwitchCase"); } + this.next(); // Closing brace + this.labels.pop(); + return this.finishNode(node, "SwitchStatement") + }; + + pp$8.parseThrowStatement = function(node) { + this.next(); + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) + { this.raise(this.lastTokEnd, "Illegal newline after throw"); } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement") + }; + + // Reused empty array added for node fields that are always empty. + + var empty$1 = []; + + pp$8.parseCatchClauseParam = function() { + var param = this.parseBindingAtom(); + var simple = param.type === "Identifier"; + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); + this.expect(types$1.parenR); + + return param + }; + + pp$8.parseTryStatement = function(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.type === types$1._catch) { + var clause = this.startNode(); + this.next(); + if (this.eat(types$1.parenL)) { + clause.param = this.parseCatchClauseParam(); + } else { + if (this.options.ecmaVersion < 10) { this.unexpected(); } + clause.param = null; + this.enterScope(0); + } + clause.body = this.parseBlock(false); + this.exitScope(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) + { this.raise(node.start, "Missing catch or finally clause"); } + return this.finishNode(node, "TryStatement") + }; + + pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) { + this.next(); + this.parseVar(node, false, kind, allowMissingInitializer); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration") + }; + + pp$8.parseWhileStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + this.labels.push(loopLabel); + node.body = this.parseStatement("while"); + this.labels.pop(); + return this.finishNode(node, "WhileStatement") + }; + + pp$8.parseWithStatement = function(node) { + if (this.strict) { this.raise(this.start, "'with' in strict mode"); } + this.next(); + node.object = this.parseParenExpression(); + node.body = this.parseStatement("with"); + return this.finishNode(node, "WithStatement") + }; + + pp$8.parseEmptyStatement = function(node) { + this.next(); + return this.finishNode(node, "EmptyStatement") + }; + + pp$8.parseLabeledStatement = function(node, maybeName, expr, context) { + for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) + { + var label = list[i$1]; + + if (label.name === maybeName) + { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } } + var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; + for (var i = this.labels.length - 1; i >= 0; i--) { + var label$1 = this.labels[i]; + if (label$1.statementStart === node.start) { + // Update information about previous labels on this node + label$1.statementStart = this.start; + label$1.kind = kind; + } else { break } + } + this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); + node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement") + }; + + pp$8.parseExpressionStatement = function(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement") + }; + + // Parse a semicolon-enclosed block of statements, handling `"use + // strict"` declarations when `allowStrict` is true (used for + // function bodies). + + pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) { + if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; + if ( node === void 0 ) node = this.startNode(); + + node.body = []; + this.expect(types$1.braceL); + if (createNewLexicalScope) { this.enterScope(0); } + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + if (exitStrict) { this.strict = false; } + this.next(); + if (createNewLexicalScope) { this.exitScope(); } + return this.finishNode(node, "BlockStatement") + }; + + // Parse a regular `for` loop. The disambiguation code in + // `parseStatement` will already have parsed the init statement or + // expression. + + pp$8.parseFor = function(node, init) { + node.init = init; + this.expect(types$1.semi); + node.test = this.type === types$1.semi ? null : this.parseExpression(); + this.expect(types$1.semi); + node.update = this.type === types$1.parenR ? null : this.parseExpression(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, "ForStatement") + }; + + // Parse a `for`/`in` and `for`/`of` loop, which are almost + // same from parser's perspective. + + pp$8.parseForIn = function(node, init) { + var isForIn = this.type === types$1._in; + this.next(); + + if ( + init.type === "VariableDeclaration" && + init.declarations[0].init != null && + ( + !isForIn || + this.options.ecmaVersion < 8 || + this.strict || + init.kind !== "var" || + init.declarations[0].id.type !== "Identifier" + ) + ) { + this.raise( + init.start, + ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") + ); + } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") + }; + + // Parse a list of variable declarations. + + pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) { + node.declarations = []; + node.kind = kind; + for (;;) { + var decl = this.startNode(); + this.parseVarId(decl, kind); + if (this.eat(types$1.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { + this.unexpected(); + } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { + this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types$1.comma)) { break } + } + return node + }; + + pp$8.parseVarId = function(decl, kind) { + decl.id = this.parseBindingAtom(); + this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); + }; + + var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; + + // Parse a function declaration or literal (depending on the + // `statement & FUNC_STATEMENT`). + + // Remove `allowExpressionBody` for 7.0.0, as it is only called with false + pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { + this.initFunction(node); + if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { + if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT)) + { this.unexpected(); } + node.generator = this.eat(types$1.star); + } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + if (statement & FUNC_STATEMENT) { + node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent(); + if (node.id && !(statement & FUNC_HANGING_STATEMENT)) + // If it is a regular function declaration in sloppy mode, then it is + // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding + // mode depends on properties of the current scope (see + // treatFunctionsAsVar). + { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } + } + + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(node.async, node.generator)); + + if (!(statement & FUNC_STATEMENT)) + { node.id = this.type === types$1.name ? this.parseIdent() : null; } + + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody, false, forInit); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") + }; + + pp$8.parseFunctionParams = function(node) { + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + }; + + // Parse a class declaration or literal (depending on the + // `isStatement` parameter). + + pp$8.parseClass = function(node, isStatement) { + this.next(); + + // ecma-262 14.6 Class Definitions + // A class definition is always strict mode code. + var oldStrict = this.strict; + this.strict = true; + + this.parseClassId(node, isStatement); + this.parseClassSuper(node); + var privateNameMap = this.enterClassBody(); + var classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types$1.braceL); + while (this.type !== types$1.braceR) { + var element = this.parseClassElement(node.superClass !== null); + if (element) { + classBody.body.push(element); + if (element.type === "MethodDefinition" && element.kind === "constructor") { + if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); } + hadConstructor = true; + } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { + this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); + } + } + } + this.strict = oldStrict; + this.next(); + node.body = this.finishNode(classBody, "ClassBody"); + this.exitClassBody(); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") + }; + + pp$8.parseClassElement = function(constructorAllowsSuper) { + if (this.eat(types$1.semi)) { return null } + + var ecmaVersion = this.options.ecmaVersion; + var node = this.startNode(); + var keyName = ""; + var isGenerator = false; + var isAsync = false; + var kind = "method"; + var isStatic = false; + + if (this.eatContextual("static")) { + // Parse static init block + if (ecmaVersion >= 13 && this.eat(types$1.braceL)) { + this.parseClassStaticBlock(node); + return node + } + if (this.isClassElementNameStart() || this.type === types$1.star) { + isStatic = true; + } else { + keyName = "static"; + } + } + node.static = isStatic; + if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { + isAsync = true; + } else { + keyName = "async"; + } + } + if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) { + isGenerator = true; + } + if (!keyName && !isAsync && !isGenerator) { + var lastValue = this.value; + if (this.eatContextual("get") || this.eatContextual("set")) { + if (this.isClassElementNameStart()) { + kind = lastValue; + } else { + keyName = lastValue; + } + } + } + + // Parse element name + if (keyName) { + // 'async', 'get', 'set', or 'static' were not a keyword contextually. + // The last token is any of those. Make it the element name. + node.computed = false; + node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); + node.key.name = keyName; + this.finishNode(node.key, "Identifier"); + } else { + this.parseClassElementName(node); + } + + // Parse element value + if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { + var isConstructor = !node.static && checkKeyName(node, "constructor"); + var allowsDirectSuper = isConstructor && constructorAllowsSuper; + // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. + if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } + node.kind = isConstructor ? "constructor" : kind; + this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); + } else { + this.parseClassField(node); + } + + return node + }; + + pp$8.isClassElementNameStart = function() { + return ( + this.type === types$1.name || + this.type === types$1.privateId || + this.type === types$1.num || + this.type === types$1.string || + this.type === types$1.bracketL || + this.type.keyword + ) + }; + + pp$8.parseClassElementName = function(element) { + if (this.type === types$1.privateId) { + if (this.value === "constructor") { + this.raise(this.start, "Classes can't have an element named '#constructor'"); + } + element.computed = false; + element.key = this.parsePrivateIdent(); + } else { + this.parsePropertyName(element); + } + }; + + pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + // Check key and flags + var key = method.key; + if (method.kind === "constructor") { + if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } + if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } + } else if (method.static && checkKeyName(method, "prototype")) { + this.raise(key.start, "Classes may not have a static property named prototype"); + } + + // Parse value + var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + + // Check value + if (method.kind === "get" && value.params.length !== 0) + { this.raiseRecoverable(value.start, "getter should have no params"); } + if (method.kind === "set" && value.params.length !== 1) + { this.raiseRecoverable(value.start, "setter should have exactly one param"); } + if (method.kind === "set" && value.params[0].type === "RestElement") + { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } + + return this.finishNode(method, "MethodDefinition") + }; + + pp$8.parseClassField = function(field) { + if (checkKeyName(field, "constructor")) { + this.raise(field.key.start, "Classes can't have a field named 'constructor'"); + } else if (field.static && checkKeyName(field, "prototype")) { + this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); + } + + if (this.eat(types$1.eq)) { + // To raise SyntaxError if 'arguments' exists in the initializer. + var scope = this.currentThisScope(); + var inClassFieldInit = scope.inClassFieldInit; + scope.inClassFieldInit = true; + field.value = this.parseMaybeAssign(); + scope.inClassFieldInit = inClassFieldInit; + } else { + field.value = null; + } + this.semicolon(); + + return this.finishNode(field, "PropertyDefinition") + }; + + pp$8.parseClassStaticBlock = function(node) { + node.body = []; + + var oldLabels = this.labels; + this.labels = []; + this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + this.next(); + this.exitScope(); + this.labels = oldLabels; + + return this.finishNode(node, "StaticBlock") + }; + + pp$8.parseClassId = function(node, isStatement) { + if (this.type === types$1.name) { + node.id = this.parseIdent(); + if (isStatement) + { this.checkLValSimple(node.id, BIND_LEXICAL, false); } + } else { + if (isStatement === true) + { this.unexpected(); } + node.id = null; + } + }; + + pp$8.parseClassSuper = function(node) { + node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null; + }; + + pp$8.enterClassBody = function() { + var element = {declared: Object.create(null), used: []}; + this.privateNameStack.push(element); + return element.declared + }; + + pp$8.exitClassBody = function() { + var ref = this.privateNameStack.pop(); + var declared = ref.declared; + var used = ref.used; + if (!this.options.checkPrivateFields) { return } + var len = this.privateNameStack.length; + var parent = len === 0 ? null : this.privateNameStack[len - 1]; + for (var i = 0; i < used.length; ++i) { + var id = used[i]; + if (!hasOwn(declared, id.name)) { + if (parent) { + parent.used.push(id); + } else { + this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); + } + } + } + }; + + function isPrivateNameConflicted(privateNameMap, element) { + var name = element.key.name; + var curr = privateNameMap[name]; + + var next = "true"; + if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { + next = (element.static ? "s" : "i") + element.kind; + } + + // `class { get #a(){}; static set #a(_){} }` is also conflict. + if ( + curr === "iget" && next === "iset" || + curr === "iset" && next === "iget" || + curr === "sget" && next === "sset" || + curr === "sset" && next === "sget" + ) { + privateNameMap[name] = "true"; + return false + } else if (!curr) { + privateNameMap[name] = next; + return false + } else { + return true + } + } + + function checkKeyName(node, name) { + var computed = node.computed; + var key = node.key; + return !computed && ( + key.type === "Identifier" && key.name === name || + key.type === "Literal" && key.value === name + ) + } + + // Parses module export declaration. + + pp$8.parseExportAllDeclaration = function(node, exports) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseModuleExportName(); + this.checkExport(exports, node.exported, this.lastTokStart); + } else { + node.exported = null; + } + } + this.expectContextual("from"); + if (this.type !== types$1.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration") + }; + + pp$8.parseExport = function(node, exports) { + this.next(); + // export * from '...' + if (this.eat(types$1.star)) { + return this.parseExportAllDeclaration(node, exports) + } + if (this.eat(types$1._default)) { // export default ... + this.checkExport(exports, "default", this.lastTokStart); + node.declaration = this.parseExportDefaultDeclaration(); + return this.finishNode(node, "ExportDefaultDeclaration") + } + // export var|const|let|function|class ... + if (this.shouldParseExportStatement()) { + node.declaration = this.parseExportDeclaration(node); + if (node.declaration.type === "VariableDeclaration") + { this.checkVariableExport(exports, node.declaration.declarations); } + else + { this.checkExport(exports, node.declaration.id, node.declaration.id.start); } + node.specifiers = []; + node.source = null; + } else { // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); + if (this.eatContextual("from")) { + if (this.type !== types$1.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + } else { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) { + // check for keywords used as local names + var spec = list[i]; + + this.checkUnreserved(spec.local); + // check if export is defined + this.checkLocalExport(spec.local); + + if (spec.local.type === "Literal") { + this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); + } + } + + node.source = null; + } + this.semicolon(); + } + return this.finishNode(node, "ExportNamedDeclaration") + }; + + pp$8.parseExportDeclaration = function(node) { + return this.parseStatement(null) + }; + + pp$8.parseExportDefaultDeclaration = function() { + var isAsync; + if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { this.next(); } + return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync) + } else if (this.type === types$1._class) { + var cNode = this.startNode(); + return this.parseClass(cNode, "nullableID") + } else { + var declaration = this.parseMaybeAssign(); + this.semicolon(); + return declaration + } + }; + + pp$8.checkExport = function(exports, name, pos) { + if (!exports) { return } + if (typeof name !== "string") + { name = name.type === "Identifier" ? name.name : name.value; } + if (hasOwn(exports, name)) + { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } + exports[name] = true; + }; + + pp$8.checkPatternExport = function(exports, pat) { + var type = pat.type; + if (type === "Identifier") + { this.checkExport(exports, pat, pat.start); } + else if (type === "ObjectPattern") + { for (var i = 0, list = pat.properties; i < list.length; i += 1) + { + var prop = list[i]; + + this.checkPatternExport(exports, prop); + } } + else if (type === "ArrayPattern") + { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { + var elt = list$1[i$1]; + + if (elt) { this.checkPatternExport(exports, elt); } + } } + else if (type === "Property") + { this.checkPatternExport(exports, pat.value); } + else if (type === "AssignmentPattern") + { this.checkPatternExport(exports, pat.left); } + else if (type === "RestElement") + { this.checkPatternExport(exports, pat.argument); } + }; + + pp$8.checkVariableExport = function(exports, decls) { + if (!exports) { return } + for (var i = 0, list = decls; i < list.length; i += 1) + { + var decl = list[i]; + + this.checkPatternExport(exports, decl.id); + } + }; + + pp$8.shouldParseExportStatement = function() { + return this.type.keyword === "var" || + this.type.keyword === "const" || + this.type.keyword === "class" || + this.type.keyword === "function" || + this.isLet() || + this.isAsyncFunction() + }; + + // Parses a comma-separated list of module exports. + + pp$8.parseExportSpecifier = function(exports) { + var node = this.startNode(); + node.local = this.parseModuleExportName(); + + node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; + this.checkExport( + exports, + node.exported, + node.exported.start + ); + + return this.finishNode(node, "ExportSpecifier") + }; + + pp$8.parseExportSpecifiers = function(exports) { + var nodes = [], first = true; + // export { x, y as z } [from '...'] + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + nodes.push(this.parseExportSpecifier(exports)); + } + return nodes + }; + + // Parses import declaration. + + pp$8.parseImport = function(node) { + this.next(); + + // import '...' + if (this.type === types$1.string) { + node.specifiers = empty$1; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); + } + this.semicolon(); + return this.finishNode(node, "ImportDeclaration") + }; + + // Parses a comma-separated list of module imports. + + pp$8.parseImportSpecifier = function() { + var node = this.startNode(); + node.imported = this.parseModuleExportName(); + + if (this.eatContextual("as")) { + node.local = this.parseIdent(); + } else { + this.checkUnreserved(node.imported); + node.local = node.imported; + } + this.checkLValSimple(node.local, BIND_LEXICAL); + + return this.finishNode(node, "ImportSpecifier") + }; + + pp$8.parseImportDefaultSpecifier = function() { + // import defaultObj, { x, y as z } from '...' + var node = this.startNode(); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportDefaultSpecifier") + }; + + pp$8.parseImportNamespaceSpecifier = function() { + var node = this.startNode(); + this.next(); + this.expectContextual("as"); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportNamespaceSpecifier") + }; + + pp$8.parseImportSpecifiers = function() { + var nodes = [], first = true; + if (this.type === types$1.name) { + nodes.push(this.parseImportDefaultSpecifier()); + if (!this.eat(types$1.comma)) { return nodes } + } + if (this.type === types$1.star) { + nodes.push(this.parseImportNamespaceSpecifier()); + return nodes + } + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + nodes.push(this.parseImportSpecifier()); + } + return nodes + }; + + pp$8.parseModuleExportName = function() { + if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { + var stringLiteral = this.parseLiteral(this.value); + if (loneSurrogate.test(stringLiteral.value)) { + this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); + } + return stringLiteral + } + return this.parseIdent(true) + }; + + // Set `ExpressionStatement#directive` property for directive prologues. + pp$8.adaptDirectivePrologue = function(statements) { + for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { + statements[i].directive = statements[i].expression.raw.slice(1, -1); + } + }; + pp$8.isDirectiveCandidate = function(statement) { + return ( + this.options.ecmaVersion >= 5 && + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + typeof statement.expression.value === "string" && + // Reject parenthesized strings. + (this.input[statement.start] === "\"" || this.input[statement.start] === "'") + ) + }; + + var pp$7 = Parser.prototype; + + // Convert existing expression atom to assignable pattern + // if possible. + + pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) { + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") + { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } + break + + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break + + case "ObjectExpression": + node.type = "ObjectPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.toAssignable(prop, isBinding); + // Early error: + // AssignmentRestProperty[Yield, Await] : + // `...` DestructuringAssignmentTarget[Yield, Await] + // + // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. + if ( + prop.type === "RestElement" && + (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") + ) { + this.raise(prop.argument.start, "Unexpected token"); + } + } + break + + case "Property": + // AssignmentProperty has type === "Property" + if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } + this.toAssignable(node.value, isBinding); + break + + case "ArrayExpression": + node.type = "ArrayPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + this.toAssignableList(node.elements, isBinding); + break + + case "SpreadElement": + node.type = "RestElement"; + this.toAssignable(node.argument, isBinding); + if (node.argument.type === "AssignmentPattern") + { this.raise(node.argument.start, "Rest elements cannot have a default value"); } + break + + case "AssignmentExpression": + if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isBinding); + break + + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + break + + case "ChainExpression": + this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (!isBinding) { break } + + default: + this.raise(node.start, "Assigning to rvalue"); + } + } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + return node + }; + + // Convert list of expression atoms to binding list. + + pp$7.toAssignableList = function(exprList, isBinding) { + var end = exprList.length; + for (var i = 0; i < end; i++) { + var elt = exprList[i]; + if (elt) { this.toAssignable(elt, isBinding); } + } + if (end) { + var last = exprList[end - 1]; + if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") + { this.unexpected(last.argument.start); } + } + return exprList + }; + + // Parses spread element. + + pp$7.parseSpread = function(refDestructuringErrors) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node, "SpreadElement") + }; + + pp$7.parseRestBinding = function() { + var node = this.startNode(); + this.next(); + + // RestElement inside of a function parameter must be an identifier + if (this.options.ecmaVersion === 6 && this.type !== types$1.name) + { this.unexpected(); } + + node.argument = this.parseBindingAtom(); + + return this.finishNode(node, "RestElement") + }; + + // Parses lvalue (assignable) atom. + + pp$7.parseBindingAtom = function() { + if (this.options.ecmaVersion >= 6) { + switch (this.type) { + case types$1.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types$1.bracketR, true, true); + return this.finishNode(node, "ArrayPattern") + + case types$1.braceL: + return this.parseObj(true) + } + } + return this.parseIdent() + }; + + pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) { + var elts = [], first = true; + while (!this.eat(close)) { + if (first) { first = false; } + else { this.expect(types$1.comma); } + if (allowEmpty && this.type === types$1.comma) { + elts.push(null); + } else if (allowTrailingComma && this.afterTrailingComma(close)) { + break + } else if (this.type === types$1.ellipsis) { + var rest = this.parseRestBinding(); + this.parseBindingListItem(rest); + elts.push(rest); + if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); } + this.expect(close); + break + } else { + elts.push(this.parseAssignableListItem(allowModifiers)); + } + } + return elts + }; + + pp$7.parseAssignableListItem = function(allowModifiers) { + var elem = this.parseMaybeDefault(this.start, this.startLoc); + this.parseBindingListItem(elem); + return elem + }; + + pp$7.parseBindingListItem = function(param) { + return param + }; + + // Parses assignment pattern around given atom if possible. + + pp$7.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom(); + if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern") + }; + + // The following three functions all verify that a node is an lvalue — + // something that can be bound, or assigned to. In order to do so, they perform + // a variety of checks: + // + // - Check that none of the bound/assigned-to identifiers are reserved words. + // - Record name declarations for bindings in the appropriate scope. + // - Check duplicate argument names, if checkClashes is set. + // + // If a complex binding pattern is encountered (e.g., object and array + // destructuring), the entire pattern is recursively checked. + // + // There are three versions of checkLVal*() appropriate for different + // circumstances: + // + // - checkLValSimple() shall be used if the syntactic construct supports + // nothing other than identifiers and member expressions. Parenthesized + // expressions are also correctly handled. This is generally appropriate for + // constructs for which the spec says + // + // > It is a Syntax Error if AssignmentTargetType of [the production] is not + // > simple. + // + // It is also appropriate for checking if an identifier is valid and not + // defined elsewhere, like import declarations or function/class identifiers. + // + // Examples where this is used include: + // a += …; + // import a from '…'; + // where a is the node to be checked. + // + // - checkLValPattern() shall be used if the syntactic construct supports + // anything checkLValSimple() supports, as well as object and array + // destructuring patterns. This is generally appropriate for constructs for + // which the spec says + // + // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor + // > an ArrayLiteral and AssignmentTargetType of [the production] is not + // > simple. + // + // Examples where this is used include: + // (a = …); + // const a = …; + // try { … } catch (a) { … } + // where a is the node to be checked. + // + // - checkLValInnerPattern() shall be used if the syntactic construct supports + // anything checkLValPattern() supports, as well as default assignment + // patterns, rest elements, and other constructs that may appear within an + // object or array destructuring pattern. + // + // As a special case, function parameters also use checkLValInnerPattern(), + // as they also support defaults and rest constructs. + // + // These functions deliberately support both assignment and binding constructs, + // as the logic for both is exceedingly similar. If the node is the target of + // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it + // should be set to the appropriate BIND_* constant, like BIND_VAR or + // BIND_LEXICAL. + // + // If the function is called with a non-BIND_NONE bindingType, then + // additionally a checkClashes object may be specified to allow checking for + // duplicate argument names. checkClashes is ignored if the provided construct + // is an assignment (i.e., bindingType is BIND_NONE). + + pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + var isBind = bindingType !== BIND_NONE; + + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } + if (isBind) { + if (bindingType === BIND_LEXICAL && expr.name === "let") + { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } + if (checkClashes) { + if (hasOwn(checkClashes, expr.name)) + { this.raiseRecoverable(expr.start, "Argument name clash"); } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } + } + break + + case "ChainExpression": + this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } + break + + case "ParenthesizedExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } + return this.checkLValSimple(expr.expression, bindingType, checkClashes) + + default: + this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); + } + }; + + pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "ObjectPattern": + for (var i = 0, list = expr.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.checkLValInnerPattern(prop, bindingType, checkClashes); + } + break + + case "ArrayPattern": + for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { + var elem = list$1[i$1]; + + if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } + } + break + + default: + this.checkLValSimple(expr, bindingType, checkClashes); + } + }; + + pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "Property": + // AssignmentProperty has type === "Property" + this.checkLValInnerPattern(expr.value, bindingType, checkClashes); + break + + case "AssignmentPattern": + this.checkLValPattern(expr.left, bindingType, checkClashes); + break + + case "RestElement": + this.checkLValPattern(expr.argument, bindingType, checkClashes); + break + + default: + this.checkLValPattern(expr, bindingType, checkClashes); + } + }; + + // The algorithm used to determine whether a regexp can appear at a + // given point in the program is loosely based on sweet.js' approach. + // See https://github.com/mozilla/sweet.js/wiki/design + + + var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; + this.generator = !!generator; + }; + + var types = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", false), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), + f_stat: new TokContext("function", false), + f_expr: new TokContext("function", true), + f_expr_gen: new TokContext("function", true, false, null, true), + f_gen: new TokContext("function", false, false, null, true) + }; + + var pp$6 = Parser.prototype; + + pp$6.initialContext = function() { + return [types.b_stat] + }; + + pp$6.curContext = function() { + return this.context[this.context.length - 1] + }; + + pp$6.braceIsBlock = function(prevType) { + var parent = this.curContext(); + if (parent === types.f_expr || parent === types.f_stat) + { return true } + if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr)) + { return !parent.isExpr } + + // The check for `tt.name && exprAllowed` detects whether we are + // after a `yield` or `of` construct. See the `updateContext` for + // `tt.name`. + if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) + { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } + if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) + { return true } + if (prevType === types$1.braceL) + { return parent === types.b_stat } + if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) + { return false } + return !this.exprAllowed + }; + + pp$6.inGeneratorContext = function() { + for (var i = this.context.length - 1; i >= 1; i--) { + var context = this.context[i]; + if (context.token === "function") + { return context.generator } + } + return false + }; + + pp$6.updateContext = function(prevType) { + var update, type = this.type; + if (type.keyword && prevType === types$1.dot) + { this.exprAllowed = false; } + else if (update = type.updateContext) + { update.call(this, prevType); } + else + { this.exprAllowed = type.beforeExpr; } + }; + + // Used to handle edge cases when token context could not be inferred correctly during tokenization phase + + pp$6.overrideContext = function(tokenCtx) { + if (this.curContext() !== tokenCtx) { + this.context[this.context.length - 1] = tokenCtx; + } + }; + + // Token-specific context update code + + types$1.parenR.updateContext = types$1.braceR.updateContext = function() { + if (this.context.length === 1) { + this.exprAllowed = true; + return + } + var out = this.context.pop(); + if (out === types.b_stat && this.curContext().token === "function") { + out = this.context.pop(); + } + this.exprAllowed = !out.isExpr; + }; + + types$1.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); + this.exprAllowed = true; + }; + + types$1.dollarBraceL.updateContext = function() { + this.context.push(types.b_tmpl); + this.exprAllowed = true; + }; + + types$1.parenL.updateContext = function(prevType) { + var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; + this.context.push(statementParens ? types.p_stat : types.p_expr); + this.exprAllowed = true; + }; + + types$1.incDec.updateContext = function() { + // tokExprAllowed stays unchanged + }; + + types$1._function.updateContext = types$1._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types$1._else && + !(prevType === types$1.semi && this.curContext() !== types.p_stat) && + !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && + !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat)) + { this.context.push(types.f_expr); } + else + { this.context.push(types.f_stat); } + this.exprAllowed = false; + }; + + types$1.colon.updateContext = function() { + if (this.curContext().token === "function") { this.context.pop(); } + this.exprAllowed = true; + }; + + types$1.backQuote.updateContext = function() { + if (this.curContext() === types.q_tmpl) + { this.context.pop(); } + else + { this.context.push(types.q_tmpl); } + this.exprAllowed = false; + }; + + types$1.star.updateContext = function(prevType) { + if (prevType === types$1._function) { + var index = this.context.length - 1; + if (this.context[index] === types.f_expr) + { this.context[index] = types.f_expr_gen; } + else + { this.context[index] = types.f_gen; } + } + this.exprAllowed = true; + }; + + types$1.name.updateContext = function(prevType) { + var allowed = false; + if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { + if (this.value === "of" && !this.exprAllowed || + this.value === "yield" && this.inGeneratorContext()) + { allowed = true; } + } + this.exprAllowed = allowed; + }; + + // A recursive descent parser operates by defining functions for all + // syntactic elements, and recursively calling those, each function + // advancing the input stream and returning an AST node. Precedence + // of constructs (for example, the fact that `!x[1]` means `!(x[1])` + // instead of `(!x)[1]` is handled by the fact that the parser + // function that parses unary prefix operators is called first, and + // in turn calls the function that parses `[]` subscripts — that + // way, it'll receive the node for `x[1]` already parsed, and wraps + // *that* in the unary operator node. + // + // Acorn uses an [operator precedence parser][opp] to handle binary + // operator precedence, because it is much more compact than using + // the technique outlined above, which uses different, nesting + // functions to specify precedence, for all of the ten binary + // precedence levels that JavaScript defines. + // + // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + + + var pp$5 = Parser.prototype; + + // Check if property name clashes with already added. + // Object/class getters and setters are not allowed to clash — + // either with each other or with an init property — and in + // strict mode, init properties are also not allowed to be repeated. + + pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) { + if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") + { return } + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) + { return } + var key = prop.key; + var name; + switch (key.type) { + case "Identifier": name = key.name; break + case "Literal": name = String(key.value); break + default: return + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) { + if (refDestructuringErrors) { + if (refDestructuringErrors.doubleProto < 0) { + refDestructuringErrors.doubleProto = key.start; + } + } else { + this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); + } + } + propHash.proto = true; + } + return + } + name = "$" + name; + var other = propHash[name]; + if (other) { + var redefinition; + if (kind === "init") { + redefinition = this.strict && other.init || other.get || other.set; + } else { + redefinition = other.init || other[kind]; + } + if (redefinition) + { this.raiseRecoverable(key.start, "Redefinition of property"); } + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + }; + } + other[kind] = true; + }; + + // ### Expression parsing + + // These nest, from the most general expression type at the top to + // 'atomic', nondivisible expression types at the bottom. Most of + // the functions will simply let the function(s) below them parse, + // and, *if* the syntactic construct they handle is present, wrap + // the AST node that the inner parser gave them in another node. + + // Parse a full expression. The optional arguments are used to + // forbid the `in` operator (in for loops initalization expressions) + // and provide reference for storing '=' operator inside shorthand + // property assignment in contexts where both object expression + // and object pattern might appear (so it's possible to raise + // delayed syntax error at correct position). + + pp$5.parseExpression = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); + if (this.type === types$1.comma) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } + return this.finishNode(node, "SequenceExpression") + } + return expr + }; + + // Parse an assignment expression. This includes applications of + // operators like `+=`. + + pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { return this.parseYield(forInit) } + // The tokenizer will assume an expression is allowed after + // `yield`, but this isn't that kind of yield + else { this.exprAllowed = false; } + } + + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + oldDoubleProto = refDestructuringErrors.doubleProto; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; + } else { + refDestructuringErrors = new DestructuringErrors; + ownDestructuringErrors = true; + } + + var startPos = this.start, startLoc = this.startLoc; + if (this.type === types$1.parenL || this.type === types$1.name) { + this.potentialArrowAt = this.start; + this.potentialArrowInForAwait = forInit === "await"; + } + var left = this.parseMaybeConditional(forInit, refDestructuringErrors); + if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } + if (this.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + if (this.type === types$1.eq) + { left = this.toAssignable(left, false, refDestructuringErrors); } + if (!ownDestructuringErrors) { + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; + } + if (refDestructuringErrors.shorthandAssign >= left.start) + { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly + if (this.type === types$1.eq) + { this.checkLValPattern(left); } + else + { this.checkLValSimple(left); } + node.left = left; + this.next(); + node.right = this.parseMaybeAssign(forInit); + if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; } + return this.finishNode(node, "AssignmentExpression") + } else { + if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } + } + if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } + if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } + return left + }; + + // Parse a ternary conditional (`?:`) operator. + + pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(forInit, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + if (this.eat(types$1.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(types$1.colon); + node.alternate = this.parseMaybeAssign(forInit); + return this.finishNode(node, "ConditionalExpression") + } + return expr + }; + + // Start the precedence parser. + + pp$5.parseExprOps = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) + }; + + // Parse binary operators with the operator precedence parsing + // algorithm. `left` is the left-hand side of the operator. + // `minPrec` provides context that allows the function to stop and + // defer further parser to one of its callers when it encounters an + // operator that has a lower precedence than the set it is parsing. + + pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { + var prec = this.type.binop; + if (prec != null && (!forInit || this.type !== types$1._in)) { + if (prec > minPrec) { + var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND; + var coalesce = this.type === types$1.coalesce; + if (coalesce) { + // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. + // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. + prec = types$1.logicalAND.binop; + } + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); + if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) { + this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); + } + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) + } + } + return left + }; + + pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) { + if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.operator = op; + node.right = right; + return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") + }; + + // Parse unary operators, both prefix and postfix. + + pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && this.canAwait) { + expr = this.parseAwait(forInit); + sawUnary = true; + } else if (this.type.prefix) { + var node = this.startNode(), update = this.type === types$1.incDec; + node.operator = this.value; + node.prefix = true; + this.next(); + node.argument = this.parseMaybeUnary(null, true, update, forInit); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update) { this.checkLValSimple(node.argument); } + else if (this.strict && node.operator === "delete" && + node.argument.type === "Identifier") + { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } + else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) + { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } + else { sawUnary = true; } + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } else if (!sawUnary && this.type === types$1.privateId) { + if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); } + expr = this.parsePrivateIdent(); + // only could be private fields in 'in', such as #x in obj + if (this.type !== types$1._in) { this.unexpected(); } + } else { + expr = this.parseExprSubscripts(refDestructuringErrors, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.operator = this.value; + node$1.prefix = false; + node$1.argument = expr; + this.checkLValSimple(expr); + this.next(); + expr = this.finishNode(node$1, "UpdateExpression"); + } + } + + if (!incDec && this.eat(types$1.starstar)) { + if (sawUnary) + { this.unexpected(this.lastTokStart); } + else + { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } + } else { + return expr + } + }; + + function isPrivateFieldAccess(node) { + return ( + node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || + node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) + ) + } + + // Parse call, dot, and `[]`-subscript expressions. + + pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors, forInit); + if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") + { return expr } + var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } + if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } + if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } + } + return result + }; + + pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && + this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && + this.potentialArrowAt === base.start; + var optionalChained = false; + + while (true) { + var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); + + if (element.optional) { optionalChained = true; } + if (element === base || element.type === "ArrowFunctionExpression") { + if (optionalChained) { + var chainNode = this.startNodeAt(startPos, startLoc); + chainNode.expression = element; + element = this.finishNode(chainNode, "ChainExpression"); + } + return element + } + + base = element; + } + }; + + pp$5.shouldParseAsyncArrow = function() { + return !this.canInsertSemicolon() && this.eat(types$1.arrow) + }; + + pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) + }; + + pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { + var optionalSupported = this.options.ecmaVersion >= 11; + var optional = optionalSupported && this.eat(types$1.questionDot); + if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } + + var computed = this.eat(types$1.bracketL); + if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + if (computed) { + node.property = this.parseExpression(); + this.expect(types$1.bracketR); + } else if (this.type === types$1.privateId && base.type !== "Super") { + node.property = this.parsePrivateIdent(); + } else { + node.property = this.parseIdent(this.options.allowReserved !== "never"); + } + node.computed = !!computed; + if (optionalSupported) { + node.optional = optional; + } + base = this.finishNode(node, "MemberExpression"); + } else if (!noCalls && this.eat(types$1.parenL)) { + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); + if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + if (this.awaitIdentPos > 0) + { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit) + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.callee = base; + node$1.arguments = exprList; + if (optionalSupported) { + node$1.optional = optional; + } + base = this.finishNode(node$1, "CallExpression"); + } else if (this.type === types$1.backQuote) { + if (optional || optionalChained) { + this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); + } + var node$2 = this.startNodeAt(startPos, startLoc); + node$2.tag = base; + node$2.quasi = this.parseTemplate({isTagged: true}); + base = this.finishNode(node$2, "TaggedTemplateExpression"); + } + return base + }; + + // Parse an atomic expression — either a single token that is an + // expression, an expression started by a keyword like `function` or + // `new`, or an expression wrapped in punctuation like `()`, `[]`, + // or `{}`. + + pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) { + // If a division operator appears in an expression position, the + // tokenizer got confused, and we force it to read a regexp instead. + if (this.type === types$1.slash) { this.readRegexp(); } + + var node, canBeArrow = this.potentialArrowAt === this.start; + switch (this.type) { + case types$1._super: + if (!this.allowSuper) + { this.raise(this.start, "'super' keyword outside a method"); } + node = this.startNode(); + this.next(); + if (this.type === types$1.parenL && !this.allowDirectSuper) + { this.raise(node.start, "super() call outside constructor of a subclass"); } + // The `super` keyword can appear at below: + // SuperProperty: + // super [ Expression ] + // super . IdentifierName + // SuperCall: + // super ( Arguments ) + if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) + { this.unexpected(); } + return this.finishNode(node, "Super") + + case types$1._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression") + + case types$1.name: + var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + var id = this.parseIdent(false); + if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) { + this.overrideContext(types.f_expr); + return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) + } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types$1.arrow)) + { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && + (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { + id = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) + { this.unexpected(); } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) + } + } + return id + + case types$1.regexp: + var value = this.value; + node = this.parseLiteral(value.value); + node.regex = {pattern: value.pattern, flags: value.flags}; + return node + + case types$1.num: case types$1.string: + return this.parseLiteral(this.value) + + case types$1._null: case types$1._true: case types$1._false: + node = this.startNode(); + node.value = this.type === types$1._null ? null : this.type === types$1._true; + node.raw = this.type.keyword; + this.next(); + return this.finishNode(node, "Literal") + + case types$1.parenL: + var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); + if (refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) + { refDestructuringErrors.parenthesizedAssign = start; } + if (refDestructuringErrors.parenthesizedBind < 0) + { refDestructuringErrors.parenthesizedBind = start; } + } + return expr + + case types$1.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node, "ArrayExpression") + + case types$1.braceL: + this.overrideContext(types.b_expr); + return this.parseObj(false, refDestructuringErrors) + + case types$1._function: + node = this.startNode(); + this.next(); + return this.parseFunction(node, 0) + + case types$1._class: + return this.parseClass(this.startNode(), false) + + case types$1._new: + return this.parseNew() + + case types$1.backQuote: + return this.parseTemplate() + + case types$1._import: + if (this.options.ecmaVersion >= 11) { + return this.parseExprImport(forNew) + } else { + return this.unexpected() + } + + default: + return this.parseExprAtomDefault() + } + }; + + pp$5.parseExprAtomDefault = function() { + this.unexpected(); + }; + + pp$5.parseExprImport = function(forNew) { + var node = this.startNode(); + + // Consume `import` as an identifier for `import.meta`. + // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } + this.next(); + + if (this.type === types$1.parenL && !forNew) { + return this.parseDynamicImport(node) + } else if (this.type === types$1.dot) { + var meta = this.startNodeAt(node.start, node.loc && node.loc.start); + meta.name = "import"; + node.meta = this.finishNode(meta, "Identifier"); + return this.parseImportMeta(node) + } else { + this.unexpected(); + } + }; + + pp$5.parseDynamicImport = function(node) { + this.next(); // skip `(` + + // Parse node.source. + node.source = this.parseMaybeAssign(); + + // Verify ending. + if (!this.eat(types$1.parenR)) { + var errorPos = this.start; + if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { + this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); + } else { + this.unexpected(errorPos); + } + } + + return this.finishNode(node, "ImportExpression") + }; + + pp$5.parseImportMeta = function(node) { + this.next(); // skip `.` + + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + + if (node.property.name !== "meta") + { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } + if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) + { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } + + return this.finishNode(node, "MetaProperty") + }; + + pp$5.parseLiteral = function(value) { + var node = this.startNode(); + node.value = value; + node.raw = this.input.slice(this.start, this.end); + if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } + this.next(); + return this.finishNode(node, "Literal") + }; + + pp$5.parseParenExpression = function() { + this.expect(types$1.parenL); + var val = this.parseExpression(); + this.expect(types$1.parenR); + return val + }; + + pp$5.shouldParseArrow = function(exprList) { + return !this.canInsertSemicolon() + }; + + pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; + if (this.options.ecmaVersion >= 6) { + this.next(); + + var innerStartPos = this.start, innerStartLoc = this.startLoc; + var exprList = [], first = true, lastIsComma = false; + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + // Do not save awaitIdentPos to allow checking awaits nested in parameters + while (this.type !== types$1.parenR) { + first ? first = false : this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { + lastIsComma = true; + break + } else if (this.type === types$1.ellipsis) { + spreadStart = this.start; + exprList.push(this.parseParenItem(this.parseRestBinding())); + if (this.type === types$1.comma) { + this.raiseRecoverable( + this.start, + "Comma is not permitted after the rest element" + ); + } + break + } else { + exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); + } + } + var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; + this.expect(types$1.parenR); + + if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList, forInit) + } + + if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } + if (spreadStart) { this.unexpected(spreadStart); } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); + } + + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression") + } else { + return val + } + }; + + pp$5.parseParenItem = function(item) { + return item + }; + + pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit) + }; + + // New's precedence is slightly tricky. It must allow its argument to + // be a `[]` or dot subscript expression, but not a call — at least, + // not without wrapping it in parentheses. Thus, it uses the noCalls + // argument to parseSubscripts to prevent it from consuming the + // argument list. + + var empty = []; + + pp$5.parseNew = function() { + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } + var node = this.startNode(); + this.next(); + if (this.options.ecmaVersion >= 6 && this.type === types$1.dot) { + var meta = this.startNodeAt(node.start, node.loc && node.loc.start); + meta.name = "new"; + node.meta = this.finishNode(meta, "Identifier"); + this.next(); + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "target") + { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } + if (!this.allowNewDotTarget) + { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } + return this.finishNode(node, "MetaProperty") + } + var startPos = this.start, startLoc = this.startLoc; + node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false); + if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); } + else { node.arguments = empty; } + return this.finishNode(node, "NewExpression") + }; + + // Parse template expression. + + pp$5.parseTemplateElement = function(ref) { + var isTagged = ref.isTagged; + + var elem = this.startNode(); + if (this.type === types$1.invalidTemplate) { + if (!isTagged) { + this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); + } + elem.value = { + raw: this.value, + cooked: null + }; + } else { + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), + cooked: this.value + }; + } + this.next(); + elem.tail = this.type === types$1.backQuote; + return this.finishNode(elem, "TemplateElement") + }; + + pp$5.parseTemplate = function(ref) { + if ( ref === void 0 ) ref = {}; + var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; + + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement({isTagged: isTagged}); + node.quasis = [curElt]; + while (!curElt.tail) { + if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); } + this.expect(types$1.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(types$1.braceR); + node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); + } + this.next(); + return this.finishNode(node, "TemplateLiteral") + }; + + pp$5.isAsyncProp = function(prop) { + return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && + (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) && + !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) + }; + + // Parse an object literal or binding pattern. + + pp$5.parseObj = function(isPattern, refDestructuringErrors) { + var node = this.startNode(), first = true, propHash = {}; + node.properties = []; + this.next(); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + var prop = this.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } + node.properties.push(prop); + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") + }; + + pp$5.parseProperty = function(isPattern, refDestructuringErrors) { + var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; + if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { + if (isPattern) { + prop.argument = this.parseIdent(false); + if (this.type === types$1.comma) { + this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); + } + return this.finishNode(prop, "RestElement") + } + // Parse argument. + prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); + // To disallow trailing comma via `this.toAssignable()`. + if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + // Finish + return this.finishNode(prop, "SpreadElement") + } + if (this.options.ecmaVersion >= 6) { + prop.method = false; + prop.shorthand = false; + if (isPattern || refDestructuringErrors) { + startPos = this.start; + startLoc = this.startLoc; + } + if (!isPattern) + { isGenerator = this.eat(types$1.star); } + } + var containsEsc = this.containsEsc; + this.parsePropertyName(prop); + if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star); + this.parsePropertyName(prop); + } else { + isAsync = false; + } + this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); + return this.finishNode(prop, "Property") + }; + + pp$5.parseGetterSetter = function(prop) { + prop.kind = prop.key.name; + this.parsePropertyName(prop); + prop.value = this.parseMethod(false); + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.value.params.length !== paramCount) { + var start = prop.value.start; + if (prop.kind === "get") + { this.raiseRecoverable(start, "getter should have no params"); } + else + { this.raiseRecoverable(start, "setter should have exactly one param"); } + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") + { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } + } + }; + + pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types$1.colon) + { this.unexpected(); } + + if (this.eat(types$1.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); + prop.kind = "init"; + } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) { + if (isPattern) { this.unexpected(); } + prop.kind = "init"; + prop.method = true; + prop.value = this.parseMethod(isGenerator, isAsync); + } else if (!isPattern && !containsEsc && + this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set") && + (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { + if (isGenerator || isAsync) { this.unexpected(); } + this.parseGetterSetter(prop); + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + if (isGenerator || isAsync) { this.unexpected(); } + this.checkUnreserved(prop.key); + if (prop.key.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = startPos; } + prop.kind = "init"; + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else if (this.type === types$1.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) + { refDestructuringErrors.shorthandAssign = this.start; } + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else { + prop.value = this.copyNode(prop.key); + } + prop.shorthand = true; + } else { this.unexpected(); } + }; + + pp$5.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(types$1.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(types$1.bracketR); + return prop.key + } else { + prop.computed = false; + } + } + return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") + }; + + // Initialize empty function node. + + pp$5.initFunction = function(node) { + node.id = null; + if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } + if (this.options.ecmaVersion >= 8) { node.async = false; } + }; + + // Parse object or class method. + + pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { + var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.initFunction(node); + if (this.options.ecmaVersion >= 6) + { node.generator = isGenerator; } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false, true, false); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression") + }; + + // Parse arrow function expression with given parameters. + + pp$5.parseArrowExpression = function(node, params, isAsync, forInit) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node); + if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + + node.params = this.toAssignableList(params, true); + this.parseFunctionBody(node, true, false, forInit); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression") + }; + + // Parse function body and check parameters. + + pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { + var isExpression = isArrowFunction && this.type !== types$1.braceL; + var oldStrict = this.strict, useStrict = false; + + if (isExpression) { + node.body = this.parseMaybeAssign(forInit); + node.expression = true; + this.checkParams(node, false); + } else { + var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.end); + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + if (useStrict && nonSimple) + { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } + } + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldLabels = this.labels; + this.labels = []; + if (useStrict) { this.strict = true; } + + // Add the params to varDeclaredNames to ensure that an error is thrown + // if a let/const declaration in the function clashes with one of the params. + this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); + // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' + if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } + node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; + } + this.exitScope(); + }; + + pp$5.isSimpleParamList = function(params) { + for (var i = 0, list = params; i < list.length; i += 1) + { + var param = list[i]; + + if (param.type !== "Identifier") { return false + } } + return true + }; + + // Checks function params for various disallowed patterns such as using "eval" + // or "arguments" and duplicate parameters. + + pp$5.checkParams = function(node, allowDuplicates) { + var nameHash = Object.create(null); + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); + } + }; + + // Parses a comma-separated list of expressions, and returns them as + // an array. `close` is the token type that ends the list, and + // `allowEmpty` can be turned on to allow subsequent commas with + // nothing in between them to be parsed as `null` (which is needed + // for array literals). + + pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var elts = [], first = true; + while (!this.eat(close)) { + if (!first) { + this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(close)) { break } + } else { first = false; } + + var elt = (void 0); + if (allowEmpty && this.type === types$1.comma) + { elt = null; } + else if (this.type === types$1.ellipsis) { + elt = this.parseSpread(refDestructuringErrors); + if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) + { refDestructuringErrors.trailingComma = this.start; } + } else { + elt = this.parseMaybeAssign(false, refDestructuringErrors); + } + elts.push(elt); + } + return elts + }; + + pp$5.checkUnreserved = function(ref) { + var start = ref.start; + var end = ref.end; + var name = ref.name; + + if (this.inGenerator && name === "yield") + { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } + if (this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } + if (this.currentThisScope().inClassFieldInit && name === "arguments") + { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } + if (this.inClassStaticBlock && (name === "arguments" || name === "await")) + { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } + if (this.keywords.test(name)) + { this.raise(start, ("Unexpected keyword '" + name + "'")); } + if (this.options.ecmaVersion < 6 && + this.input.slice(start, end).indexOf("\\") !== -1) { return } + var re = this.strict ? this.reservedWordsStrict : this.reservedWords; + if (re.test(name)) { + if (!this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } + this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); + } + }; + + // Parse the next token as an identifier. If `liberal` is true (used + // when parsing properties), it will also convert keywords into + // identifiers. + + pp$5.parseIdent = function(liberal) { + var node = this.parseIdentNode(); + this.next(!!liberal); + this.finishNode(node, "Identifier"); + if (!liberal) { + this.checkUnreserved(node); + if (node.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = node.start; } + } + return node + }; + + pp$5.parseIdentNode = function() { + var node = this.startNode(); + if (this.type === types$1.name) { + node.name = this.value; + } else if (this.type.keyword) { + node.name = this.type.keyword; + + // To fix https://github.com/acornjs/acorn/issues/575 + // `class` and `function` keywords push new context into this.context. + // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. + // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword + if ((node.name === "class" || node.name === "function") && + (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { + this.context.pop(); + } + this.type = types$1.name; + } else { + this.unexpected(); + } + return node + }; + + pp$5.parsePrivateIdent = function() { + var node = this.startNode(); + if (this.type === types$1.privateId) { + node.name = this.value; + } else { + this.unexpected(); + } + this.next(); + this.finishNode(node, "PrivateIdentifier"); + + // For validating existence + if (this.options.checkPrivateFields) { + if (this.privateNameStack.length === 0) { + this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); + } else { + this.privateNameStack[this.privateNameStack.length - 1].used.push(node); + } + } + + return node + }; + + // Parses yield expression inside generator. + + pp$5.parseYield = function(forInit) { + if (!this.yieldPos) { this.yieldPos = this.start; } + + var node = this.startNode(); + this.next(); + if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(types$1.star); + node.argument = this.parseMaybeAssign(forInit); + } + return this.finishNode(node, "YieldExpression") + }; + + pp$5.parseAwait = function(forInit) { + if (!this.awaitPos) { this.awaitPos = this.start; } + + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true, false, forInit); + return this.finishNode(node, "AwaitExpression") + }; + + var pp$4 = Parser.prototype; + + // This function is used to raise exceptions on parse errors. It + // takes an offset integer (into the current `input`) to indicate + // the location of the error, attaches the position to the end + // of the error message, and then raises a `SyntaxError` with that + // message. + + pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + var err = new SyntaxError(message); + err.pos = pos; err.loc = loc; err.raisedAt = this.pos; + throw err + }; + + pp$4.raiseRecoverable = pp$4.raise; + + pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) + } + }; + + var pp$3 = Parser.prototype; + + var Scope = function Scope(flags) { + this.flags = flags; + // A list of var-declared names in the current lexical scope + this.var = []; + // A list of lexically-declared names in the current lexical scope + this.lexical = []; + // A list of lexically-declared FunctionDeclaration names in the current lexical scope + this.functions = []; + // A switch to disallow the identifier reference 'arguments' + this.inClassFieldInit = false; + }; + + // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. + + pp$3.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); + }; + + pp$3.exitScope = function() { + this.scopeStack.pop(); + }; + + // The spec says: + // > At the top level of a function, or script, function declarations are + // > treated like var declarations rather than like lexical declarations. + pp$3.treatFunctionsAsVarInScope = function(scope) { + return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) + }; + + pp$3.declareName = function(name, bindingType, pos) { + var redeclared = false; + if (bindingType === BIND_LEXICAL) { + var scope = this.currentScope(); + redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + scope.lexical.push(name); + if (this.inModule && (scope.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + } else if (bindingType === BIND_SIMPLE_CATCH) { + var scope$1 = this.currentScope(); + scope$1.lexical.push(name); + } else if (bindingType === BIND_FUNCTION) { + var scope$2 = this.currentScope(); + if (this.treatFunctionsAsVar) + { redeclared = scope$2.lexical.indexOf(name) > -1; } + else + { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } + scope$2.functions.push(name); + } else { + for (var i = this.scopeStack.length - 1; i >= 0; --i) { + var scope$3 = this.scopeStack[i]; + if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || + !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { + redeclared = true; + break + } + scope$3.var.push(name); + if (this.inModule && (scope$3.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + if (scope$3.flags & SCOPE_VAR) { break } + } + } + if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } + }; + + pp$3.checkLocalExport = function(id) { + // scope.functions must be empty as Module code is always strict. + if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && + this.scopeStack[0].var.indexOf(id.name) === -1) { + this.undefinedExports[id.name] = id; + } + }; + + pp$3.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1] + }; + + pp$3.currentVarScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR) { return scope } + } + }; + + // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. + pp$3.currentThisScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } + } + }; + + var Node = function Node(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + if (parser.options.locations) + { this.loc = new SourceLocation(parser, loc); } + if (parser.options.directSourceFile) + { this.sourceFile = parser.options.directSourceFile; } + if (parser.options.ranges) + { this.range = [pos, 0]; } + }; + + // Start an AST node, attaching a start offset. + + var pp$2 = Parser.prototype; + + pp$2.startNode = function() { + return new Node(this, this.start, this.startLoc) + }; + + pp$2.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc) + }; + + // Finish an AST node, adding `type` and `end` properties. + + function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + if (this.options.locations) + { node.loc.end = loc; } + if (this.options.ranges) + { node.range[1] = pos; } + return node + } + + pp$2.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) + }; + + // Finish node at given position + + pp$2.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) + }; + + pp$2.copyNode = function(node) { + var newNode = new Node(this, node.start, this.startLoc); + for (var prop in node) { newNode[prop] = node[prop]; } + return newNode + }; + + // This file contains Unicode properties extracted from the ECMAScript specification. + // The lists are extracted like so: + // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) + + // #table-binary-unicode-properties + var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; + var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; + var ecma11BinaryProperties = ecma10BinaryProperties; + var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; + var ecma13BinaryProperties = ecma12BinaryProperties; + var ecma14BinaryProperties = ecma13BinaryProperties; + + var unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties, + 12: ecma12BinaryProperties, + 13: ecma13BinaryProperties, + 14: ecma14BinaryProperties + }; + + // #table-binary-unicode-properties-of-strings + var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"; + + var unicodeBinaryPropertiesOfStrings = { + 9: "", + 10: "", + 11: "", + 12: "", + 13: "", + 14: ecma14BinaryPropertiesOfStrings + }; + + // #table-unicode-general-category-values + var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; + + // #table-unicode-script-values + var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; + var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; + var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; + var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; + var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; + var ecma14ScriptValues = ecma13ScriptValues + " Hrkt Katakana_Or_Hiragana Kawi Nag_Mundari Nagm Unknown Zzzz"; + + var unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues, + 12: ecma12ScriptValues, + 13: ecma13ScriptValues, + 14: ecma14ScriptValues + }; + + var data = {}; + function buildUnicodeData(ecmaVersion) { + var d = data[ecmaVersion] = { + binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), + binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]), + nonBinary: { + General_Category: wordsRegexp(unicodeGeneralCategoryValues), + Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) + } + }; + d.nonBinary.Script_Extensions = d.nonBinary.Script; + + d.nonBinary.gc = d.nonBinary.General_Category; + d.nonBinary.sc = d.nonBinary.Script; + d.nonBinary.scx = d.nonBinary.Script_Extensions; + } + + for (var i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) { + var ecmaVersion = list[i]; + + buildUnicodeData(ecmaVersion); + } + + var pp$1 = Parser.prototype; + + var RegExpValidationState = function RegExpValidationState(parser) { + this.parser = parser; + this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : ""); + this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion]; + this.source = ""; + this.flags = ""; + this.start = 0; + this.switchU = false; + this.switchV = false; + this.switchN = false; + this.pos = 0; + this.lastIntValue = 0; + this.lastStringValue = ""; + this.lastAssertionIsQuantifiable = false; + this.numCapturingParens = 0; + this.maxBackReference = 0; + this.groupNames = []; + this.backReferenceNames = []; + }; + + RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { + var unicodeSets = flags.indexOf("v") !== -1; + var unicode = flags.indexOf("u") !== -1; + this.start = start | 0; + this.source = pattern + ""; + this.flags = flags; + if (unicodeSets && this.parser.options.ecmaVersion >= 15) { + this.switchU = true; + this.switchV = true; + this.switchN = true; + } else { + this.switchU = unicode && this.parser.options.ecmaVersion >= 6; + this.switchV = false; + this.switchN = unicode && this.parser.options.ecmaVersion >= 9; + } + }; + + RegExpValidationState.prototype.raise = function raise (message) { + this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); + }; + + // If u flag is given, this returns the code point at the index (it combines a surrogate pair). + // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). + RegExpValidationState.prototype.at = function at (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return -1 + } + var c = s.charCodeAt(i); + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { + return c + } + var next = s.charCodeAt(i + 1); + return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c + }; + + RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return l + } + var c = s.charCodeAt(i), next; + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || + (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { + return i + 1 + } + return i + 2 + }; + + RegExpValidationState.prototype.current = function current (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.pos, forceU) + }; + + RegExpValidationState.prototype.lookahead = function lookahead (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.nextIndex(this.pos, forceU), forceU) + }; + + RegExpValidationState.prototype.advance = function advance (forceU) { + if ( forceU === void 0 ) forceU = false; + + this.pos = this.nextIndex(this.pos, forceU); + }; + + RegExpValidationState.prototype.eat = function eat (ch, forceU) { + if ( forceU === void 0 ) forceU = false; + + if (this.current(forceU) === ch) { + this.advance(forceU); + return true + } + return false + }; + + RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) { + if ( forceU === void 0 ) forceU = false; + + var pos = this.pos; + for (var i = 0, list = chs; i < list.length; i += 1) { + var ch = list[i]; + + var current = this.at(pos, forceU); + if (current === -1 || current !== ch) { + return false + } + pos = this.nextIndex(pos, forceU); + } + this.pos = pos; + return true + }; + + /** + * Validate the flags part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$1.validateRegExpFlags = function(state) { + var validFlags = state.validFlags; + var flags = state.flags; + + var u = false; + var v = false; + + for (var i = 0; i < flags.length; i++) { + var flag = flags.charAt(i); + if (validFlags.indexOf(flag) === -1) { + this.raise(state.start, "Invalid regular expression flag"); + } + if (flags.indexOf(flag, i + 1) > -1) { + this.raise(state.start, "Duplicate regular expression flag"); + } + if (flag === "u") { u = true; } + if (flag === "v") { v = true; } + } + if (this.options.ecmaVersion >= 15 && u && v) { + this.raise(state.start, "Invalid regular expression flag"); + } + }; + + /** + * Validate the pattern part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ + pp$1.validateRegExpPattern = function(state) { + this.regexp_pattern(state); + + // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of + // parsing contains a |GroupName|, reparse with the goal symbol + // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* + // exception if _P_ did not conform to the grammar, if any elements of _P_ + // were not matched by the parse, or if any Early Error conditions exist. + if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { + state.switchN = true; + this.regexp_pattern(state); + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern + pp$1.regexp_pattern = function(state) { + state.pos = 0; + state.lastIntValue = 0; + state.lastStringValue = ""; + state.lastAssertionIsQuantifiable = false; + state.numCapturingParens = 0; + state.maxBackReference = 0; + state.groupNames.length = 0; + state.backReferenceNames.length = 0; + + this.regexp_disjunction(state); + + if (state.pos !== state.source.length) { + // Make the same messages as V8. + if (state.eat(0x29 /* ) */)) { + state.raise("Unmatched ')'"); + } + if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { + state.raise("Lone quantifier brackets"); + } + } + if (state.maxBackReference > state.numCapturingParens) { + state.raise("Invalid escape"); + } + for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { + var name = list[i]; + + if (state.groupNames.indexOf(name) === -1) { + state.raise("Invalid named capture referenced"); + } + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction + pp$1.regexp_disjunction = function(state) { + this.regexp_alternative(state); + while (state.eat(0x7C /* | */)) { + this.regexp_alternative(state); + } + + // Make the same message as V8. + if (this.regexp_eatQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + if (state.eat(0x7B /* { */)) { + state.raise("Lone quantifier brackets"); + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative + pp$1.regexp_alternative = function(state) { + while (state.pos < state.source.length && this.regexp_eatTerm(state)) + { } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term + pp$1.regexp_eatTerm = function(state) { + if (this.regexp_eatAssertion(state)) { + // Handle `QuantifiableAssertion Quantifier` alternative. + // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion + // is a QuantifiableAssertion. + if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { + // Make the same message as V8. + if (state.switchU) { + state.raise("Invalid quantifier"); + } + } + return true + } + + if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { + this.regexp_eatQuantifier(state); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion + pp$1.regexp_eatAssertion = function(state) { + var start = state.pos; + state.lastAssertionIsQuantifiable = false; + + // ^, $ + if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { + return true + } + + // \b \B + if (state.eat(0x5C /* \ */)) { + if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { + return true + } + state.pos = start; + } + + // Lookahead / Lookbehind + if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { + var lookbehind = false; + if (this.options.ecmaVersion >= 9) { + lookbehind = state.eat(0x3C /* < */); + } + if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { + this.regexp_disjunction(state); + if (!state.eat(0x29 /* ) */)) { + state.raise("Unterminated group"); + } + state.lastAssertionIsQuantifiable = !lookbehind; + return true + } + } + + state.pos = start; + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier + pp$1.regexp_eatQuantifier = function(state, noError) { + if ( noError === void 0 ) noError = false; + + if (this.regexp_eatQuantifierPrefix(state, noError)) { + state.eat(0x3F /* ? */); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix + pp$1.regexp_eatQuantifierPrefix = function(state, noError) { + return ( + state.eat(0x2A /* * */) || + state.eat(0x2B /* + */) || + state.eat(0x3F /* ? */) || + this.regexp_eatBracedQuantifier(state, noError) + ) + }; + pp$1.regexp_eatBracedQuantifier = function(state, noError) { + var start = state.pos; + if (state.eat(0x7B /* { */)) { + var min = 0, max = -1; + if (this.regexp_eatDecimalDigits(state)) { + min = state.lastIntValue; + if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { + max = state.lastIntValue; + } + if (state.eat(0x7D /* } */)) { + // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term + if (max !== -1 && max < min && !noError) { + state.raise("numbers out of order in {} quantifier"); + } + return true + } + } + if (state.switchU && !noError) { + state.raise("Incomplete quantifier"); + } + state.pos = start; + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom + pp$1.regexp_eatAtom = function(state) { + return ( + this.regexp_eatPatternCharacters(state) || + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) + ) + }; + pp$1.regexp_eatReverseSolidusAtomEscape = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatAtomEscape(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatUncapturingGroup = function(state) { + var start = state.pos; + if (state.eat(0x28 /* ( */)) { + if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + return true + } + state.raise("Unterminated group"); + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatCapturingGroup = function(state) { + if (state.eat(0x28 /* ( */)) { + if (this.options.ecmaVersion >= 9) { + this.regexp_groupSpecifier(state); + } else if (state.current() === 0x3F /* ? */) { + state.raise("Invalid group"); + } + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + state.numCapturingParens += 1; + return true + } + state.raise("Unterminated group"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom + pp$1.regexp_eatExtendedAtom = function(state) { + return ( + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) || + this.regexp_eatInvalidBracedQuantifier(state) || + this.regexp_eatExtendedPatternCharacter(state) + ) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier + pp$1.regexp_eatInvalidBracedQuantifier = function(state) { + if (this.regexp_eatBracedQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter + pp$1.regexp_eatSyntaxCharacter = function(state) { + var ch = state.current(); + if (isSyntaxCharacter(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false + }; + function isSyntaxCharacter(ch) { + return ( + ch === 0x24 /* $ */ || + ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || + ch === 0x2E /* . */ || + ch === 0x3F /* ? */ || + ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter + // But eat eager. + pp$1.regexp_eatPatternCharacters = function(state) { + var start = state.pos; + var ch = 0; + while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { + state.advance(); + } + return state.pos !== start + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter + pp$1.regexp_eatExtendedPatternCharacter = function(state) { + var ch = state.current(); + if ( + ch !== -1 && + ch !== 0x24 /* $ */ && + !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && + ch !== 0x2E /* . */ && + ch !== 0x3F /* ? */ && + ch !== 0x5B /* [ */ && + ch !== 0x5E /* ^ */ && + ch !== 0x7C /* | */ + ) { + state.advance(); + return true + } + return false + }; + + // GroupSpecifier :: + // [empty] + // `?` GroupName + pp$1.regexp_groupSpecifier = function(state) { + if (state.eat(0x3F /* ? */)) { + if (this.regexp_eatGroupName(state)) { + if (state.groupNames.indexOf(state.lastStringValue) !== -1) { + state.raise("Duplicate capture group name"); + } + state.groupNames.push(state.lastStringValue); + return + } + state.raise("Invalid group"); + } + }; + + // GroupName :: + // `<` RegExpIdentifierName `>` + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$1.regexp_eatGroupName = function(state) { + state.lastStringValue = ""; + if (state.eat(0x3C /* < */)) { + if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { + return true + } + state.raise("Invalid capture group name"); + } + return false + }; + + // RegExpIdentifierName :: + // RegExpIdentifierStart + // RegExpIdentifierName RegExpIdentifierPart + // Note: this updates `state.lastStringValue` property with the eaten name. + pp$1.regexp_eatRegExpIdentifierName = function(state) { + state.lastStringValue = ""; + if (this.regexp_eatRegExpIdentifierStart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + while (this.regexp_eatRegExpIdentifierPart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + } + return true + } + return false + }; + + // RegExpIdentifierStart :: + // UnicodeIDStart + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + pp$1.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false + }; + function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ + } + + // RegExpIdentifierPart :: + // UnicodeIDContinue + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[+U] + // + // + pp$1.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false + }; + function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape + pp$1.regexp_eatAtomEscape = function(state) { + if ( + this.regexp_eatBackReference(state) || + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) || + (state.switchN && this.regexp_eatKGroupName(state)) + ) { + return true + } + if (state.switchU) { + // Make the same message as V8. + if (state.current() === 0x63 /* c */) { + state.raise("Invalid unicode escape"); + } + state.raise("Invalid escape"); + } + return false + }; + pp$1.regexp_eatBackReference = function(state) { + var start = state.pos; + if (this.regexp_eatDecimalEscape(state)) { + var n = state.lastIntValue; + if (state.switchU) { + // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape + if (n > state.maxBackReference) { + state.maxBackReference = n; + } + return true + } + if (n <= state.numCapturingParens) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatKGroupName = function(state) { + if (state.eat(0x6B /* k */)) { + if (this.regexp_eatGroupName(state)) { + state.backReferenceNames.push(state.lastStringValue); + return true + } + state.raise("Invalid named reference"); + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape + pp$1.regexp_eatCharacterEscape = function(state) { + return ( + this.regexp_eatControlEscape(state) || + this.regexp_eatCControlLetter(state) || + this.regexp_eatZero(state) || + this.regexp_eatHexEscapeSequence(state) || + this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || + (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || + this.regexp_eatIdentityEscape(state) + ) + }; + pp$1.regexp_eatCControlLetter = function(state) { + var start = state.pos; + if (state.eat(0x63 /* c */)) { + if (this.regexp_eatControlLetter(state)) { + return true + } + state.pos = start; + } + return false + }; + pp$1.regexp_eatZero = function(state) { + if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { + state.lastIntValue = 0; + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape + pp$1.regexp_eatControlEscape = function(state) { + var ch = state.current(); + if (ch === 0x74 /* t */) { + state.lastIntValue = 0x09; /* \t */ + state.advance(); + return true + } + if (ch === 0x6E /* n */) { + state.lastIntValue = 0x0A; /* \n */ + state.advance(); + return true + } + if (ch === 0x76 /* v */) { + state.lastIntValue = 0x0B; /* \v */ + state.advance(); + return true + } + if (ch === 0x66 /* f */) { + state.lastIntValue = 0x0C; /* \f */ + state.advance(); + return true + } + if (ch === 0x72 /* r */) { + state.lastIntValue = 0x0D; /* \r */ + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter + pp$1.regexp_eatControlLetter = function(state) { + var ch = state.current(); + if (isControlLetter(ch)) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false + }; + function isControlLetter(ch) { + return ( + (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || + (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence + pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { + if ( forceU === void 0 ) forceU = false; + + var start = state.pos; + var switchU = forceU || state.switchU; + + if (state.eat(0x75 /* u */)) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { + var leadSurrogateEnd = state.pos; + if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { + var trail = state.lastIntValue; + if (trail >= 0xDC00 && trail <= 0xDFFF) { + state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + return true + } + } + state.pos = leadSurrogateEnd; + state.lastIntValue = lead; + } + return true + } + if ( + switchU && + state.eat(0x7B /* { */) && + this.regexp_eatHexDigits(state) && + state.eat(0x7D /* } */) && + isValidUnicode(state.lastIntValue) + ) { + return true + } + if (switchU) { + state.raise("Invalid unicode escape"); + } + state.pos = start; + } + + return false + }; + function isValidUnicode(ch) { + return ch >= 0 && ch <= 0x10FFFF + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape + pp$1.regexp_eatIdentityEscape = function(state) { + if (state.switchU) { + if (this.regexp_eatSyntaxCharacter(state)) { + return true + } + if (state.eat(0x2F /* / */)) { + state.lastIntValue = 0x2F; /* / */ + return true + } + return false + } + + var ch = state.current(); + if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape + pp$1.regexp_eatDecimalEscape = function(state) { + state.lastIntValue = 0; + var ch = state.current(); + if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { + do { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) + return true + } + return false + }; + + // Return values used by character set parsing methods, needed to + // forbid negation of sets that can match strings. + var CharSetNone = 0; // Nothing parsed + var CharSetOk = 1; // Construct parsed, cannot contain strings + var CharSetString = 2; // Construct parsed, can contain strings + + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape + pp$1.regexp_eatCharacterClassEscape = function(state) { + var ch = state.current(); + + if (isCharacterClassEscape(ch)) { + state.lastIntValue = -1; + state.advance(); + return CharSetOk + } + + var negate = false; + if ( + state.switchU && + this.options.ecmaVersion >= 9 && + ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */) + ) { + state.lastIntValue = -1; + state.advance(); + var result; + if ( + state.eat(0x7B /* { */) && + (result = this.regexp_eatUnicodePropertyValueExpression(state)) && + state.eat(0x7D /* } */) + ) { + if (negate && result === CharSetString) { state.raise("Invalid property name"); } + return result + } + state.raise("Invalid property name"); + } + + return CharSetNone + }; + + function isCharacterClassEscape(ch) { + return ( + ch === 0x64 /* d */ || + ch === 0x44 /* D */ || + ch === 0x73 /* s */ || + ch === 0x53 /* S */ || + ch === 0x77 /* w */ || + ch === 0x57 /* W */ + ) + } + + // UnicodePropertyValueExpression :: + // UnicodePropertyName `=` UnicodePropertyValue + // LoneUnicodePropertyNameOrValue + pp$1.regexp_eatUnicodePropertyValueExpression = function(state) { + var start = state.pos; + + // UnicodePropertyName `=` UnicodePropertyValue + if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { + var name = state.lastStringValue; + if (this.regexp_eatUnicodePropertyValue(state)) { + var value = state.lastStringValue; + this.regexp_validateUnicodePropertyNameAndValue(state, name, value); + return CharSetOk + } + } + state.pos = start; + + // LoneUnicodePropertyNameOrValue + if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { + var nameOrValue = state.lastStringValue; + return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue) + } + return CharSetNone + }; + + pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { + if (!hasOwn(state.unicodeProperties.nonBinary, name)) + { state.raise("Invalid property name"); } + if (!state.unicodeProperties.nonBinary[name].test(value)) + { state.raise("Invalid property value"); } + }; + + pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { + if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk } + if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString } + state.raise("Invalid property name"); + }; + + // UnicodePropertyName :: + // UnicodePropertyNameCharacters + pp$1.regexp_eatUnicodePropertyName = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyNameCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + + function isUnicodePropertyNameCharacter(ch) { + return isControlLetter(ch) || ch === 0x5F /* _ */ + } + + // UnicodePropertyValue :: + // UnicodePropertyValueCharacters + pp$1.regexp_eatUnicodePropertyValue = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyValueCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" + }; + function isUnicodePropertyValueCharacter(ch) { + return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) + } + + // LoneUnicodePropertyNameOrValue :: + // UnicodePropertyValueCharacters + pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { + return this.regexp_eatUnicodePropertyValue(state) + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass + pp$1.regexp_eatCharacterClass = function(state) { + if (state.eat(0x5B /* [ */)) { + var negate = state.eat(0x5E /* ^ */); + var result = this.regexp_classContents(state); + if (!state.eat(0x5D /* ] */)) + { state.raise("Unterminated character class"); } + if (negate && result === CharSetString) + { state.raise("Negated character class may contain strings"); } + return true + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassContents + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges + pp$1.regexp_classContents = function(state) { + if (state.current() === 0x5D /* ] */) { return CharSetOk } + if (state.switchV) { return this.regexp_classSetExpression(state) } + this.regexp_nonEmptyClassRanges(state); + return CharSetOk + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges + // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash + pp$1.regexp_nonEmptyClassRanges = function(state) { + while (this.regexp_eatClassAtom(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { + var right = state.lastIntValue; + if (state.switchU && (left === -1 || right === -1)) { + state.raise("Invalid character class"); + } + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + } + } + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom + // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash + pp$1.regexp_eatClassAtom = function(state) { + var start = state.pos; + + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatClassEscape(state)) { + return true + } + if (state.switchU) { + // Make the same message as V8. + var ch$1 = state.current(); + if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { + state.raise("Invalid class escape"); + } + state.raise("Invalid escape"); + } + state.pos = start; + } + + var ch = state.current(); + if (ch !== 0x5D /* ] */) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape + pp$1.regexp_eatClassEscape = function(state) { + var start = state.pos; + + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + + if (state.switchU && state.eat(0x2D /* - */)) { + state.lastIntValue = 0x2D; /* - */ + return true + } + + if (!state.switchU && state.eat(0x63 /* c */)) { + if (this.regexp_eatClassControlLetter(state)) { + return true + } + state.pos = start; + } + + return ( + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) + ) + }; + + // https://tc39.es/ecma262/#prod-ClassSetExpression + // https://tc39.es/ecma262/#prod-ClassUnion + // https://tc39.es/ecma262/#prod-ClassIntersection + // https://tc39.es/ecma262/#prod-ClassSubtraction + pp$1.regexp_classSetExpression = function(state) { + var result = CharSetOk, subResult; + if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) { + if (subResult === CharSetString) { result = CharSetString; } + // https://tc39.es/ecma262/#prod-ClassIntersection + var start = state.pos; + while (state.eatChars([0x26, 0x26] /* && */)) { + if ( + state.current() !== 0x26 /* & */ && + (subResult = this.regexp_eatClassSetOperand(state)) + ) { + if (subResult !== CharSetString) { result = CharSetOk; } + continue + } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { return result } + // https://tc39.es/ecma262/#prod-ClassSubtraction + while (state.eatChars([0x2D, 0x2D] /* -- */)) { + if (this.regexp_eatClassSetOperand(state)) { continue } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { return result } + } else { + state.raise("Invalid character in character class"); + } + // https://tc39.es/ecma262/#prod-ClassUnion + for (;;) { + if (this.regexp_eatClassSetRange(state)) { continue } + subResult = this.regexp_eatClassSetOperand(state); + if (!subResult) { return result } + if (subResult === CharSetString) { result = CharSetString; } + } + }; + + // https://tc39.es/ecma262/#prod-ClassSetRange + pp$1.regexp_eatClassSetRange = function(state) { + var start = state.pos; + if (this.regexp_eatClassSetCharacter(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) { + var right = state.lastIntValue; + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + return true + } + state.pos = start; + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassSetOperand + pp$1.regexp_eatClassSetOperand = function(state) { + if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk } + return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state) + }; + + // https://tc39.es/ecma262/#prod-NestedClass + pp$1.regexp_eatNestedClass = function(state) { + var start = state.pos; + if (state.eat(0x5B /* [ */)) { + var negate = state.eat(0x5E /* ^ */); + var result = this.regexp_classContents(state); + if (state.eat(0x5D /* ] */)) { + if (negate && result === CharSetString) { + state.raise("Negated character class may contain strings"); + } + return result + } + state.pos = start; + } + if (state.eat(0x5C /* \ */)) { + var result$1 = this.regexp_eatCharacterClassEscape(state); + if (result$1) { + return result$1 + } + state.pos = start; + } + return null + }; + + // https://tc39.es/ecma262/#prod-ClassStringDisjunction + pp$1.regexp_eatClassStringDisjunction = function(state) { + var start = state.pos; + if (state.eatChars([0x5C, 0x71] /* \q */)) { + if (state.eat(0x7B /* { */)) { + var result = this.regexp_classStringDisjunctionContents(state); + if (state.eat(0x7D /* } */)) { + return result + } + } else { + // Make the same message as V8. + state.raise("Invalid escape"); + } + state.pos = start; + } + return null + }; + + // https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents + pp$1.regexp_classStringDisjunctionContents = function(state) { + var result = this.regexp_classString(state); + while (state.eat(0x7C /* | */)) { + if (this.regexp_classString(state) === CharSetString) { result = CharSetString; } + } + return result + }; + + // https://tc39.es/ecma262/#prod-ClassString + // https://tc39.es/ecma262/#prod-NonEmptyClassString + pp$1.regexp_classString = function(state) { + var count = 0; + while (this.regexp_eatClassSetCharacter(state)) { count++; } + return count === 1 ? CharSetOk : CharSetString + }; + + // https://tc39.es/ecma262/#prod-ClassSetCharacter + pp$1.regexp_eatClassSetCharacter = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if ( + this.regexp_eatCharacterEscape(state) || + this.regexp_eatClassSetReservedPunctuator(state) + ) { + return true + } + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + state.pos = start; + return false + } + var ch = state.current(); + if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false } + if (isClassSetSyntaxCharacter(ch)) { return false } + state.advance(); + state.lastIntValue = ch; + return true + }; + + // https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator + function isClassSetReservedDoublePunctuatorCharacter(ch) { + return ( + ch === 0x21 /* ! */ || + ch >= 0x23 /* # */ && ch <= 0x26 /* & */ || + ch >= 0x2A /* * */ && ch <= 0x2C /* , */ || + ch === 0x2E /* . */ || + ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ || + ch === 0x5E /* ^ */ || + ch === 0x60 /* ` */ || + ch === 0x7E /* ~ */ + ) + } + + // https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter + function isClassSetSyntaxCharacter(ch) { + return ( + ch === 0x28 /* ( */ || + ch === 0x29 /* ) */ || + ch === 0x2D /* - */ || + ch === 0x2F /* / */ || + ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) + } + + // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator + pp$1.regexp_eatClassSetReservedPunctuator = function(state) { + var ch = state.current(); + if (isClassSetReservedPunctuator(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false + }; + + // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator + function isClassSetReservedPunctuator(ch) { + return ( + ch === 0x21 /* ! */ || + ch === 0x23 /* # */ || + ch === 0x25 /* % */ || + ch === 0x26 /* & */ || + ch === 0x2C /* , */ || + ch === 0x2D /* - */ || + ch >= 0x3A /* : */ && ch <= 0x3E /* > */ || + ch === 0x40 /* @ */ || + ch === 0x60 /* ` */ || + ch === 0x7E /* ~ */ + ) + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter + pp$1.regexp_eatClassControlLetter = function(state) { + var ch = state.current(); + if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$1.regexp_eatHexEscapeSequence = function(state) { + var start = state.pos; + if (state.eat(0x78 /* x */)) { + if (this.regexp_eatFixedHexDigits(state, 2)) { + return true + } + if (state.switchU) { + state.raise("Invalid escape"); + } + state.pos = start; + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits + pp$1.regexp_eatDecimalDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isDecimalDigit(ch = state.current())) { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } + return state.pos !== start + }; + function isDecimalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits + pp$1.regexp_eatHexDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isHexDigit(ch = state.current())) { + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return state.pos !== start + }; + function isHexDigit(ch) { + return ( + (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || + (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || + (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) + ) + } + function hexToInt(ch) { + if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { + return 10 + (ch - 0x41 /* A */) + } + if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { + return 10 + (ch - 0x61 /* a */) + } + return ch - 0x30 /* 0 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence + // Allows only 0-377(octal) i.e. 0-255(decimal). + pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) { + if (this.regexp_eatOctalDigit(state)) { + var n1 = state.lastIntValue; + if (this.regexp_eatOctalDigit(state)) { + var n2 = state.lastIntValue; + if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { + state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; + } else { + state.lastIntValue = n1 * 8 + n2; + } + } else { + state.lastIntValue = n1; + } + return true + } + return false + }; + + // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit + pp$1.regexp_eatOctalDigit = function(state) { + var ch = state.current(); + if (isOctalDigit(ch)) { + state.lastIntValue = ch - 0x30; /* 0 */ + state.advance(); + return true + } + state.lastIntValue = 0; + return false + }; + function isOctalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ + } + + // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits + // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit + // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence + pp$1.regexp_eatFixedHexDigits = function(state, length) { + var start = state.pos; + state.lastIntValue = 0; + for (var i = 0; i < length; ++i) { + var ch = state.current(); + if (!isHexDigit(ch)) { + state.pos = start; + return false + } + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return true + }; + + // Object type used to represent tokens. Note that normally, tokens + // simply exist as properties on the parser object. This is only + // used for the onToken callback and the external tokenizer. + + var Token = function Token(p) { + this.type = p.type; + this.value = p.value; + this.start = p.start; + this.end = p.end; + if (p.options.locations) + { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } + if (p.options.ranges) + { this.range = [p.start, p.end]; } + }; + + // ## Tokenizer + + var pp = Parser.prototype; + + // Move to the next token + + pp.next = function(ignoreEscapeSequenceInKeyword) { + if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) + { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } + if (this.options.onToken) + { this.options.onToken(new Token(this)); } + + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); + }; + + pp.getToken = function() { + this.next(); + return new Token(this) + }; + + // If we're in an ES6 environment, make parsers iterable + if (typeof Symbol !== "undefined") + { pp[Symbol.iterator] = function() { + var this$1$1 = this; + + return { + next: function () { + var token = this$1$1.getToken(); + return { + done: token.type === types$1.eof, + value: token + } + } + } + }; } + + // Toggle strict mode. Re-reads the next number or string to please + // pedantic tests (`"use strict"; 010;` should fail). + + // Read a single token, updating the parser object's token-related + // properties. + + pp.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } + + this.start = this.pos; + if (this.options.locations) { this.startLoc = this.curPosition(); } + if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) } + + if (curContext.override) { return curContext.override(this) } + else { this.readToken(this.fullCharCodeAtPos()); } + }; + + pp.readToken = function(code) { + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) + { return this.readWord() } + + return this.getTokenFromCode(code) + }; + + pp.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos); + if (code <= 0xd7ff || code >= 0xdc00) { return code } + var next = this.input.charCodeAt(this.pos + 1); + return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 + }; + + pp.skipBlockComment = function() { + var startLoc = this.options.onComment && this.curPosition(); + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } + this.pos = end + 2; + if (this.options.locations) { + for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) { + ++this.curLine; + pos = this.lineStart = nextBreak; + } + } + if (this.options.onComment) + { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, + startLoc, this.curPosition()); } + }; + + pp.skipLineComment = function(startSkip) { + var start = this.pos; + var startLoc = this.options.onComment && this.curPosition(); + var ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine(ch)) { + ch = this.input.charCodeAt(++this.pos); + } + if (this.options.onComment) + { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, + startLoc, this.curPosition()); } + }; + + // Called at the start of the parse and after every token. Skips + // whitespace and comments, and. + + pp.skipSpace = function() { + loop: while (this.pos < this.input.length) { + var ch = this.input.charCodeAt(this.pos); + switch (ch) { + case 32: case 160: // ' ' + ++this.pos; + break + case 13: + if (this.input.charCodeAt(this.pos + 1) === 10) { + ++this.pos; + } + case 10: case 8232: case 8233: + ++this.pos; + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + break + case 47: // '/' + switch (this.input.charCodeAt(this.pos + 1)) { + case 42: // '*' + this.skipBlockComment(); + break + case 47: + this.skipLineComment(2); + break + default: + break loop + } + break + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this.pos; + } else { + break loop + } + } + } + }; + + // Called at the end of every token. Sets `end`, `val`, and + // maintains `context` and `exprAllowed`, and skips the space after + // the token, so that the next one's `start` will point at the + // right position. + + pp.finishToken = function(type, val) { + this.end = this.pos; + if (this.options.locations) { this.endLoc = this.curPosition(); } + var prevType = this.type; + this.type = type; + this.value = val; + + this.updateContext(prevType); + }; + + // ### Token reading + + // This is the function that is called to fetch the next token. It + // is somewhat obscure, because it works in character codes rather + // than characters, and because operator parsing has been inlined + // into it. + // + // All in the name of speed. + // + pp.readToken_dot = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next >= 48 && next <= 57) { return this.readNumber(true) } + var next2 = this.input.charCodeAt(this.pos + 2); + if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' + this.pos += 3; + return this.finishToken(types$1.ellipsis) + } else { + ++this.pos; + return this.finishToken(types$1.dot) + } + }; + + pp.readToken_slash = function() { // '/' + var next = this.input.charCodeAt(this.pos + 1); + if (this.exprAllowed) { ++this.pos; return this.readRegexp() } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.slash, 1) + }; + + pp.readToken_mult_modulo_exp = function(code) { // '%*' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + var tokentype = code === 42 ? types$1.star : types$1.modulo; + + // exponentiation operator ** and **= + if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { + ++size; + tokentype = types$1.starstar; + next = this.input.charCodeAt(this.pos + 2); + } + + if (next === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(tokentype, size) + }; + + pp.readToken_pipe_amp = function(code) { // '|&' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (this.options.ecmaVersion >= 12) { + var next2 = this.input.charCodeAt(this.pos + 2); + if (next2 === 61) { return this.finishOp(types$1.assign, 3) } + } + return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1) + }; + + pp.readToken_caret = function() { // '^' + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.bitwiseXOR, 1) + }; + + pp.readToken_plus_min = function(code) { // '+-' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && + (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { + // A `-->` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types$1.incDec, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.plusMin, 1) + }; + + pp.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(types$1.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // `` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types$1.incDec, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.plusMin, 1) +}; + +pp.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(types$1.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // ` ${serverHost} (server)\n` + + ` (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)\n` + + 'Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .'); + }); + socket.addEventListener('open', () => { + console.info('[vite] Direct websocket connection fallback. Check out https://vitejs.dev/config/server-options.html#server-hmr to remove the previous connection error.'); + }, { once: true }); + }; + } + socket = setupWebSocket(socketProtocol, socketHost, fallback); +} +catch (error) { + console.error(`[vite] failed to connect to websocket (${error}). `); +} +function setupWebSocket(protocol, hostAndPath, onCloseWithoutOpen) { + const socket = new WebSocket(`${protocol}://${hostAndPath}`, 'vite-hmr'); + let isOpened = false; + socket.addEventListener('open', () => { + isOpened = true; + notifyListeners('vite:ws:connect', { webSocket: socket }); + }, { once: true }); + // Listen for messages + socket.addEventListener('message', async ({ data }) => { + handleMessage(JSON.parse(data)); + }); + // ping server + socket.addEventListener('close', async ({ wasClean }) => { + if (wasClean) + return; + if (!isOpened && onCloseWithoutOpen) { + onCloseWithoutOpen(); + return; + } + notifyListeners('vite:ws:disconnect', { webSocket: socket }); + console.log(`[vite] server connection lost. polling for restart...`); + await waitForSuccessfulPing(protocol, hostAndPath); + location.reload(); + }); + return socket; +} +function cleanUrl(pathname) { + const url = new URL(pathname, location.toString()); + url.searchParams.delete('direct'); + return url.pathname + url.search; +} +let isFirstUpdate = true; +const outdatedLinkTags = new WeakSet(); +const debounceReload = (time) => { + let timer; + return () => { + if (timer) { + clearTimeout(timer); + timer = null; + } + timer = setTimeout(() => { + location.reload(); + }, time); + }; +}; +const pageReload = debounceReload(50); +const hmrClient = new HMRClient(console, async function importUpdatedModule({ acceptedPath, timestamp, explicitImportRequired, }) { + const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`); + return await import( + /* @vite-ignore */ + base + + acceptedPathWithoutQuery.slice(1) + + `?${explicitImportRequired ? 'import&' : ''}t=${timestamp}${query ? `&${query}` : ''}`); +}); +async function handleMessage(payload) { + switch (payload.type) { + case 'connected': + console.debug(`[vite] connected.`); + sendMessageBuffer(); + // proxy(nginx, docker) hmr ws maybe caused timeout, + // so send ping package let ws keep alive. + setInterval(() => { + if (socket.readyState === socket.OPEN) { + socket.send('{"type":"ping"}'); + } + }, __HMR_TIMEOUT__); + break; + case 'update': + notifyListeners('vite:beforeUpdate', payload); + // if this is the first update and there's already an error overlay, it + // means the page opened with existing server compile error and the whole + // module script failed to load (since one of the nested imports is 500). + // in this case a normal update won't work and a full reload is needed. + if (isFirstUpdate && hasErrorOverlay()) { + window.location.reload(); + return; + } + else { + clearErrorOverlay(); + isFirstUpdate = false; + } + await Promise.all(payload.updates.map(async (update) => { + if (update.type === 'js-update') { + return queueUpdate(hmrClient.fetchUpdate(update)); + } + // css-update + // this is only sent when a css file referenced with is updated + const { path, timestamp } = update; + const searchUrl = cleanUrl(path); + // can't use querySelector with `[href*=]` here since the link may be + // using relative paths so we need to use link.href to grab the full + // URL for the include check. + const el = Array.from(document.querySelectorAll('link')).find((e) => !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl)); + if (!el) { + return; + } + const newPath = `${base}${searchUrl.slice(1)}${searchUrl.includes('?') ? '&' : '?'}t=${timestamp}`; + // rather than swapping the href on the existing tag, we will + // create a new link tag. Once the new stylesheet has loaded we + // will remove the existing link tag. This removes a Flash Of + // Unstyled Content that can occur when swapping out the tag href + // directly, as the new stylesheet has not yet been loaded. + return new Promise((resolve) => { + const newLinkTag = el.cloneNode(); + newLinkTag.href = new URL(newPath, el.href).href; + const removeOldEl = () => { + el.remove(); + console.debug(`[vite] css hot updated: ${searchUrl}`); + resolve(); + }; + newLinkTag.addEventListener('load', removeOldEl); + newLinkTag.addEventListener('error', removeOldEl); + outdatedLinkTags.add(el); + el.after(newLinkTag); + }); + })); + notifyListeners('vite:afterUpdate', payload); + break; + case 'custom': { + notifyListeners(payload.event, payload.data); + break; + } + case 'full-reload': + notifyListeners('vite:beforeFullReload', payload); + if (payload.path && payload.path.endsWith('.html')) { + // if html file is edited, only reload the page if the browser is + // currently on that page. + const pagePath = decodeURI(location.pathname); + const payloadPath = base + payload.path.slice(1); + if (pagePath === payloadPath || + payload.path === '/index.html' || + (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)) { + pageReload(); + } + return; + } + else { + pageReload(); + } + break; + case 'prune': + notifyListeners('vite:beforePrune', payload); + hmrClient.prunePaths(payload.paths); + break; + case 'error': { + notifyListeners('vite:error', payload); + const err = payload.err; + if (enableOverlay) { + createErrorOverlay(err); + } + else { + console.error(`[vite] Internal Server Error\n${err.message}\n${err.stack}`); + } + break; + } + default: { + const check = payload; + return check; + } + } +} +function notifyListeners(event, data) { + hmrClient.notifyListeners(event, data); +} +const enableOverlay = __HMR_ENABLE_OVERLAY__; +function createErrorOverlay(err) { + clearErrorOverlay(); + document.body.appendChild(new ErrorOverlay(err)); +} +function clearErrorOverlay() { + document.querySelectorAll(overlayId).forEach((n) => n.close()); +} +function hasErrorOverlay() { + return document.querySelectorAll(overlayId).length; +} +let pending = false; +let queued = []; +/** + * buffer multiple hot updates triggered by the same src change + * so that they are invoked in the same order they were sent. + * (otherwise the order may be inconsistent because of the http request round trip) + */ +async function queueUpdate(p) { + queued.push(p); + if (!pending) { + pending = true; + await Promise.resolve(); + pending = false; + const loading = [...queued]; + queued = []; + (await Promise.all(loading)).forEach((fn) => fn && fn()); + } +} +async function waitForSuccessfulPing(socketProtocol, hostAndPath, ms = 1000) { + const pingHostProtocol = socketProtocol === 'wss' ? 'https' : 'http'; + const ping = async () => { + // A fetch on a websocket URL will return a successful promise with status 400, + // but will reject a networking error. + // When running on middleware mode, it returns status 426, and an cors error happens if mode is not no-cors + try { + await fetch(`${pingHostProtocol}://${hostAndPath}`, { + mode: 'no-cors', + headers: { + // Custom headers won't be included in a request with no-cors so (ab)use one of the + // safelisted headers to identify the ping request + Accept: 'text/x-vite-ping', + }, + }); + return true; + } + catch { } + return false; + }; + if (await ping()) { + return; + } + await wait(ms); + // eslint-disable-next-line no-constant-condition + while (true) { + if (document.visibilityState === 'visible') { + if (await ping()) { + break; + } + await wait(ms); + } + else { + await waitForWindowShow(); + } + } +} +function wait(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} +function waitForWindowShow() { + return new Promise((resolve) => { + const onChange = async () => { + if (document.visibilityState === 'visible') { + resolve(); + document.removeEventListener('visibilitychange', onChange); + } + }; + document.addEventListener('visibilitychange', onChange); + }); +} +const sheetsMap = new Map(); +// collect existing style elements that may have been inserted during SSR +// to avoid FOUC or duplicate styles +if ('document' in globalThis) { + document + .querySelectorAll('style[data-vite-dev-id]') + .forEach((el) => { + sheetsMap.set(el.getAttribute('data-vite-dev-id'), el); + }); +} +// all css imports should be inserted at the same position +// because after build it will be a single css file +let lastInsertedStyle; +function updateStyle(id, content) { + let style = sheetsMap.get(id); + if (!style) { + style = document.createElement('style'); + style.setAttribute('type', 'text/css'); + style.setAttribute('data-vite-dev-id', id); + style.textContent = content; + if (!lastInsertedStyle) { + document.head.appendChild(style); + // reset lastInsertedStyle after async + // because dynamically imported css will be splitted into a different file + setTimeout(() => { + lastInsertedStyle = undefined; + }, 0); + } + else { + lastInsertedStyle.insertAdjacentElement('afterend', style); + } + lastInsertedStyle = style; + } + else { + style.textContent = content; + } + sheetsMap.set(id, style); +} +function removeStyle(id) { + const style = sheetsMap.get(id); + if (style) { + document.head.removeChild(style); + sheetsMap.delete(id); + } +} +function sendMessageBuffer() { + if (socket.readyState === 1) { + messageBuffer.forEach((msg) => socket.send(msg)); + messageBuffer.length = 0; + } +} +function createHotContext(ownerPath) { + return new HMRContext(ownerPath, hmrClient, { + addBuffer(message) { + messageBuffer.push(message); + }, + send() { + sendMessageBuffer(); + }, + }); +} +/** + * urls here are dynamic import() urls that couldn't be statically analyzed + */ +function injectQuery(url, queryToInject) { + // skip urls that won't be handled by vite + if (url[0] !== '.' && url[0] !== '/') { + return url; + } + // can't use pathname from URL since it may be relative like ../ + const pathname = url.replace(/[?#].*$/s, ''); + const { search, hash } = new URL(url, 'http://vitejs.dev'); + return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash || ''}`; +} + +export { ErrorOverlay, createHotContext, injectQuery, removeStyle, updateStyle }; +//# sourceMappingURL=client.mjs.map diff --git a/node_modules/vite/dist/client/client.mjs.map b/node_modules/vite/dist/client/client.mjs.map new file mode 100644 index 0000000..6734019 --- /dev/null +++ b/node_modules/vite/dist/client/client.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"client.mjs","sources":["hmr.ts","overlay.ts","client.ts"],"sourcesContent":["import type { Update } from 'types/hmrPayload'\nimport type { ModuleNamespace, ViteHotContext } from 'types/hot'\nimport type { InferCustomEventPayload } from 'types/customEvent'\n\ntype CustomListenersMap = Map void)[]>\n\ninterface HotModule {\n id: string\n callbacks: HotCallback[]\n}\n\ninterface HotCallback {\n // the dependencies must be fetchable paths\n deps: string[]\n fn: (modules: Array) => void\n}\n\ninterface Connection {\n addBuffer(message: string): void\n send(): unknown\n}\n\nexport class HMRContext implements ViteHotContext {\n private newListeners: CustomListenersMap\n\n constructor(\n private ownerPath: string,\n private hmrClient: HMRClient,\n private connection: Connection,\n ) {\n if (!hmrClient.dataMap.has(ownerPath)) {\n hmrClient.dataMap.set(ownerPath, {})\n }\n\n // when a file is hot updated, a new context is created\n // clear its stale callbacks\n const mod = hmrClient.hotModulesMap.get(ownerPath)\n if (mod) {\n mod.callbacks = []\n }\n\n // clear stale custom event listeners\n const staleListeners = hmrClient.ctxToListenersMap.get(ownerPath)\n if (staleListeners) {\n for (const [event, staleFns] of staleListeners) {\n const listeners = hmrClient.customListenersMap.get(event)\n if (listeners) {\n hmrClient.customListenersMap.set(\n event,\n listeners.filter((l) => !staleFns.includes(l)),\n )\n }\n }\n }\n\n this.newListeners = new Map()\n hmrClient.ctxToListenersMap.set(ownerPath, this.newListeners)\n }\n\n get data(): any {\n return this.hmrClient.dataMap.get(this.ownerPath)\n }\n\n accept(deps?: any, callback?: any): void {\n if (typeof deps === 'function' || !deps) {\n // self-accept: hot.accept(() => {})\n this.acceptDeps([this.ownerPath], ([mod]) => deps?.(mod))\n } else if (typeof deps === 'string') {\n // explicit deps\n this.acceptDeps([deps], ([mod]) => callback?.(mod))\n } else if (Array.isArray(deps)) {\n this.acceptDeps(deps, callback)\n } else {\n throw new Error(`invalid hot.accept() usage.`)\n }\n }\n\n // export names (first arg) are irrelevant on the client side, they're\n // extracted in the server for propagation\n acceptExports(\n _: string | readonly string[],\n callback: (data: any) => void,\n ): void {\n this.acceptDeps([this.ownerPath], ([mod]) => callback?.(mod))\n }\n\n dispose(cb: (data: any) => void): void {\n this.hmrClient.disposeMap.set(this.ownerPath, cb)\n }\n\n prune(cb: (data: any) => void): void {\n this.hmrClient.pruneMap.set(this.ownerPath, cb)\n }\n\n // Kept for backward compatibility (#11036)\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n decline(): void {}\n\n invalidate(message: string): void {\n this.hmrClient.notifyListeners('vite:invalidate', {\n path: this.ownerPath,\n message,\n })\n this.send('vite:invalidate', { path: this.ownerPath, message })\n this.hmrClient.logger.debug(\n `[vite] invalidate ${this.ownerPath}${message ? `: ${message}` : ''}`,\n )\n }\n\n on(\n event: T,\n cb: (payload: InferCustomEventPayload) => void,\n ): void {\n const addToMap = (map: Map) => {\n const existing = map.get(event) || []\n existing.push(cb)\n map.set(event, existing)\n }\n addToMap(this.hmrClient.customListenersMap)\n addToMap(this.newListeners)\n }\n\n off(\n event: T,\n cb: (payload: InferCustomEventPayload) => void,\n ): void {\n const removeFromMap = (map: Map) => {\n const existing = map.get(event)\n if (existing === undefined) {\n return\n }\n const pruned = existing.filter((l) => l !== cb)\n if (pruned.length === 0) {\n map.delete(event)\n return\n }\n map.set(event, pruned)\n }\n removeFromMap(this.hmrClient.customListenersMap)\n removeFromMap(this.newListeners)\n }\n\n send(event: T, data?: InferCustomEventPayload): void {\n this.connection.addBuffer(JSON.stringify({ type: 'custom', event, data }))\n this.connection.send()\n }\n\n private acceptDeps(\n deps: string[],\n callback: HotCallback['fn'] = () => {},\n ): void {\n const mod: HotModule = this.hmrClient.hotModulesMap.get(this.ownerPath) || {\n id: this.ownerPath,\n callbacks: [],\n }\n mod.callbacks.push({\n deps,\n fn: callback,\n })\n this.hmrClient.hotModulesMap.set(this.ownerPath, mod)\n }\n}\n\nexport class HMRClient {\n public hotModulesMap = new Map()\n public disposeMap = new Map void | Promise>()\n public pruneMap = new Map void | Promise>()\n public dataMap = new Map()\n public customListenersMap: CustomListenersMap = new Map()\n public ctxToListenersMap = new Map()\n\n constructor(\n public logger: Console,\n // this allows up to implement reloading via different methods depending on the environment\n private importUpdatedModule: (update: Update) => Promise,\n ) {}\n\n public async notifyListeners(\n event: T,\n data: InferCustomEventPayload,\n ): Promise\n public async notifyListeners(event: string, data: any): Promise {\n const cbs = this.customListenersMap.get(event)\n if (cbs) {\n await Promise.allSettled(cbs.map((cb) => cb(data)))\n }\n }\n\n // After an HMR update, some modules are no longer imported on the page\n // but they may have left behind side effects that need to be cleaned up\n // (.e.g style injections)\n // TODO Trigger their dispose callbacks.\n public prunePaths(paths: string[]): void {\n paths.forEach((path) => {\n const fn = this.pruneMap.get(path)\n if (fn) {\n fn(this.dataMap.get(path))\n }\n })\n }\n\n protected warnFailedUpdate(err: Error, path: string | string[]): void {\n if (!err.message.includes('fetch')) {\n this.logger.error(err)\n }\n this.logger.error(\n `[hmr] Failed to reload ${path}. ` +\n `This could be due to syntax errors or importing non-existent ` +\n `modules. (see errors above)`,\n )\n }\n\n public async fetchUpdate(update: Update): Promise<(() => void) | undefined> {\n const { path, acceptedPath } = update\n const mod = this.hotModulesMap.get(path)\n if (!mod) {\n // In a code-splitting project,\n // it is common that the hot-updating module is not loaded yet.\n // https://github.com/vitejs/vite/issues/721\n return\n }\n\n let fetchedModule: ModuleNamespace | undefined\n const isSelfUpdate = path === acceptedPath\n\n // determine the qualified callbacks before we re-import the modules\n const qualifiedCallbacks = mod.callbacks.filter(({ deps }) =>\n deps.includes(acceptedPath),\n )\n\n if (isSelfUpdate || qualifiedCallbacks.length > 0) {\n const disposer = this.disposeMap.get(acceptedPath)\n if (disposer) await disposer(this.dataMap.get(acceptedPath))\n try {\n fetchedModule = await this.importUpdatedModule(update)\n } catch (e) {\n this.warnFailedUpdate(e, acceptedPath)\n }\n }\n\n return () => {\n for (const { deps, fn } of qualifiedCallbacks) {\n fn(\n deps.map((dep) => (dep === acceptedPath ? fetchedModule : undefined)),\n )\n }\n const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`\n this.logger.debug(`[vite] hot updated: ${loggedPath}`)\n }\n }\n}\n","import type { ErrorPayload } from 'types/hmrPayload'\n\n// injected by the hmr plugin when served\ndeclare const __BASE__: string\ndeclare const __HMR_CONFIG_NAME__: string\n\nconst hmrConfigName = __HMR_CONFIG_NAME__\nconst base = __BASE__ || '/'\n\n// set :host styles to make playwright detect the element as visible\nconst template = /*html*/ `\n\n
\n
\n
\n
\n    
\n    
\n    
\n Click outside, press Esc key, or fix the code to dismiss.
\n You can also disable this overlay by setting\n server.hmr.overlay to false in ${hmrConfigName}.\n
\n
\n
\n`\n\nconst fileRE = /(?:[a-zA-Z]:\\\\|\\/).*?:\\d+:\\d+/g\nconst codeframeRE = /^(?:>?\\s*\\d+\\s+\\|.*|\\s+\\|\\s*\\^.*)\\r?\\n/gm\n\n// Allow `ErrorOverlay` to extend `HTMLElement` even in environments where\n// `HTMLElement` was not originally defined.\nconst { HTMLElement = class {} as typeof globalThis.HTMLElement } = globalThis\nexport class ErrorOverlay extends HTMLElement {\n root: ShadowRoot\n closeOnEsc: (e: KeyboardEvent) => void\n\n constructor(err: ErrorPayload['err'], links = true) {\n super()\n this.root = this.attachShadow({ mode: 'open' })\n this.root.innerHTML = template\n\n codeframeRE.lastIndex = 0\n const hasFrame = err.frame && codeframeRE.test(err.frame)\n const message = hasFrame\n ? err.message.replace(codeframeRE, '')\n : err.message\n if (err.plugin) {\n this.text('.plugin', `[plugin:${err.plugin}] `)\n }\n this.text('.message-body', message.trim())\n\n const [file] = (err.loc?.file || err.id || 'unknown file').split(`?`)\n if (err.loc) {\n this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, links)\n } else if (err.id) {\n this.text('.file', file)\n }\n\n if (hasFrame) {\n this.text('.frame', err.frame!.trim())\n }\n this.text('.stack', err.stack, links)\n\n this.root.querySelector('.window')!.addEventListener('click', (e) => {\n e.stopPropagation()\n })\n\n this.addEventListener('click', () => {\n this.close()\n })\n\n this.closeOnEsc = (e: KeyboardEvent) => {\n if (e.key === 'Escape' || e.code === 'Escape') {\n this.close()\n }\n }\n\n document.addEventListener('keydown', this.closeOnEsc)\n }\n\n text(selector: string, text: string, linkFiles = false): void {\n const el = this.root.querySelector(selector)!\n if (!linkFiles) {\n el.textContent = text\n } else {\n let curIndex = 0\n let match: RegExpExecArray | null\n fileRE.lastIndex = 0\n while ((match = fileRE.exec(text))) {\n const { 0: file, index } = match\n if (index != null) {\n const frag = text.slice(curIndex, index)\n el.appendChild(document.createTextNode(frag))\n const link = document.createElement('a')\n link.textContent = file\n link.className = 'file-link'\n link.onclick = () => {\n fetch(\n new URL(\n `${base}__open-in-editor?file=${encodeURIComponent(file)}`,\n import.meta.url,\n ),\n )\n }\n el.appendChild(link)\n curIndex += frag.length + file.length\n }\n }\n }\n }\n close(): void {\n this.parentNode?.removeChild(this)\n document.removeEventListener('keydown', this.closeOnEsc)\n }\n}\n\nexport const overlayId = 'vite-error-overlay'\nconst { customElements } = globalThis // Ensure `customElements` is defined before the next line.\nif (customElements && !customElements.get(overlayId)) {\n customElements.define(overlayId, ErrorOverlay)\n}\n","import type { ErrorPayload, HMRPayload } from 'types/hmrPayload'\nimport type { ViteHotContext } from 'types/hot'\nimport type { InferCustomEventPayload } from 'types/customEvent'\nimport { HMRClient, HMRContext } from '../shared/hmr'\nimport { ErrorOverlay, overlayId } from './overlay'\nimport '@vite/env'\n\n// injected by the hmr plugin when served\ndeclare const __BASE__: string\ndeclare const __SERVER_HOST__: string\ndeclare const __HMR_PROTOCOL__: string | null\ndeclare const __HMR_HOSTNAME__: string | null\ndeclare const __HMR_PORT__: number | null\ndeclare const __HMR_DIRECT_TARGET__: string\ndeclare const __HMR_BASE__: string\ndeclare const __HMR_TIMEOUT__: number\ndeclare const __HMR_ENABLE_OVERLAY__: boolean\n\nconsole.debug('[vite] connecting...')\n\nconst importMetaUrl = new URL(import.meta.url)\n\n// use server configuration, then fallback to inference\nconst serverHost = __SERVER_HOST__\nconst socketProtocol =\n __HMR_PROTOCOL__ || (importMetaUrl.protocol === 'https:' ? 'wss' : 'ws')\nconst hmrPort = __HMR_PORT__\nconst socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${\n hmrPort || importMetaUrl.port\n}${__HMR_BASE__}`\nconst directSocketHost = __HMR_DIRECT_TARGET__\nconst base = __BASE__ || '/'\nconst messageBuffer: string[] = []\n\nlet socket: WebSocket\ntry {\n let fallback: (() => void) | undefined\n // only use fallback when port is inferred to prevent confusion\n if (!hmrPort) {\n fallback = () => {\n // fallback to connecting directly to the hmr server\n // for servers which does not support proxying websocket\n socket = setupWebSocket(socketProtocol, directSocketHost, () => {\n const currentScriptHostURL = new URL(import.meta.url)\n const currentScriptHost =\n currentScriptHostURL.host +\n currentScriptHostURL.pathname.replace(/@vite\\/client$/, '')\n console.error(\n '[vite] failed to connect to websocket.\\n' +\n 'your current setup:\\n' +\n ` (browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)\\n` +\n ` (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)\\n` +\n 'Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .',\n )\n })\n socket.addEventListener(\n 'open',\n () => {\n console.info(\n '[vite] Direct websocket connection fallback. Check out https://vitejs.dev/config/server-options.html#server-hmr to remove the previous connection error.',\n )\n },\n { once: true },\n )\n }\n }\n\n socket = setupWebSocket(socketProtocol, socketHost, fallback)\n} catch (error) {\n console.error(`[vite] failed to connect to websocket (${error}). `)\n}\n\nfunction setupWebSocket(\n protocol: string,\n hostAndPath: string,\n onCloseWithoutOpen?: () => void,\n) {\n const socket = new WebSocket(`${protocol}://${hostAndPath}`, 'vite-hmr')\n let isOpened = false\n\n socket.addEventListener(\n 'open',\n () => {\n isOpened = true\n notifyListeners('vite:ws:connect', { webSocket: socket })\n },\n { once: true },\n )\n\n // Listen for messages\n socket.addEventListener('message', async ({ data }) => {\n handleMessage(JSON.parse(data))\n })\n\n // ping server\n socket.addEventListener('close', async ({ wasClean }) => {\n if (wasClean) return\n\n if (!isOpened && onCloseWithoutOpen) {\n onCloseWithoutOpen()\n return\n }\n\n notifyListeners('vite:ws:disconnect', { webSocket: socket })\n\n console.log(`[vite] server connection lost. polling for restart...`)\n await waitForSuccessfulPing(protocol, hostAndPath)\n location.reload()\n })\n\n return socket\n}\n\nfunction cleanUrl(pathname: string): string {\n const url = new URL(pathname, location.toString())\n url.searchParams.delete('direct')\n return url.pathname + url.search\n}\n\nlet isFirstUpdate = true\nconst outdatedLinkTags = new WeakSet()\n\nconst debounceReload = (time: number) => {\n let timer: ReturnType | null\n return () => {\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n timer = setTimeout(() => {\n location.reload()\n }, time)\n }\n}\nconst pageReload = debounceReload(50)\n\nconst hmrClient = new HMRClient(console, async function importUpdatedModule({\n acceptedPath,\n timestamp,\n explicitImportRequired,\n}) {\n const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`)\n return await import(\n /* @vite-ignore */\n base +\n acceptedPathWithoutQuery.slice(1) +\n `?${explicitImportRequired ? 'import&' : ''}t=${timestamp}${\n query ? `&${query}` : ''\n }`\n )\n})\n\nasync function handleMessage(payload: HMRPayload) {\n switch (payload.type) {\n case 'connected':\n console.debug(`[vite] connected.`)\n sendMessageBuffer()\n // proxy(nginx, docker) hmr ws maybe caused timeout,\n // so send ping package let ws keep alive.\n setInterval(() => {\n if (socket.readyState === socket.OPEN) {\n socket.send('{\"type\":\"ping\"}')\n }\n }, __HMR_TIMEOUT__)\n break\n case 'update':\n notifyListeners('vite:beforeUpdate', payload)\n // if this is the first update and there's already an error overlay, it\n // means the page opened with existing server compile error and the whole\n // module script failed to load (since one of the nested imports is 500).\n // in this case a normal update won't work and a full reload is needed.\n if (isFirstUpdate && hasErrorOverlay()) {\n window.location.reload()\n return\n } else {\n clearErrorOverlay()\n isFirstUpdate = false\n }\n await Promise.all(\n payload.updates.map(async (update): Promise => {\n if (update.type === 'js-update') {\n return queueUpdate(hmrClient.fetchUpdate(update))\n }\n\n // css-update\n // this is only sent when a css file referenced with is updated\n const { path, timestamp } = update\n const searchUrl = cleanUrl(path)\n // can't use querySelector with `[href*=]` here since the link may be\n // using relative paths so we need to use link.href to grab the full\n // URL for the include check.\n const el = Array.from(\n document.querySelectorAll('link'),\n ).find(\n (e) =>\n !outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl),\n )\n\n if (!el) {\n return\n }\n\n const newPath = `${base}${searchUrl.slice(1)}${\n searchUrl.includes('?') ? '&' : '?'\n }t=${timestamp}`\n\n // rather than swapping the href on the existing tag, we will\n // create a new link tag. Once the new stylesheet has loaded we\n // will remove the existing link tag. This removes a Flash Of\n // Unstyled Content that can occur when swapping out the tag href\n // directly, as the new stylesheet has not yet been loaded.\n return new Promise((resolve) => {\n const newLinkTag = el.cloneNode() as HTMLLinkElement\n newLinkTag.href = new URL(newPath, el.href).href\n const removeOldEl = () => {\n el.remove()\n console.debug(`[vite] css hot updated: ${searchUrl}`)\n resolve()\n }\n newLinkTag.addEventListener('load', removeOldEl)\n newLinkTag.addEventListener('error', removeOldEl)\n outdatedLinkTags.add(el)\n el.after(newLinkTag)\n })\n }),\n )\n notifyListeners('vite:afterUpdate', payload)\n break\n case 'custom': {\n notifyListeners(payload.event, payload.data)\n break\n }\n case 'full-reload':\n notifyListeners('vite:beforeFullReload', payload)\n if (payload.path && payload.path.endsWith('.html')) {\n // if html file is edited, only reload the page if the browser is\n // currently on that page.\n const pagePath = decodeURI(location.pathname)\n const payloadPath = base + payload.path.slice(1)\n if (\n pagePath === payloadPath ||\n payload.path === '/index.html' ||\n (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)\n ) {\n pageReload()\n }\n return\n } else {\n pageReload()\n }\n break\n case 'prune':\n notifyListeners('vite:beforePrune', payload)\n hmrClient.prunePaths(payload.paths)\n break\n case 'error': {\n notifyListeners('vite:error', payload)\n const err = payload.err\n if (enableOverlay) {\n createErrorOverlay(err)\n } else {\n console.error(\n `[vite] Internal Server Error\\n${err.message}\\n${err.stack}`,\n )\n }\n break\n }\n default: {\n const check: never = payload\n return check\n }\n }\n}\n\nfunction notifyListeners(\n event: T,\n data: InferCustomEventPayload,\n): void\nfunction notifyListeners(event: string, data: any): void {\n hmrClient.notifyListeners(event, data)\n}\n\nconst enableOverlay = __HMR_ENABLE_OVERLAY__\n\nfunction createErrorOverlay(err: ErrorPayload['err']) {\n clearErrorOverlay()\n document.body.appendChild(new ErrorOverlay(err))\n}\n\nfunction clearErrorOverlay() {\n document.querySelectorAll(overlayId).forEach((n) => n.close())\n}\n\nfunction hasErrorOverlay() {\n return document.querySelectorAll(overlayId).length\n}\n\nlet pending = false\nlet queued: Promise<(() => void) | undefined>[] = []\n\n/**\n * buffer multiple hot updates triggered by the same src change\n * so that they are invoked in the same order they were sent.\n * (otherwise the order may be inconsistent because of the http request round trip)\n */\nasync function queueUpdate(p: Promise<(() => void) | undefined>) {\n queued.push(p)\n if (!pending) {\n pending = true\n await Promise.resolve()\n pending = false\n const loading = [...queued]\n queued = []\n ;(await Promise.all(loading)).forEach((fn) => fn && fn())\n }\n}\n\nasync function waitForSuccessfulPing(\n socketProtocol: string,\n hostAndPath: string,\n ms = 1000,\n) {\n const pingHostProtocol = socketProtocol === 'wss' ? 'https' : 'http'\n\n const ping = async () => {\n // A fetch on a websocket URL will return a successful promise with status 400,\n // but will reject a networking error.\n // When running on middleware mode, it returns status 426, and an cors error happens if mode is not no-cors\n try {\n await fetch(`${pingHostProtocol}://${hostAndPath}`, {\n mode: 'no-cors',\n headers: {\n // Custom headers won't be included in a request with no-cors so (ab)use one of the\n // safelisted headers to identify the ping request\n Accept: 'text/x-vite-ping',\n },\n })\n return true\n } catch {}\n return false\n }\n\n if (await ping()) {\n return\n }\n await wait(ms)\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (document.visibilityState === 'visible') {\n if (await ping()) {\n break\n }\n await wait(ms)\n } else {\n await waitForWindowShow()\n }\n }\n}\n\nfunction wait(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction waitForWindowShow() {\n return new Promise((resolve) => {\n const onChange = async () => {\n if (document.visibilityState === 'visible') {\n resolve()\n document.removeEventListener('visibilitychange', onChange)\n }\n }\n document.addEventListener('visibilitychange', onChange)\n })\n}\n\nconst sheetsMap = new Map()\n\n// collect existing style elements that may have been inserted during SSR\n// to avoid FOUC or duplicate styles\nif ('document' in globalThis) {\n document\n .querySelectorAll('style[data-vite-dev-id]')\n .forEach((el) => {\n sheetsMap.set(el.getAttribute('data-vite-dev-id')!, el)\n })\n}\n\n// all css imports should be inserted at the same position\n// because after build it will be a single css file\nlet lastInsertedStyle: HTMLStyleElement | undefined\n\nexport function updateStyle(id: string, content: string): void {\n let style = sheetsMap.get(id)\n if (!style) {\n style = document.createElement('style')\n style.setAttribute('type', 'text/css')\n style.setAttribute('data-vite-dev-id', id)\n style.textContent = content\n\n if (!lastInsertedStyle) {\n document.head.appendChild(style)\n\n // reset lastInsertedStyle after async\n // because dynamically imported css will be splitted into a different file\n setTimeout(() => {\n lastInsertedStyle = undefined\n }, 0)\n } else {\n lastInsertedStyle.insertAdjacentElement('afterend', style)\n }\n lastInsertedStyle = style\n } else {\n style.textContent = content\n }\n sheetsMap.set(id, style)\n}\n\nexport function removeStyle(id: string): void {\n const style = sheetsMap.get(id)\n if (style) {\n document.head.removeChild(style)\n sheetsMap.delete(id)\n }\n}\n\nfunction sendMessageBuffer() {\n if (socket.readyState === 1) {\n messageBuffer.forEach((msg) => socket.send(msg))\n messageBuffer.length = 0\n }\n}\n\nexport function createHotContext(ownerPath: string): ViteHotContext {\n return new HMRContext(ownerPath, hmrClient, {\n addBuffer(message) {\n messageBuffer.push(message)\n },\n send() {\n sendMessageBuffer()\n },\n })\n}\n\n/**\n * urls here are dynamic import() urls that couldn't be statically analyzed\n */\nexport function injectQuery(url: string, queryToInject: string): string {\n // skip urls that won't be handled by vite\n if (url[0] !== '.' && url[0] !== '/') {\n return url\n }\n\n // can't use pathname from URL since it may be relative like ../\n const pathname = url.replace(/[?#].*$/s, '')\n const { search, hash } = new URL(url, 'http://vitejs.dev')\n\n return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${\n hash || ''\n }`\n}\n\nexport { ErrorOverlay }\n"],"names":["base"],"mappings":";;MAsBa,UAAU,CAAA;AAGrB,IAAA,WAAA,CACU,SAAiB,EACjB,SAAoB,EACpB,UAAsB,EAAA;QAFtB,IAAS,CAAA,SAAA,GAAT,SAAS,CAAQ;QACjB,IAAS,CAAA,SAAA,GAAT,SAAS,CAAW;QACpB,IAAU,CAAA,UAAA,GAAV,UAAU,CAAY;QAE9B,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;YACrC,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,EAAE,CAAC,CAAA;AACrC,SAAA;;;QAID,MAAM,GAAG,GAAG,SAAS,CAAC,aAAa,CAAC,GAAG,CAAC,SAAS,CAAC,CAAA;AAClD,QAAA,IAAI,GAAG,EAAE;AACP,YAAA,GAAG,CAAC,SAAS,GAAG,EAAE,CAAA;AACnB,SAAA;;QAGD,MAAM,cAAc,GAAG,SAAS,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G,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE;AACpC,QAAA,OAAO,GAAG,CAAA;AACX,KAAA;;IAGD,MAAM,QAAQ,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAA;AAC5C,IAAA,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,mBAAmB,CAAC,CAAA;IAE1D,OAAO,CAAA,EAAG,QAAQ,CAAA,CAAA,EAAI,aAAa,CAAA,EAAG,MAAM,GAAG,CAAG,CAAA,CAAA,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,EAAE,CAAA,EACvE,IAAI,IAAI,EACV,CAAA,CAAE,CAAA;AACJ;;;;","x_google_ignoreList":[0,1,2]} \ No newline at end of file diff --git a/node_modules/vite/dist/client/env.mjs b/node_modules/vite/dist/client/env.mjs new file mode 100644 index 0000000..1b3a7d2 --- /dev/null +++ b/node_modules/vite/dist/client/env.mjs @@ -0,0 +1,30 @@ +const context = (() => { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof window !== 'undefined') { + return window; + } + else { + return Function('return this')(); + } +})(); +// assign defines +const defines = __DEFINES__; +Object.keys(defines).forEach((key) => { + const segments = key.split('.'); + let target = context; + for (let i = 0; i < segments.length; i++) { + const segment = segments[i]; + if (i === segments.length - 1) { + target[segment] = defines[key]; + } + else { + target = target[segment] || (target[segment] = {}); + } + } +}); +//# sourceMappingURL=env.mjs.map diff --git a/node_modules/vite/dist/client/env.mjs.map b/node_modules/vite/dist/client/env.mjs.map new file mode 100644 index 0000000..95e027d --- /dev/null +++ b/node_modules/vite/dist/client/env.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"env.mjs","sources":["env.ts"],"sourcesContent":["declare const __MODE__: string\ndeclare const __DEFINES__: Record\n\nconst context = (() => {\n if (typeof globalThis !== 'undefined') {\n return globalThis\n } else if (typeof self !== 'undefined') {\n return self\n } else if (typeof window !== 'undefined') {\n return window\n } else {\n return Function('return this')()\n }\n})()\n\n// assign defines\nconst defines = __DEFINES__\nObject.keys(defines).forEach((key) => {\n const segments = key.split('.')\n let target = context\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]\n if (i === segments.length - 1) {\n target[segment] = defines[key]\n } else {\n target = target[segment] || (target[segment] = {})\n }\n }\n})\n"],"names":[],"mappings":"AAGA,MAAM,OAAO,GAAG,CAAC,MAAK;AACpB,IAAA,IAAI,OAAO,UAAU,KAAK,WAAW,EAAE;AACrC,QAAA,OAAO,UAAU,CAAA;AAClB,KAAA;AAAM,SAAA,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;AACtC,QAAA,OAAO,IAAI,CAAA;AACZ,KAAA;AAAM,SAAA,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;AACxC,QAAA,OAAO,MAAM,CAAA;AACd,KAAA;AAAM,SAAA;AACL,QAAA,OAAO,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAA;AACjC,KAAA;AACH,CAAC,GAAG,CAAA;AAEJ;AACA,MAAM,OAAO,GAAG,WAAW,CAAA;AAC3B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,KAAI;IACnC,MAAM,QAAQ,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC/B,IAAI,MAAM,GAAG,OAAO,CAAA;AACpB,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACxC,QAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;AAC3B,QAAA,IAAI,CAAC,KAAK,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;YAC7B,MAAM,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAA;AAC/B,SAAA;AAAM,aAAA;AACL,YAAA,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;AACnD,SAAA;AACF,KAAA;AACH,CAAC,CAAC","x_google_ignoreList":[0]} \ No newline at end of file diff --git a/node_modules/vite/dist/node-cjs/publicUtils.cjs b/node_modules/vite/dist/node-cjs/publicUtils.cjs new file mode 100644 index 0000000..7409543 --- /dev/null +++ b/node_modules/vite/dist/node-cjs/publicUtils.cjs @@ -0,0 +1,6085 @@ +'use strict'; + +var path$3 = require('node:path'); +var node_url = require('node:url'); +var fs$1 = require('node:fs'); +var esbuild = require('esbuild'); +var rollup = require('rollup'); +var os$1 = require('node:os'); +var node_module = require('node:module'); +var require$$0 = require('tty'); +var require$$1 = require('util'); +var require$$0$1 = require('path'); +var require$$0$2 = require('crypto'); +var fs$2 = require('fs'); +var readline = require('node:readline'); +var require$$2 = require('os'); + +var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null; +const { version: version$2 } = JSON.parse(fs$1.readFileSync(new URL('../../package.json', (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))).toString()); +const VERSION = version$2; +/** + * Prefix for resolved fs paths, since windows paths may not be valid as URLs. + */ +const FS_PREFIX = `/@fs/`; +const VITE_PACKAGE_DIR = path$3.resolve( +// import.meta.url is `dist/node/constants.js` after bundle +node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))), '../../..'); +const CLIENT_ENTRY = path$3.resolve(VITE_PACKAGE_DIR, 'dist/client/client.mjs'); +path$3.resolve(VITE_PACKAGE_DIR, 'dist/client/env.mjs'); +path$3.dirname(CLIENT_ENTRY); + +const comma = ','.charCodeAt(0); +const semicolon = ';'.charCodeAt(0); +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +// Provide a fallback for older environments. +const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; +function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); +} +function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; +} + +// Matches the scheme of a URL, eg "http://" +var UrlType; +(function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; +})(UrlType || (UrlType = {})); + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var picocolors = {exports: {}}; + +let tty = require$$0; + +let isColorSupported = + !("NO_COLOR" in process.env || process.argv.includes("--no-color")) && + ("FORCE_COLOR" in process.env || + process.argv.includes("--color") || + process.platform === "win32" || + (tty.isatty(1) && process.env.TERM !== "dumb") || + "CI" in process.env); + +let formatter = + (open, close, replace = open) => + input => { + let string = "" + input; + let index = string.indexOf(close, open.length); + return ~index + ? open + replaceClose(string, close, replace, index) + close + : open + string + close + }; + +let replaceClose = (string, close, replace, index) => { + let start = string.substring(0, index) + replace; + let end = string.substring(index + close.length); + let nextIndex = end.indexOf(close); + return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end +}; + +let createColors = (enabled = isColorSupported) => ({ + isColorSupported: enabled, + reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String, + bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String, + dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String, + italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String, + underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String, + inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String, + hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String, + strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String, + black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String, + red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String, + green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String, + yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String, + blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String, + magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String, + cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String, + white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String, + gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String, + bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String, + bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String, + bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String, + bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String, + bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String, + bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String, + bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String, + bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String, +}); + +picocolors.exports = createColors(); +picocolors.exports.createColors = createColors; + +var picocolorsExports = picocolors.exports; +var colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports); + +var src = {exports: {}}; + +var node = {exports: {}}; + +/** + * Helpers. + */ + +var ms; +var hasRequiredMs; + +function requireMs () { + if (hasRequiredMs) return ms; + hasRequiredMs = 1; + var s = 1000; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + + /** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + + ms = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); + }; + + /** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + + function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } + } + + /** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; + } + + /** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; + } + + /** + * Pluralization helper. + */ + + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); + } + return ms; +} + +var common; +var hasRequiredCommon; + +function requireCommon () { + if (hasRequiredCommon) return common; + hasRequiredCommon = 1; + /** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = requireMs(); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; + } + + common = setup; + return common; +} + +/** + * Module dependencies. + */ + +var hasRequiredNode; + +function requireNode () { + if (hasRequiredNode) return node.exports; + hasRequiredNode = 1; + (function (module, exports) { + const tty = require$$0; + const util = require$$1; + + /** + * This is the Node.js implementation of `debug()`. + */ + + exports.init = init; + exports.log = log; + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' + ); + + /** + * Colors. + */ + + exports.colors = [6, 2, 3, 4, 5, 1]; + + try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = require('supports-color'); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. + } + + /** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + + exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; + }, {}); + + /** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + + function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); + } + + /** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + + function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } + } + + function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; + } + + /** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + + function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); + } + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + + function load() { + return process.env.DEBUG; + } + + /** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + + function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } + } + + module.exports = requireCommon()(exports); + + const {formatters} = module.exports; + + /** + * Map %o to `util.inspect()`, all on a single line. + */ + + formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); + }; + + /** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + + formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); + }; + } (node, node.exports)); + return node.exports; +} + +var browser$1 = {exports: {}}; + +/* eslint-env browser */ + +var hasRequiredBrowser; + +function requireBrowser () { + if (hasRequiredBrowser) return browser$1.exports; + hasRequiredBrowser = 1; + (function (module, exports) { + /** + * This is the web browser implementation of `debug()`. + */ + + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; + })(); + + /** + * Colors. + */ + + exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' + ]; + + /** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + + // eslint-disable-next-line complexity + function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); + } + + /** + * Colorize log arguments if enabled. + * + * @api public + */ + + function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); + } + + /** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ + exports.log = console.debug || console.log || (() => {}); + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; + } + + /** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + + function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + module.exports = requireCommon()(exports); + + const {formatters} = module.exports; + + /** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + + formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } + }; + } (browser$1, browser$1.exports)); + return browser$1.exports; +} + +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + src.exports = requireBrowser(); +} else { + src.exports = requireNode(); +} + +var srcExports = src.exports; +var debug$2 = /*@__PURE__*/getDefaultExportFromCjs(srcExports); + +var utils$3 = {}; + +const path$2 = require$$0$1; +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; + +/** + * Posix glob regex + */ + +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR = `${QMARK}*?`; + +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR +}; + +/** + * Windows glob regex + */ + +const WINDOWS_CHARS = { + ...POSIX_CHARS, + + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` +}; + +/** + * POSIX Bracket Regex + */ + +const POSIX_REGEX_SOURCE$1 = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; + +var constants$2 = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, + + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, + + // Digits + CHAR_0: 48, /* 0 */ + CHAR_9: 57, /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 65, /* A */ + CHAR_LOWERCASE_A: 97, /* a */ + CHAR_UPPERCASE_Z: 90, /* Z */ + CHAR_LOWERCASE_Z: 122, /* z */ + + CHAR_LEFT_PARENTHESES: 40, /* ( */ + CHAR_RIGHT_PARENTHESES: 41, /* ) */ + + CHAR_ASTERISK: 42, /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, /* & */ + CHAR_AT: 64, /* @ */ + CHAR_BACKWARD_SLASH: 92, /* \ */ + CHAR_CARRIAGE_RETURN: 13, /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ + CHAR_COLON: 58, /* : */ + CHAR_COMMA: 44, /* , */ + CHAR_DOT: 46, /* . */ + CHAR_DOUBLE_QUOTE: 34, /* " */ + CHAR_EQUAL: 61, /* = */ + CHAR_EXCLAMATION_MARK: 33, /* ! */ + CHAR_FORM_FEED: 12, /* \f */ + CHAR_FORWARD_SLASH: 47, /* / */ + CHAR_GRAVE_ACCENT: 96, /* ` */ + CHAR_HASH: 35, /* # */ + CHAR_HYPHEN_MINUS: 45, /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ + CHAR_LEFT_CURLY_BRACE: 123, /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ + CHAR_LINE_FEED: 10, /* \n */ + CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ + CHAR_PERCENT: 37, /* % */ + CHAR_PLUS: 43, /* + */ + CHAR_QUESTION_MARK: 63, /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ + CHAR_SEMICOLON: 59, /* ; */ + CHAR_SINGLE_QUOTE: 39, /* ' */ + CHAR_SPACE: 32, /* */ + CHAR_TAB: 9, /* \t */ + CHAR_UNDERSCORE: 95, /* _ */ + CHAR_VERTICAL_LINE: 124, /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ + + SEP: path$2.sep, + + /** + * Create EXTGLOB_CHARS + */ + + extglobChars(chars) { + return { + '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, + '?': { type: 'qmark', open: '(?:', close: ')?' }, + '+': { type: 'plus', open: '(?:', close: ')+' }, + '*': { type: 'star', open: '(?:', close: ')*' }, + '@': { type: 'at', open: '(?:', close: ')' } + }; + }, + + /** + * Create GLOB_CHARS + */ + + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } +}; + +(function (exports) { + + const path = require$$0$1; + const win32 = process.platform === 'win32'; + const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL + } = constants$2; + + exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); + exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); + exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); + exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); + exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + + exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); + }; + + exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split('.').map(Number); + if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { + return true; + } + return false; + }; + + exports.isWindows = options => { + if (options && typeof options.windows === 'boolean') { + return options.windows; + } + return win32 === true || path.sep === '\\'; + }; + + exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; + }; + + exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + return output; + }; + + exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; + + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; + }; +} (utils$3)); + +const utils$2 = utils$3; +const { + CHAR_ASTERISK, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET /* ] */ +} = constants$2; + +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; + +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } +}; + +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not + * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ + +const scan$1 = (input, options) => { + const opts = options || {}; + + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: '', depth: 0, isGlob: false }; + + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + + while (index < length) { + code = advance(); + let next; + + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + + if (code === CHAR_LEFT_CURLY_BRACE) { + braceEscaped = true; + } + continue; + } + + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) { + braces++; + + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (code === CHAR_LEFT_CURLY_BRACE) { + braces++; + continue; + } + + if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (braceEscaped !== true && code === CHAR_COMMA) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_RIGHT_CURLY_BRACE) { + braces--; + + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { value: '', depth: 0, isGlob: false }; + + if (finished === true) continue; + if (prev === CHAR_DOT && index === (start + 1)) { + start += 2; + continue; + } + + lastIndex = index + 1; + continue; + } + + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS + || code === CHAR_AT + || code === CHAR_ASTERISK + || code === CHAR_QUESTION_MARK + || code === CHAR_EXCLAMATION_MARK; + + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index === start) { + negatedExtglob = true; + } + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } + } + + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_LEFT_SQUARE_BRACKET) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) { + isGlob = token.isGlob = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES) { + finished = true; + break; + } + } + continue; + } + break; + } + + if (isGlob === true) { + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + + let base = str; + let prefix = ''; + let glob = ''; + + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + + if (opts.unescape === true) { + if (glob) glob = utils$2.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils$2.removeBackslashes(base); + } + } + + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; + + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); + } + state.tokens = tokens; + } + + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== '') { + parts.push(value); + } + prevIndex = i; + } + + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + + state.slashes = slashes; + state.parts = parts; + } + + return state; +}; + +var scan_1 = scan$1; + +const constants$1 = constants$2; +const utils$1 = utils$3; + +/** + * Constants + */ + +const { + MAX_LENGTH, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants$1; + +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.join('-')}]`; + + return value; +}; + +/** + * Create the message for a syntax error + */ + +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; + +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + +const parse$2 = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + input = REPLACEMENTS[input] || input; + + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + const bos = { type: 'bos', value: '', output: opts.prepend || '' }; + const tokens = [bos]; + + const capture = opts.capture ? '' : '?:'; + const win32 = utils$1.isWindows(options); + + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants$1.globChars(win32); + const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS); + + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + + const globstar = opts => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + // minimatch options support + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } + + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + + input = utils$1.removePrefix(input, state); + len = input.length; + + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index] || ''; + const remaining = () => input.slice(state.index + 1); + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; + } + + if (count % 2 === 0) { + return false; + } + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } + } + + if (extglobs.length && tok.type !== 'paren') { + extglobs[extglobs.length - 1].inner += tok.value; + } + + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + prev.output = (prev.output || '') + tok.value; + return; + } + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; + + increment('parens'); + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + let rest; + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { + // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. + // In this case, we need to parse the string and use it in the output of the original pattern. + // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. + // + // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. + const expression = parse$2(rest, { ...options, fastpaths: false }).output; + + output = token.close = `)${expression})${extglobStar})`; + } + + if (token.prev.type === 'bos') { + state.negatedExtglob = true; + } + } + + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; + + /** + * Fast paths + */ + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); + } + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); + } + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); + } + return star; + } + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); + }); + } + } + + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + + state.output = utils$1.wrapOutput(output, state, options); + return state; + } + + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; + } + + /** + * Escaped characters + */ + + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } + + // collapse slashes to reduce potential for exploits + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; + } + } + + if (opts.unescape === true) { + value = advance(); + } else { + value += advance(); + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } + } + + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } + } + } + + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ value }); + continue; + } + + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + if (state.quotes === 1 && value !== '"') { + value = utils$1.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } + + /** + * Double quotes + */ + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; + } + + /** + * Parentheses + */ + + if (value === '(') { + increment('parens'); + push({ type: 'paren', value }); + continue; + } + + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } + + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } + + /** + * Square brackets + */ + + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); + } + + value = `\\${value}`; + } else { + increment('brackets'); + } + + push({ type: 'bracket', value }); + continue; + } + + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); + } + + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + decrement('brackets'); + + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + + prev.value += value; + append({ value }); + + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils$1.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + + /** + * Braces + */ + + if (value === '{' && opts.nobrace !== true) { + increment('braces'); + + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + + braces.push(open); + push(open); + continue; + } + + if (value === '}') { + const brace = braces[braces.length - 1]; + + if (opts.nobrace === true || !brace) { + push({ type: 'text', value, output: value }); + continue; + } + + let output = ')'; + + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; + } + + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = '\\}'; + state.output = out; + for (const t of toks) { + state.output += (t.output || t.value); + } + } + + push({ type: 'brace', value, output }); + decrement('braces'); + braces.pop(); + continue; + } + + /** + * Pipes + */ + + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({ type: 'text', value }); + continue; + } + + /** + * Commas + */ + + if (value === ',') { + let output = value; + + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } + + push({ type: 'comma', value, output }); + continue; + } + + /** + * Slashes + */ + + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } + + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; + } + + /** + * Dots + */ + + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + + if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ type: 'text', value, output: DOT_LITERAL }); + continue; + } + + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; + } + + /** + * Question marks + */ + + if (value === '?') { + const isGroup = prev && prev.value === '('; + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } + + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; + + if (next === '<' && !utils$1.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } + + if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { + output = `\\${value}`; + } + + push({ type: 'text', value, output }); + continue; + } + + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; + } + + push({ type: 'qmark', value, output: QMARK }); + continue; + } + + /** + * Exclamation + */ + + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } + + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + + /** + * Plus + */ + + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } + + if ((prev && prev.value === '(') || opts.regex === false) { + push({ type: 'plus', value, output: PLUS_LITERAL }); + continue; + } + + if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { + push({ type: 'plus', value }); + continue; + } + + push({ type: 'plus', value: PLUS_LITERAL }); + continue; + } + + /** + * Plain text + */ + + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', extglob: true, value, output: '' }); + continue; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Plain text + */ + + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } + + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Stars + */ + + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } + + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + + if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { + push({ type: 'star', value, output: '' }); + continue; + } + + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); + continue; + } + + // strip consecutive `/**/` + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + if (after && after !== '/') { + break; + } + rest = rest.slice(3); + consume('/**', 3); + } + + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; + + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + + state.output += prior.output + prev.output; + state.globstar = true; + + consume(value + advance()); + + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); + + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; + + // reset output with globstar + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + + const token = { type: 'star', value, output: star }; + + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } + + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + + } else { + state.output += nodot; + prev.output += nodot; + } + + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + + push(token); + } + + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils$1.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils$1.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils$1.escapeLast(state.output, '{'); + decrement('braces'); + } + + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } + + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; + + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + + if (token.suffix) { + state.output += token.suffix; + } + } + } + + return state; +}; + +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + +parse$2.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + input = REPLACEMENTS[input] || input; + const win32 = utils$1.isWindows(options); + + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants$1.globChars(win32); + + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { negated: false, prefix: '' }; + let star = opts.bash === true ? '.*?' : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + const globstar = opts => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; + + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + + case '**': + return nodot + globstar(opts); + + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + + const source = create(match[1]); + if (!source) return; + + return source + DOT_LITERAL + match[2]; + } + } + }; + + const output = utils$1.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +var parse_1$1 = parse$2; + +const path$1 = require$$0$1; +const scan = scan_1; +const parse$1 = parse_1$1; +const utils = utils$3; +const constants = constants$2; +const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val); + +/** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ + +const picomatch$1 = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch$1(input, options, returnState)); + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } + + const isState = isObject$2(glob) && glob.tokens && glob.input; + + if (glob === '' || (typeof glob !== 'string' && !isState)) { + throw new TypeError('Expected pattern to be a non-empty string'); + } + + const opts = options || {}; + const posix = utils.isWindows(options); + const regex = isState + ? picomatch$1.compileRe(glob, options) + : picomatch$1.makeRe(glob, options, false, true); + + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch$1.test(input, regex, options, { glob, posix }); + const result = { glob, state, regex, posix, input, output, match, isMatch }; + + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } + + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; +}; + +/** + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public + */ + +picomatch$1.test = (input, regex, options, { glob, posix } = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); + } + + if (input === '') { + return { isMatch: false, output: '' }; + } + + const opts = options || {}; + const format = opts.format || (posix ? utils.toPosixSlashes : null); + let match = input === glob; + let output = (match && format) ? format(input) : input; + + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch$1.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } + } + + return { isMatch: Boolean(match), match, output }; +}; + +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + +picomatch$1.matchBase = (input, glob, options, posix = utils.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options); + return regex.test(path$1.basename(input)); +}; + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ + +picomatch$1.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options)); + return parse$1(pattern, { ...options, fastpaths: false }); +}; + +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +picomatch$1.scan = (input, options) => scan(input, options); + +/** + * Compile a regular expression from the `state` object returned by the + * [parse()](#parse) method. + * + * @param {Object} `state` + * @param {Object} `options` + * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. + * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. + * @return {RegExp} + * @api public + */ + +picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return state.output; + } + + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; + + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) { + source = `^(?!${source}).*$`; + } + + const regex = picomatch$1.toRegex(source, options); + if (returnState === true) { + regex.state = state; + } + + return regex; +}; + +/** + * Create a regular expression from a parsed glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. + * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } + + let parsed = { negated: false, fastpaths: true }; + + if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + parsed.output = parse$1.fastpaths(input, options); + } + + if (!parsed.output) { + parsed = parse$1(input, options); + } + + return picomatch$1.compileRe(parsed, options, returnOutput, returnState); +}; + +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +picomatch$1.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; + +/** + * Picomatch constants. + * @return {Object} + */ + +picomatch$1.constants = constants; + +/** + * Expose "picomatch" + */ + +var picomatch_1 = picomatch$1; + +var picomatch = picomatch_1; + +var pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch); + +// Helper since Typescript can't detect readonly arrays with Array.isArray +function isArray(arg) { + return Array.isArray(arg); +} +function ensureArray(thing) { + if (isArray(thing)) + return thing; + if (thing == null) + return []; + return [thing]; +} + +const normalizePath$1 = function normalizePath(filename) { + return filename.split(require$$0$1.win32.sep).join(require$$0$1.posix.sep); +}; + +function getMatcherString(id, resolutionBase) { + if (resolutionBase === false || require$$0$1.isAbsolute(id) || id.startsWith('**')) { + return normalizePath$1(id); + } + // resolve('') is valid and will default to process.cwd() + const basePath = normalizePath$1(require$$0$1.resolve(resolutionBase || '')) + // escape all possible (posix + win) path characters that might interfere with regex + .replace(/[-^$*+?.()|[\]{}]/g, '\\$&'); + // Note that we use posix.join because: + // 1. the basePath has been normalized to use / + // 2. the incoming glob (id) matcher, also uses / + // otherwise Node will force backslash (\) on windows + return require$$0$1.posix.join(basePath, normalizePath$1(id)); +} +const createFilter$1 = function createFilter(include, exclude, options) { + const resolutionBase = options && options.resolve; + const getMatcher = (id) => id instanceof RegExp + ? id + : { + test: (what) => { + // this refactor is a tad overly verbose but makes for easy debugging + const pattern = getMatcherString(id, resolutionBase); + const fn = pm(pattern, { dot: true }); + const result = fn(what); + return result; + } + }; + const includeMatchers = ensureArray(include).map(getMatcher); + const excludeMatchers = ensureArray(exclude).map(getMatcher); + return function result(id) { + if (typeof id !== 'string') + return false; + if (/\0/.test(id)) + return false; + const pathId = normalizePath$1(id); + for (let i = 0; i < excludeMatchers.length; ++i) { + const matcher = excludeMatchers[i]; + if (matcher.test(pathId)) + return false; + } + for (let i = 0; i < includeMatchers.length; ++i) { + const matcher = includeMatchers[i]; + if (matcher.test(pathId)) + return true; + } + return !includeMatchers.length; + }; +}; + +const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'; +const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'; +const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' ')); +forbiddenIdentifiers.add(''); + +if (process.versions.pnp) { + try { + node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))('pnpapi'); + } + catch { } +} + +const createFilter = createFilter$1; +const windowsSlashRE = /\\/g; +function slash(p) { + return p.replace(windowsSlashRE, '/'); +} +// Some runtimes like Bun injects namespaced modules here, which is not a node builtin +node_module.builtinModules.filter((id) => !id.includes(':')); +function isInNodeModules(id) { + return id.includes('node_modules'); +} +// TODO: use import() +node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))); +// set in bin/vite.js +const filter = process.env.VITE_DEBUG_FILTER; +const DEBUG = process.env.DEBUG; +function createDebugger(namespace, options = {}) { + const log = debug$2(namespace); + const { onlyWhenFocused } = options; + let enabled = log.enabled; + if (enabled && onlyWhenFocused) { + const ns = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace; + enabled = !!DEBUG?.includes(ns); + } + if (enabled) { + return (...args) => { + if (!filter || args.some((a) => a?.includes?.(filter))) { + log(...args); + } + }; + } +} +function testCaseInsensitiveFS() { + if (!CLIENT_ENTRY.endsWith('client.mjs')) { + throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`); + } + if (!fs$1.existsSync(CLIENT_ENTRY)) { + throw new Error('cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' + + CLIENT_ENTRY); + } + return fs$1.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs')); +} +const isCaseInsensitiveFS = testCaseInsensitiveFS(); +const isWindows = os$1.platform() === 'win32'; +const VOLUME_RE = /^[A-Z]:/i; +function normalizePath(id) { + return path$3.posix.normalize(isWindows ? slash(id) : id); +} +function fsPathFromId(id) { + const fsPath = normalizePath(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id); + return fsPath[0] === '/' || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`; +} +function fsPathFromUrl(url) { + return fsPathFromId(cleanUrl(url)); +} +function withTrailingSlash(path) { + if (path[path.length - 1] !== '/') { + return `${path}/`; + } + return path; +} +/** + * Check if dir is a parent of file + * + * Warning: parameters are not validated, only works with normalized absolute paths + * + * @param dir - normalized absolute path + * @param file - normalized absolute path + * @returns true if dir is a parent of file + */ +function isParentDirectory(dir, file) { + dir = withTrailingSlash(dir); + return (file.startsWith(dir) || + (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase()))); +} +/** + * Check if 2 file name are identical + * + * Warning: parameters are not validated, only works with normalized absolute paths + * + * @param file1 - normalized absolute path + * @param file2 - normalized absolute path + * @returns true if both files url are identical + */ +function isSameFileUri(file1, file2) { + return (file1 === file2 || + (isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase())); +} +const postfixRE = /[?#].*$/s; +function cleanUrl(url) { + return url.replace(postfixRE, ''); +} +const trailingSeparatorRE = /[?&]$/; +const timestampRE = /\bt=\d{13}&?\b/; +function removeTimestampQuery(url) { + return url.replace(timestampRE, '').replace(trailingSeparatorRE, ''); +} +function isObject$1(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} +function tryStatSync(file) { + try { + // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist + return fs$1.statSync(file, { throwIfNoEntry: false }); + } + catch { + // Ignore errors + } +} +function isFileReadable(filename) { + if (!tryStatSync(filename)) { + return false; + } + try { + // Check if current process has read permission to the file + fs$1.accessSync(filename, fs$1.constants.R_OK); + return true; + } + catch { + return false; + } +} +function arraify(target) { + return Array.isArray(target) ? target : [target]; +} +path$3.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))); +function backwardCompatibleWorkerPlugins(plugins) { + if (Array.isArray(plugins)) { + return plugins; + } + if (typeof plugins === 'function') { + return plugins(); + } + return []; +} +function mergeConfigRecursively(defaults, overrides, rootPath) { + const merged = { ...defaults }; + for (const key in overrides) { + const value = overrides[key]; + if (value == null) { + continue; + } + const existing = merged[key]; + if (existing == null) { + merged[key] = value; + continue; + } + // fields that require special handling + if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) { + merged[key] = mergeAlias(existing, value); + continue; + } + else if (key === 'assetsInclude' && rootPath === '') { + merged[key] = [].concat(existing, value); + continue; + } + else if (key === 'noExternal' && + rootPath === 'ssr' && + (existing === true || value === true)) { + merged[key] = true; + continue; + } + else if (key === 'plugins' && rootPath === 'worker') { + merged[key] = () => [ + ...backwardCompatibleWorkerPlugins(existing), + ...backwardCompatibleWorkerPlugins(value), + ]; + continue; + } + if (Array.isArray(existing) || Array.isArray(value)) { + merged[key] = [...arraify(existing ?? []), ...arraify(value ?? [])]; + continue; + } + if (isObject$1(existing) && isObject$1(value)) { + merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key); + continue; + } + merged[key] = value; + } + return merged; +} +function mergeConfig(defaults, overrides, isRoot = true) { + if (typeof defaults === 'function' || typeof overrides === 'function') { + throw new Error(`Cannot merge config in form of callback`); + } + return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.'); +} +function mergeAlias(a, b) { + if (!a) + return b; + if (!b) + return a; + if (isObject$1(a) && isObject$1(b)) { + return { ...a, ...b }; + } + // the order is flipped because the alias is resolved from top-down, + // where the later should have higher priority + return [...normalizeAlias(b), ...normalizeAlias(a)]; +} +function normalizeAlias(o = []) { + return Array.isArray(o) + ? o.map(normalizeSingleAlias) + : Object.keys(o).map((find) => normalizeSingleAlias({ + find, + replacement: o[find], + })); +} +// https://github.com/vitejs/vite/issues/1363 +// work around https://github.com/rollup/plugins/issues/759 +function normalizeSingleAlias({ find, replacement, customResolver, }) { + if (typeof find === 'string' && + find[find.length - 1] === '/' && + replacement[replacement.length - 1] === '/') { + find = find.slice(0, find.length - 1); + replacement = replacement.slice(0, replacement.length - 1); + } + const alias = { + find, + replacement, + }; + if (customResolver) { + alias.customResolver = customResolver; + } + return alias; +} + +// This file will be built for both ESM and CJS. Avoid relying on other modules as possible. +// copy from constants.ts +const CSS_LANGS_RE = +// eslint-disable-next-line regexp/no-unused-capturing-group +/\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/; +const isCSSRequest = (request) => CSS_LANGS_RE.test(request); +// Use splitVendorChunkPlugin() to get the same manualChunks strategy as Vite 2.7 +// We don't recommend using this strategy as a general solution moving forward +// splitVendorChunk is a simple index/vendor strategy that was used in Vite +// until v2.8. It is exposed to let people continue to use it in case it was +// working well for their setups. +// The cache needs to be reset on buildStart for watch mode to work correctly +// Don't use this manualChunks strategy for ssr, lib mode, and 'umd' or 'iife' +class SplitVendorChunkCache { + cache; + constructor() { + this.cache = new Map(); + } + reset() { + this.cache = new Map(); + } +} +function splitVendorChunk(options = {}) { + const cache = options.cache ?? new SplitVendorChunkCache(); + return (id, { getModuleInfo }) => { + if (isInNodeModules(id) && + !isCSSRequest(id) && + staticImportedByEntry(id, getModuleInfo, cache.cache)) { + return 'vendor'; + } + }; +} +function staticImportedByEntry(id, getModuleInfo, cache, importStack = []) { + if (cache.has(id)) { + return cache.get(id); + } + if (importStack.includes(id)) { + // circular deps! + cache.set(id, false); + return false; + } + const mod = getModuleInfo(id); + if (!mod) { + cache.set(id, false); + return false; + } + if (mod.isEntry) { + cache.set(id, true); + return true; + } + const someImporterIs = mod.importers.some((importer) => staticImportedByEntry(importer, getModuleInfo, cache, importStack.concat(id))); + cache.set(id, someImporterIs); + return someImporterIs; +} +function splitVendorChunkPlugin() { + const caches = []; + function createSplitVendorChunk(output, config) { + const cache = new SplitVendorChunkCache(); + caches.push(cache); + const build = config.build ?? {}; + const format = output?.format; + if (!build.ssr && !build.lib && format !== 'umd' && format !== 'iife') { + return splitVendorChunk({ cache }); + } + } + return { + name: 'vite:split-vendor-chunk', + config(config) { + let outputs = config?.build?.rollupOptions?.output; + if (outputs) { + outputs = Array.isArray(outputs) ? outputs : [outputs]; + for (const output of outputs) { + const viteManualChunks = createSplitVendorChunk(output, config); + if (viteManualChunks) { + if (output.manualChunks) { + if (typeof output.manualChunks === 'function') { + const userManualChunks = output.manualChunks; + output.manualChunks = (id, api) => { + return userManualChunks(id, api) ?? viteManualChunks(id, api); + }; + } + else { + // else, leave the object form of manualChunks untouched, as + // we can't safely replicate rollup handling. + // eslint-disable-next-line no-console + console.warn("(!) the `splitVendorChunk` plugin doesn't have any effect when using the object form of `build.rollupOptions.output.manualChunks`. Consider using the function form instead."); + } + } + else { + output.manualChunks = viteManualChunks; + } + } + } + } + else { + return { + build: { + rollupOptions: { + output: { + manualChunks: createSplitVendorChunk({}, config), + }, + }, + }, + }; + } + }, + buildStart() { + caches.forEach((cache) => cache.reset()); + }, + }; +} + +var convertSourceMap$1 = {}; + +(function (exports) { + + Object.defineProperty(exports, 'commentRegex', { + get: function getCommentRegex () { + // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data. + return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg; + } + }); + + + Object.defineProperty(exports, 'mapFileCommentRegex', { + get: function getMapFileCommentRegex () { + // Matches sourceMappingURL in either // or /* comment styles. + return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg; + } + }); + + var decodeBase64; + if (typeof Buffer !== 'undefined') { + if (typeof Buffer.from === 'function') { + decodeBase64 = decodeBase64WithBufferFrom; + } else { + decodeBase64 = decodeBase64WithNewBuffer; + } + } else { + decodeBase64 = decodeBase64WithAtob; + } + + function decodeBase64WithBufferFrom(base64) { + return Buffer.from(base64, 'base64').toString(); + } + + function decodeBase64WithNewBuffer(base64) { + if (typeof value === 'number') { + throw new TypeError('The value to decode must not be of type number.'); + } + return new Buffer(base64, 'base64').toString(); + } + + function decodeBase64WithAtob(base64) { + return decodeURIComponent(escape(atob(base64))); + } + + function stripComment(sm) { + return sm.split(',').pop(); + } + + function readFromFileMap(sm, read) { + var r = exports.mapFileCommentRegex.exec(sm); + // for some odd reason //# .. captures in 1 and /* .. */ in 2 + var filename = r[1] || r[2]; + + try { + var sm = read(filename); + if (sm != null && typeof sm.catch === 'function') { + return sm.catch(throwError); + } else { + return sm; + } + } catch (e) { + throwError(e); + } + + function throwError(e) { + throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack); + } + } + + function Converter (sm, opts) { + opts = opts || {}; + + if (opts.hasComment) { + sm = stripComment(sm); + } + + if (opts.encoding === 'base64') { + sm = decodeBase64(sm); + } else if (opts.encoding === 'uri') { + sm = decodeURIComponent(sm); + } + + if (opts.isJSON || opts.encoding) { + sm = JSON.parse(sm); + } + + this.sourcemap = sm; + } + + Converter.prototype.toJSON = function (space) { + return JSON.stringify(this.sourcemap, null, space); + }; + + if (typeof Buffer !== 'undefined') { + if (typeof Buffer.from === 'function') { + Converter.prototype.toBase64 = encodeBase64WithBufferFrom; + } else { + Converter.prototype.toBase64 = encodeBase64WithNewBuffer; + } + } else { + Converter.prototype.toBase64 = encodeBase64WithBtoa; + } + + function encodeBase64WithBufferFrom() { + var json = this.toJSON(); + return Buffer.from(json, 'utf8').toString('base64'); + } + + function encodeBase64WithNewBuffer() { + var json = this.toJSON(); + if (typeof json === 'number') { + throw new TypeError('The json to encode must not be of type number.'); + } + return new Buffer(json, 'utf8').toString('base64'); + } + + function encodeBase64WithBtoa() { + var json = this.toJSON(); + return btoa(unescape(encodeURIComponent(json))); + } + + Converter.prototype.toURI = function () { + var json = this.toJSON(); + return encodeURIComponent(json); + }; + + Converter.prototype.toComment = function (options) { + var encoding, content, data; + if (options != null && options.encoding === 'uri') { + encoding = ''; + content = this.toURI(); + } else { + encoding = ';base64'; + content = this.toBase64(); + } + data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content; + return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; + }; + + // returns copy instead of original + Converter.prototype.toObject = function () { + return JSON.parse(this.toJSON()); + }; + + Converter.prototype.addProperty = function (key, value) { + if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead'); + return this.setProperty(key, value); + }; + + Converter.prototype.setProperty = function (key, value) { + this.sourcemap[key] = value; + return this; + }; + + Converter.prototype.getProperty = function (key) { + return this.sourcemap[key]; + }; + + exports.fromObject = function (obj) { + return new Converter(obj); + }; + + exports.fromJSON = function (json) { + return new Converter(json, { isJSON: true }); + }; + + exports.fromURI = function (uri) { + return new Converter(uri, { encoding: 'uri' }); + }; + + exports.fromBase64 = function (base64) { + return new Converter(base64, { encoding: 'base64' }); + }; + + exports.fromComment = function (comment) { + var m, encoding; + comment = comment + .replace(/^\/\*/g, '//') + .replace(/\*\/$/g, ''); + m = exports.commentRegex.exec(comment); + encoding = m && m[4] || 'uri'; + return new Converter(comment, { encoding: encoding, hasComment: true }); + }; + + function makeConverter(sm) { + return new Converter(sm, { isJSON: true }); + } + + exports.fromMapFileComment = function (comment, read) { + if (typeof read === 'string') { + throw new Error( + 'String directory paths are no longer supported with `fromMapFileComment`\n' + + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' + ) + } + + var sm = readFromFileMap(comment, read); + if (sm != null && typeof sm.then === 'function') { + return sm.then(makeConverter); + } else { + return makeConverter(sm); + } + }; + + // Finds last sourcemap comment in file or returns null if none was found + exports.fromSource = function (content) { + var m = content.match(exports.commentRegex); + return m ? exports.fromComment(m.pop()) : null; + }; + + // Finds last sourcemap comment in file or returns null if none was found + exports.fromMapFileSource = function (content, read) { + if (typeof read === 'string') { + throw new Error( + 'String directory paths are no longer supported with `fromMapFileSource`\n' + + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' + ) + } + var m = content.match(exports.mapFileCommentRegex); + return m ? exports.fromMapFileComment(m.pop(), read) : null; + }; + + exports.removeComments = function (src) { + return src.replace(exports.commentRegex, ''); + }; + + exports.removeMapFileComments = function (src) { + return src.replace(exports.mapFileCommentRegex, ''); + }; + + exports.generateMapFileComment = function (file, options) { + var data = 'sourceMappingURL=' + file; + return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; + }; +} (convertSourceMap$1)); + +var convertSourceMap = /*@__PURE__*/getDefaultExportFromCjs(convertSourceMap$1); + +/*! + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + * @public + */ + +var etag_1 = etag; + +/** + * Module dependencies. + * @private + */ + +var crypto$1 = require$$0$2; +var Stats = fs$2.Stats; + +/** + * Module variables. + * @private + */ + +var toString$1 = Object.prototype.toString; + +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } + + // compute hash of entity + var hash = crypto$1 + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27); + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length; + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } + + // support fs.Stats object + var isStats = isstats(entity); + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats; + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity); + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + return obj && typeof obj === 'object' && + 'ctime' in obj && toString$1.call(obj.ctime) === '[object Date]' && + 'mtime' in obj && toString$1.call(obj.mtime) === '[object Date]' && + 'ino' in obj && typeof obj.ino === 'number' && + 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16); + var size = stat.size.toString(16); + + return '"' + size + '-' + mtime + '"' +} + +var getEtag = /*@__PURE__*/getDefaultExportFromCjs(etag_1); + +class BitSet { + constructor(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; + } + + add(n) { + this.bits[n >> 5] |= 1 << (n & 31); + } + + has(n) { + return !!(this.bits[n >> 5] & (1 << (n & 31))); + } +} + +class Chunk { + constructor(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + + this.intro = ''; + this.outro = ''; + + this.content = content; + this.storeName = false; + this.edited = false; + + { + this.previous = null; + this.next = null; + } + } + + appendLeft(content) { + this.outro += content; + } + + appendRight(content) { + this.intro = this.intro + content; + } + + clone() { + const chunk = new Chunk(this.start, this.end, this.original); + + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + + return chunk; + } + + contains(index) { + return this.start < index && index < this.end; + } + + eachNext(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } + } + + eachPrevious(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } + } + + edit(content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ''; + this.outro = ''; + } + this.storeName = storeName; + + this.edited = true; + + return this; + } + + prependLeft(content) { + this.outro = content + this.outro; + } + + prependRight(content) { + this.intro = content + this.intro; + } + + split(index) { + const sliceIndex = index - this.start; + + const originalBefore = this.original.slice(0, sliceIndex); + const originalAfter = this.original.slice(sliceIndex); + + this.original = originalBefore; + + const newChunk = new Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ''; + + this.end = index; + + if (this.edited) { + // after split we should save the edit content record into the correct chunk + // to make sure sourcemap correct + // For example: + // ' test'.trim() + // split -> ' ' + 'test' + // ✔️ edit -> '' + 'test' + // ✖️ edit -> 'test' + '' + // TODO is this block necessary?... + newChunk.edit('', false); + this.content = ''; + } else { + this.content = originalBefore; + } + + newChunk.next = this.next; + if (newChunk.next) newChunk.next.previous = newChunk; + newChunk.previous = this; + this.next = newChunk; + + return newChunk; + } + + toString() { + return this.intro + this.content + this.outro; + } + + trimEnd(rx) { + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit('', undefined, true); + if (this.edited) { + // save the change, if it has been edited + this.edit(trimmed, this.storeName, true); + } + } + return true; + } else { + this.edit('', undefined, true); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + } + } + + trimStart(rx) { + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + const newChunk = this.split(this.end - trimmed.length); + if (this.edited) { + // save the change, if it has been edited + newChunk.edit(trimmed, this.storeName, true); + } + this.edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + } + } +} + +function getBtoa() { + if (typeof window !== 'undefined' && typeof window.btoa === 'function') { + return (str) => window.btoa(unescape(encodeURIComponent(str))); + } else if (typeof Buffer === 'function') { + return (str) => Buffer.from(str, 'utf-8').toString('base64'); + } else { + return () => { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); + }; + } +} + +const btoa$1 = /*#__PURE__*/ getBtoa(); + +class SourceMap { + constructor(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = encode(properties.mappings); + if (typeof properties.x_google_ignoreList !== 'undefined') { + this.x_google_ignoreList = properties.x_google_ignoreList; + } + } + + toString() { + return JSON.stringify(this); + } + + toUrl() { + return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString()); + } +} + +function guessIndent(code) { + const lines = code.split('\n'); + + const tabbed = lines.filter((line) => /^\t+/.test(line)); + const spaced = lines.filter((line) => /^ {2,}/.test(line)); + + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + + // More lines tabbed than spaced? Assume tabs, and + // default to tabs in the case of a tie (or nothing + // to go on) + if (tabbed.length >= spaced.length) { + return '\t'; + } + + // Otherwise, we need to guess the multiple + const min = spaced.reduce((previous, current) => { + const numSpaces = /^ +/.exec(current)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + + return new Array(min + 1).join(' '); +} + +function getRelativePath(from, to) { + const fromParts = from.split(/[/\\]/); + const toParts = to.split(/[/\\]/); + + fromParts.pop(); // get dirname + + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + + if (fromParts.length) { + let i = fromParts.length; + while (i--) fromParts[i] = '..'; + } + + return fromParts.concat(toParts).join('/'); +} + +const toString = Object.prototype.toString; + +function isObject(thing) { + return toString.call(thing) === '[object Object]'; +} + +function getLocator(source) { + const originalLines = source.split('\n'); + const lineOffsets = []; + + for (let i = 0, pos = 0; i < originalLines.length; i++) { + lineOffsets.push(pos); + pos += originalLines[i].length + 1; + } + + return function locate(index) { + let i = 0; + let j = lineOffsets.length; + while (i < j) { + const m = (i + j) >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i = m + 1; + } + } + const line = i - 1; + const column = index - lineOffsets[line]; + return { line, column }; + }; +} + +const wordRegex = /\w/; + +class Mappings { + constructor(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; + } + + addEdit(sourceIndex, content, loc, nameIndex) { + if (content.length) { + let contentLineEnd = content.indexOf('\n', 0); + let previousContentLineEnd = -1; + while (contentLineEnd >= 0) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + + previousContentLineEnd = contentLineEnd; + contentLineEnd = content.indexOf('\n', contentLineEnd + 1); + } + + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.advance(content.slice(previousContentLineEnd + 1)); + } else if (this.pending) { + this.rawSegments.push(this.pending); + this.advance(content); + } + + this.pending = null; + } + + addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { + let originalCharIndex = chunk.start; + let first = true; + // when iterating each char, check if it's in a word boundary + let charInHiresBoundary = false; + + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + + if (this.hires === 'boundary') { + // in hires "boundary", group segments per word boundary than per char + if (wordRegex.test(original[originalCharIndex])) { + // for first char in the boundary found, start the boundary by pushing a segment + if (!charInHiresBoundary) { + this.rawSegments.push(segment); + charInHiresBoundary = true; + } + } else { + // for non-word char, end the boundary by pushing a segment + this.rawSegments.push(segment); + charInHiresBoundary = false; + } + } else { + this.rawSegments.push(segment); + } + } + + if (original[originalCharIndex] === '\n') { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + + originalCharIndex += 1; + } + + this.pending = null; + } + + advance(str) { + if (!str) return; + + const lines = str.split('\n'); + + if (lines.length > 1) { + for (let i = 0; i < lines.length - 1; i++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + + this.generatedCodeColumn += lines[lines.length - 1].length; + } +} + +const n = '\n'; + +const warned = { + insertLeft: false, + insertRight: false, + storeName: false, +}; + +class MagicString { + constructor(string, options = {}) { + const chunk = new Chunk(0, string.length, string); + + Object.defineProperties(this, { + original: { writable: true, value: string }, + outro: { writable: true, value: '' }, + intro: { writable: true, value: '' }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: undefined }, + ignoreList: { writable: true, value: options.ignoreList }, + }); + + this.byStart[0] = chunk; + this.byEnd[string.length] = chunk; + } + + addSourcemapLocation(char) { + this.sourcemapLocations.add(char); + } + + append(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.outro += content; + return this; + } + + appendLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; + } + + appendRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; + } + + clone() { + const cloned = new MagicString(this.original, { filename: this.filename }); + + let originalChunk = this.firstChunk; + let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); + + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + + const nextOriginalChunk = originalChunk.next; + const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + + clonedChunk = nextClonedChunk; + } + + originalChunk = nextOriginalChunk; + } + + cloned.lastChunk = clonedChunk; + + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + + cloned.intro = this.intro; + cloned.outro = this.outro; + + return cloned; + } + + generateDecodedMap(options) { + options = options || {}; + + const sourceIndex = 0; + const names = Object.keys(this.storedNames); + const mappings = new Mappings(options.hires); + + const locate = getLocator(this.original); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + + if (chunk.intro.length) mappings.advance(chunk.intro); + + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1, + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); + } + + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : undefined, + sources: [ + options.source ? getRelativePath(options.file || '', options.source) : options.file || '', + ], + sourcesContent: options.includeContent ? [this.original] : undefined, + names, + mappings: mappings.raw, + x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined, + }; + } + + generateMap(options) { + return new SourceMap(this.generateDecodedMap(options)); + } + + _ensureindentStr() { + if (this.indentStr === undefined) { + this.indentStr = guessIndent(this.original); + } + } + + _getRawIndentString() { + this._ensureindentStr(); + return this.indentStr; + } + + getIndentString() { + this._ensureindentStr(); + return this.indentStr === null ? '\t' : this.indentStr; + } + + indent(indentStr, options) { + const pattern = /^[^\r\n]/gm; + + if (isObject(indentStr)) { + options = indentStr; + indentStr = undefined; + } + + if (indentStr === undefined) { + this._ensureindentStr(); + indentStr = this.indentStr || '\t'; + } + + if (indentStr === '') return this; // noop + + options = options || {}; + + // Process exclusion ranges + const isExcluded = {}; + + if (options.exclude) { + const exclusions = + typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; + exclusions.forEach((exclusion) => { + for (let i = exclusion[0]; i < exclusion[1]; i += 1) { + isExcluded[i] = true; + } + }); + } + + let shouldIndentNextCharacter = options.indentStart !== false; + const replacer = (match) => { + if (shouldIndentNextCharacter) return `${indentStr}${match}`; + shouldIndentNextCharacter = true; + return match; + }; + + this.intro = this.intro.replace(pattern, replacer); + + let charIndex = 0; + let chunk = this.firstChunk; + + while (chunk) { + const end = chunk.end; + + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; + } + } + } else { + charIndex = chunk.start; + + while (charIndex < end) { + if (!isExcluded[charIndex]) { + const char = this.original[charIndex]; + + if (char === '\n') { + shouldIndentNextCharacter = true; + } else if (char !== '\r' && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + + charIndex += 1; + } + } + + charIndex = chunk.end; + chunk = chunk.next; + } + + this.outro = this.outro.replace(pattern, replacer); + + return this; + } + + insert() { + throw new Error( + 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)', + ); + } + + insertLeft(index, content) { + if (!warned.insertLeft) { + console.warn( + 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead', + ); // eslint-disable-line no-console + warned.insertLeft = true; + } + + return this.appendLeft(index, content); + } + + insertRight(index, content) { + if (!warned.insertRight) { + console.warn( + 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead', + ); // eslint-disable-line no-console + warned.insertRight = true; + } + + return this.prependRight(index, content); + } + + move(start, end, index) { + if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); + + this._split(start); + this._split(end); + this._split(index); + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + const oldLeft = first.previous; + const oldRight = last.next; + + const newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) return this; + const newLeft = newRight ? newRight.previous : this.lastChunk; + + if (oldLeft) oldLeft.next = oldRight; + if (oldRight) oldRight.previous = oldLeft; + + if (newLeft) newLeft.next = first; + if (newRight) newRight.previous = last; + + if (!first.previous) this.firstChunk = last.next; + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + + first.previous = newLeft; + last.next = newRight || null; + + if (!newLeft) this.firstChunk = first; + if (!newRight) this.lastChunk = last; + return this; + } + + overwrite(start, end, content, options) { + options = options || {}; + return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); + } + + update(start, end, content, options) { + if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); + + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (end > this.original.length) throw new Error('end is out of bounds'); + if (start === end) + throw new Error( + 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead', + ); + + this._split(start); + this._split(end); + + if (options === true) { + if (!warned.storeName) { + console.warn( + 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string', + ); // eslint-disable-line no-console + warned.storeName = true; + } + + options = { storeName: true }; + } + const storeName = options !== undefined ? options.storeName : false; + const overwrite = options !== undefined ? options.overwrite : false; + + if (storeName) { + const original = this.original.slice(start, end); + Object.defineProperty(this.storedNames, original, { + writable: true, + value: true, + enumerable: true, + }); + } + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + if (first) { + let chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error('Cannot overwrite across a split point'); + } + chunk = chunk.next; + chunk.edit('', false); + } + + first.edit(content, storeName, !overwrite); + } else { + // must be inserting at the end + const newChunk = new Chunk(start, end, '').edit(content, storeName); + + // TODO last chunk in the array may not be the last chunk, if it's moved... + last.next = newChunk; + newChunk.previous = last; + } + return this; + } + + prepend(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.intro = content + this.intro; + return this; + } + + prependLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; + } + + prependRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; + } + + remove(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.intro = ''; + chunk.outro = ''; + chunk.edit(''); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + lastChar() { + if (this.outro.length) return this.outro[this.outro.length - 1]; + let chunk = this.lastChunk; + do { + if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; + if (chunk.content.length) return chunk.content[chunk.content.length - 1]; + if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; + } while ((chunk = chunk.previous)); + if (this.intro.length) return this.intro[this.intro.length - 1]; + return ''; + } + + lastLine() { + let lineIndex = this.outro.lastIndexOf(n); + if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); + let lineStr = this.outro; + let chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.outro + lineStr; + } + + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n); + if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; + lineStr = chunk.content + lineStr; + } + + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n); + if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.intro + lineStr; + } + } while ((chunk = chunk.previous)); + lineIndex = this.intro.lastIndexOf(n); + if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; + return this.intro + lineStr; + } + + slice(start = 0, end = this.original.length) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + let result = ''; + + // find start chunk + let chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + // found end chunk before start + if (chunk.start < end && chunk.end >= end) { + return result; + } + + chunk = chunk.next; + } + + if (chunk && chunk.edited && chunk.start !== start) + throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); + + const startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + + const containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); + + const sliceStart = startChunk === chunk ? start - chunk.start : 0; + const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + + result += chunk.content.slice(sliceStart, sliceEnd); + + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + + if (containsEnd) { + break; + } + + chunk = chunk.next; + } + + return result; + } + + // TODO deprecate this? not really very useful + snip(start, end) { + const clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + + return clone; + } + + _split(index) { + if (this.byStart[index] || this.byEnd[index]) return; + + let chunk = this.lastSearchedChunk; + const searchForward = index > chunk.end; + + while (chunk) { + if (chunk.contains(index)) return this._splitChunk(chunk, index); + + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } + } + + _splitChunk(chunk, index) { + if (chunk.edited && chunk.content.length) { + // zero-length edited chunks are a special case (overlapping replacements) + const loc = getLocator(this.original)(index); + throw new Error( + `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`, + ); + } + + const newChunk = chunk.split(index); + + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + + if (chunk === this.lastChunk) this.lastChunk = newChunk; + + this.lastSearchedChunk = chunk; + return true; + } + + toString() { + let str = this.intro; + + let chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + + return str + this.outro; + } + + isEmpty() { + let chunk = this.firstChunk; + do { + if ( + (chunk.intro.length && chunk.intro.trim()) || + (chunk.content.length && chunk.content.trim()) || + (chunk.outro.length && chunk.outro.trim()) + ) + return false; + } while ((chunk = chunk.next)); + return true; + } + + length() { + let chunk = this.firstChunk; + let length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while ((chunk = chunk.next)); + return length; + } + + trimLines() { + return this.trim('[\\r\\n]'); + } + + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + + trimEndAborted(charType) { + const rx = new RegExp((charType || '\\s') + '+$'); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + let chunk = this.lastChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimEnd(rx); + + // if chunk was trimmed, we have a new lastChunk + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.previous; + } while (chunk); + + return false; + } + + trimEnd(charType) { + this.trimEndAborted(charType); + return this; + } + trimStartAborted(charType) { + const rx = new RegExp('^' + (charType || '\\s') + '+'); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + let chunk = this.firstChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimStart(rx); + + if (chunk.end !== end) { + // special case... + if (chunk === this.lastChunk) this.lastChunk = chunk.next; + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.next; + } while (chunk); + + return false; + } + + trimStart(charType) { + this.trimStartAborted(charType); + return this; + } + + hasChanged() { + return this.original !== this.toString(); + } + + _replaceRegexp(searchValue, replacement) { + function getReplacement(match, str) { + if (typeof replacement === 'string') { + return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter + if (i === '$') return '$'; + if (i === '&') return match[0]; + const num = +i; + if (num < match.length) return match[+i]; + return `$${i}`; + }); + } else { + return replacement(...match, match.index, str, match.groups); + } + } + function matchAll(re, str) { + let match; + const matches = []; + while ((match = re.exec(str))) { + matches.push(match); + } + return matches; + } + if (searchValue.global) { + const matches = matchAll(searchValue, this.original); + matches.forEach((match) => { + if (match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + }); + } else { + const match = this.original.match(searchValue); + if (match && match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + } + return this; + } + + _replaceString(string, replacement) { + const { original } = this; + const index = original.indexOf(string); + + if (index !== -1) { + this.overwrite(index, index + string.length, replacement); + } + + return this; + } + + replace(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceString(searchValue, replacement); + } + + return this._replaceRegexp(searchValue, replacement); + } + + _replaceAllString(string, replacement) { + const { original } = this; + const stringLength = string.length; + for ( + let index = original.indexOf(string); + index !== -1; + index = original.indexOf(string, index + stringLength) + ) { + this.overwrite(index, index + stringLength, replacement); + } + + return this; + } + + replaceAll(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceAllString(searchValue, replacement); + } + + if (!searchValue.global) { + throw new TypeError( + 'MagicString.prototype.replaceAll called with a non-global RegExp argument', + ); + } + + return this._replaceRegexp(searchValue, replacement); + } +} + +const debug$1 = createDebugger('vite:sourcemap', { + onlyWhenFocused: true, +}); +function genSourceMapUrl(map) { + if (typeof map !== 'string') { + map = JSON.stringify(map); + } + return `data:application/json;base64,${Buffer.from(map).toString('base64')}`; +} +function getCodeWithSourcemap(type, code, map) { + if (debug$1) { + code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`; + } + if (type === 'js') { + code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`; + } + else if (type === 'css') { + code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`; + } + return code; +} + +const debug = createDebugger('vite:send', { + onlyWhenFocused: true, +}); +const alias = { + js: 'application/javascript', + css: 'text/css', + html: 'text/html', + json: 'application/json', +}; +function send(req, res, content, type, options) { + const { etag = getEtag(content, { weak: true }), cacheControl = 'no-cache', headers, map, } = options; + if (res.writableEnded) { + return; + } + if (req.headers['if-none-match'] === etag) { + res.statusCode = 304; + res.end(); + return; + } + res.setHeader('Content-Type', alias[type] || type); + res.setHeader('Cache-Control', cacheControl); + res.setHeader('Etag', etag); + if (headers) { + for (const name in headers) { + res.setHeader(name, headers[name]); + } + } + // inject source map reference + if (map && 'version' in map && map.mappings) { + if (type === 'js' || type === 'css') { + content = getCodeWithSourcemap(type, content.toString(), map); + } + } + // inject fallback sourcemap for js for improved debugging + // https://github.com/vitejs/vite/pull/13514#issuecomment-1592431496 + else if (type === 'js' && (!map || map.mappings !== '')) { + const code = content.toString(); + // if the code has existing inline sourcemap, assume it's correct and skip + if (convertSourceMap.mapFileCommentRegex.test(code)) { + debug?.(`Skipped injecting fallback sourcemap for ${req.url}`); + } + else { + const urlWithoutTimestamp = removeTimestampQuery(req.url); + const ms = new MagicString(code); + content = getCodeWithSourcemap(type, code, ms.generateMap({ + source: path$3.basename(urlWithoutTimestamp), + hires: 'boundary', + includeContent: true, + })); + } + } + res.statusCode = 200; + res.end(content); + return; +} + +/* eslint no-console: 0 */ +const LogLevels = { + silent: 0, + error: 1, + warn: 2, + info: 3, +}; +let lastType; +let lastMsg; +let sameCount = 0; +function clearScreen() { + const repeatCount = process.stdout.rows - 2; + const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : ''; + console.log(blank); + readline.cursorTo(process.stdout, 0, 0); + readline.clearScreenDown(process.stdout); +} +function createLogger(level = 'info', options = {}) { + if (options.customLogger) { + return options.customLogger; + } + const timeFormatter = new Intl.DateTimeFormat(undefined, { + hour: 'numeric', + minute: 'numeric', + second: 'numeric', + }); + const loggedErrors = new WeakSet(); + const { prefix = '[vite]', allowClearScreen = true } = options; + const thresh = LogLevels[level]; + const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI; + const clear = canClearScreen ? clearScreen : () => { }; + function output(type, msg, options = {}) { + if (thresh >= LogLevels[type]) { + const method = type === 'info' ? 'log' : type; + const format = () => { + if (options.timestamp) { + const tag = type === 'info' + ? colors.cyan(colors.bold(prefix)) + : type === 'warn' + ? colors.yellow(colors.bold(prefix)) + : colors.red(colors.bold(prefix)); + return `${colors.dim(timeFormatter.format(new Date()))} ${tag} ${msg}`; + } + else { + return msg; + } + }; + if (options.error) { + loggedErrors.add(options.error); + } + if (canClearScreen) { + if (type === lastType && msg === lastMsg) { + sameCount++; + clear(); + console[method](format(), colors.yellow(`(x${sameCount + 1})`)); + } + else { + sameCount = 0; + lastMsg = msg; + lastType = type; + if (options.clear) { + clear(); + } + console[method](format()); + } + } + else { + console[method](format()); + } + } + } + const warnedMessages = new Set(); + const logger = { + hasWarned: false, + info(msg, opts) { + output('info', msg, opts); + }, + warn(msg, opts) { + logger.hasWarned = true; + output('warn', msg, opts); + }, + warnOnce(msg, opts) { + if (warnedMessages.has(msg)) + return; + logger.hasWarned = true; + output('warn', msg, opts); + warnedMessages.add(msg); + }, + error(msg, opts) { + logger.hasWarned = true; + output('error', msg, opts); + }, + clearScreen(type) { + if (thresh >= LogLevels[type]) { + clear(); + } + }, + hasErrorLogged(error) { + return loggedErrors.has(error); + }, + }; + return logger; +} + +// https://github.com/vitejs/vite/issues/2820#issuecomment-812495079 +const ROOT_FILES = [ + // '.git', + // https://pnpm.io/workspaces/ + 'pnpm-workspace.yaml', + // https://rushjs.io/pages/advanced/config_files/ + // 'rush.json', + // https://nx.dev/latest/react/getting-started/nx-setup + // 'workspace.json', + // 'nx.json', + // https://github.com/lerna/lerna#lernajson + 'lerna.json', +]; +// npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces +// yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it +function hasWorkspacePackageJSON(root) { + const path = path$3.join(root, 'package.json'); + if (!isFileReadable(path)) { + return false; + } + try { + const content = JSON.parse(fs$1.readFileSync(path, 'utf-8')) || {}; + return !!content.workspaces; + } + catch { + return false; + } +} +function hasRootFile(root) { + return ROOT_FILES.some((file) => fs$1.existsSync(path$3.join(root, file))); +} +function hasPackageJSON(root) { + const path = path$3.join(root, 'package.json'); + return fs$1.existsSync(path); +} +/** + * Search up for the nearest `package.json` + */ +function searchForPackageRoot(current, root = current) { + if (hasPackageJSON(current)) + return current; + const dir = path$3.dirname(current); + // reach the fs root + if (!dir || dir === current) + return root; + return searchForPackageRoot(dir, root); +} +/** + * Search up for the nearest workspace root + */ +function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) { + if (hasRootFile(current)) + return current; + if (hasWorkspacePackageJSON(current)) + return current; + const dir = path$3.dirname(current); + // reach the fs root + if (!dir || dir === current) + return root; + return searchForWorkspaceRoot(dir, root); +} + +/** + * Check if the url is allowed to be served, via the `server.fs` config. + */ +function isFileServingAllowed(url, server) { + if (!server.config.server.fs.strict) + return true; + const file = fsPathFromUrl(url); + if (server._fsDenyGlob(file)) + return false; + if (server.moduleGraph.safeModulesPath.has(file)) + return true; + if (server.config.server.fs.allow.some((uri) => isSameFileUri(uri, file) || isParentDirectory(uri, file))) + return true; + return false; +} + +var main$1 = {exports: {}}; + +var name = "dotenv"; +var version$1 = "16.3.1"; +var description = "Loads environment variables from .env file"; +var main = "lib/main.js"; +var types = "lib/main.d.ts"; +var exports$1 = { + ".": { + types: "./lib/main.d.ts", + require: "./lib/main.js", + "default": "./lib/main.js" + }, + "./config": "./config.js", + "./config.js": "./config.js", + "./lib/env-options": "./lib/env-options.js", + "./lib/env-options.js": "./lib/env-options.js", + "./lib/cli-options": "./lib/cli-options.js", + "./lib/cli-options.js": "./lib/cli-options.js", + "./package.json": "./package.json" +}; +var scripts = { + "dts-check": "tsc --project tests/types/tsconfig.json", + lint: "standard", + "lint-readme": "standard-markdown", + pretest: "npm run lint && npm run dts-check", + test: "tap tests/*.js --100 -Rspec", + prerelease: "npm test", + release: "standard-version" +}; +var repository = { + type: "git", + url: "git://github.com/motdotla/dotenv.git" +}; +var funding = "https://github.com/motdotla/dotenv?sponsor=1"; +var keywords = [ + "dotenv", + "env", + ".env", + "environment", + "variables", + "config", + "settings" +]; +var readmeFilename = "README.md"; +var license = "BSD-2-Clause"; +var devDependencies = { + "@definitelytyped/dtslint": "^0.0.133", + "@types/node": "^18.11.3", + decache: "^4.6.1", + sinon: "^14.0.1", + standard: "^17.0.0", + "standard-markdown": "^7.1.0", + "standard-version": "^9.5.0", + tap: "^16.3.0", + tar: "^6.1.11", + typescript: "^4.8.4" +}; +var engines = { + node: ">=12" +}; +var browser = { + fs: false +}; +var require$$4 = { + name: name, + version: version$1, + description: description, + main: main, + types: types, + exports: exports$1, + scripts: scripts, + repository: repository, + funding: funding, + keywords: keywords, + readmeFilename: readmeFilename, + license: license, + devDependencies: devDependencies, + engines: engines, + browser: browser +}; + +const fs = fs$2; +const path = require$$0$1; +const os = require$$2; +const crypto = require$$0$2; +const packageJson = require$$4; + +const version = packageJson.version; + +const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; + +// Parse src into an Object +function parse (src) { + const obj = {}; + + // Convert buffer to string + let lines = src.toString(); + + // Convert line breaks to same format + lines = lines.replace(/\r\n?/mg, '\n'); + + let match; + while ((match = LINE.exec(lines)) != null) { + const key = match[1]; + + // Default undefined or null to empty string + let value = (match[2] || ''); + + // Remove whitespace + value = value.trim(); + + // Check if double quoted + const maybeQuote = value[0]; + + // Remove surrounding quotes + value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2'); + + // Expand newlines if double quoted + if (maybeQuote === '"') { + value = value.replace(/\\n/g, '\n'); + value = value.replace(/\\r/g, '\r'); + } + + // Add to object + obj[key] = value; + } + + return obj +} + +function _parseVault (options) { + const vaultPath = _vaultPath(options); + + // Parse .env.vault + const result = DotenvModule.configDotenv({ path: vaultPath }); + if (!result.parsed) { + throw new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`) + } + + // handle scenario for comma separated keys - for use with key rotation + // example: DOTENV_KEY="dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenv.org/vault/.env.vault?environment=prod" + const keys = _dotenvKey(options).split(','); + const length = keys.length; + + let decrypted; + for (let i = 0; i < length; i++) { + try { + // Get full key + const key = keys[i].trim(); + + // Get instructions for decrypt + const attrs = _instructions(result, key); + + // Decrypt + decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); + + break + } catch (error) { + // last key + if (i + 1 >= length) { + throw error + } + // try next key + } + } + + // Parse decrypted .env string + return DotenvModule.parse(decrypted) +} + +function _log (message) { + console.log(`[dotenv@${version}][INFO] ${message}`); +} + +function _warn (message) { + console.log(`[dotenv@${version}][WARN] ${message}`); +} + +function _debug (message) { + console.log(`[dotenv@${version}][DEBUG] ${message}`); +} + +function _dotenvKey (options) { + // prioritize developer directly setting options.DOTENV_KEY + if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) { + return options.DOTENV_KEY + } + + // secondary infra already contains a DOTENV_KEY environment variable + if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) { + return process.env.DOTENV_KEY + } + + // fallback to empty string + return '' +} + +function _instructions (result, dotenvKey) { + // Parse DOTENV_KEY. Format is a URI + let uri; + try { + uri = new URL(dotenvKey); + } catch (error) { + if (error.code === 'ERR_INVALID_URL') { + throw new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=development') + } + + throw error + } + + // Get decrypt key + const key = uri.password; + if (!key) { + throw new Error('INVALID_DOTENV_KEY: Missing key part') + } + + // Get environment + const environment = uri.searchParams.get('environment'); + if (!environment) { + throw new Error('INVALID_DOTENV_KEY: Missing environment part') + } + + // Get ciphertext payload + const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`; + const ciphertext = result.parsed[environmentKey]; // DOTENV_VAULT_PRODUCTION + if (!ciphertext) { + throw new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`) + } + + return { ciphertext, key } +} + +function _vaultPath (options) { + let dotenvPath = path.resolve(process.cwd(), '.env'); + + if (options && options.path && options.path.length > 0) { + dotenvPath = options.path; + } + + // Locate .env.vault + return dotenvPath.endsWith('.vault') ? dotenvPath : `${dotenvPath}.vault` +} + +function _resolveHome (envPath) { + return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath +} + +function _configVault (options) { + _log('Loading env from encrypted .env.vault'); + + const parsed = DotenvModule._parseVault(options); + + let processEnv = process.env; + if (options && options.processEnv != null) { + processEnv = options.processEnv; + } + + DotenvModule.populate(processEnv, parsed, options); + + return { parsed } +} + +function configDotenv (options) { + let dotenvPath = path.resolve(process.cwd(), '.env'); + let encoding = 'utf8'; + const debug = Boolean(options && options.debug); + + if (options) { + if (options.path != null) { + dotenvPath = _resolveHome(options.path); + } + if (options.encoding != null) { + encoding = options.encoding; + } + } + + try { + // Specifying an encoding returns a string instead of a buffer + const parsed = DotenvModule.parse(fs.readFileSync(dotenvPath, { encoding })); + + let processEnv = process.env; + if (options && options.processEnv != null) { + processEnv = options.processEnv; + } + + DotenvModule.populate(processEnv, parsed, options); + + return { parsed } + } catch (e) { + if (debug) { + _debug(`Failed to load ${dotenvPath} ${e.message}`); + } + + return { error: e } + } +} + +// Populates process.env from .env file +function config (options) { + const vaultPath = _vaultPath(options); + + // fallback to original dotenv if DOTENV_KEY is not set + if (_dotenvKey(options).length === 0) { + return DotenvModule.configDotenv(options) + } + + // dotenvKey exists but .env.vault file does not exist + if (!fs.existsSync(vaultPath)) { + _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`); + + return DotenvModule.configDotenv(options) + } + + return DotenvModule._configVault(options) +} + +function decrypt (encrypted, keyStr) { + const key = Buffer.from(keyStr.slice(-64), 'hex'); + let ciphertext = Buffer.from(encrypted, 'base64'); + + const nonce = ciphertext.slice(0, 12); + const authTag = ciphertext.slice(-16); + ciphertext = ciphertext.slice(12, -16); + + try { + const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce); + aesgcm.setAuthTag(authTag); + return `${aesgcm.update(ciphertext)}${aesgcm.final()}` + } catch (error) { + const isRange = error instanceof RangeError; + const invalidKeyLength = error.message === 'Invalid key length'; + const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'; + + if (isRange || invalidKeyLength) { + const msg = 'INVALID_DOTENV_KEY: It must be 64 characters long (or more)'; + throw new Error(msg) + } else if (decryptionFailed) { + const msg = 'DECRYPTION_FAILED: Please check your DOTENV_KEY'; + throw new Error(msg) + } else { + console.error('Error: ', error.code); + console.error('Error: ', error.message); + throw error + } + } +} + +// Populate process.env with parsed values +function populate (processEnv, parsed, options = {}) { + const debug = Boolean(options && options.debug); + const override = Boolean(options && options.override); + + if (typeof parsed !== 'object') { + throw new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate') + } + + // Set process.env + for (const key of Object.keys(parsed)) { + if (Object.prototype.hasOwnProperty.call(processEnv, key)) { + if (override === true) { + processEnv[key] = parsed[key]; + } + + if (debug) { + if (override === true) { + _debug(`"${key}" is already defined and WAS overwritten`); + } else { + _debug(`"${key}" is already defined and was NOT overwritten`); + } + } + } else { + processEnv[key] = parsed[key]; + } + } +} + +const DotenvModule = { + configDotenv, + _configVault, + _parseVault, + config, + decrypt, + parse, + populate +}; + +main$1.exports.configDotenv = DotenvModule.configDotenv; +main$1.exports._configVault = DotenvModule._configVault; +main$1.exports._parseVault = DotenvModule._parseVault; +main$1.exports.config = DotenvModule.config; +main$1.exports.decrypt = DotenvModule.decrypt; +var parse_1 = main$1.exports.parse = DotenvModule.parse; +main$1.exports.populate = DotenvModule.populate; + +main$1.exports = DotenvModule; + +// like String.prototype.search but returns the last index +function _searchLast (str, rgx) { + const matches = Array.from(str.matchAll(rgx)); + return matches.length > 0 ? matches.slice(-1)[0].index : -1 +} + +function _interpolate (envValue, environment, config) { + // find the last unescaped dollar sign in the + // value so that we can evaluate it + const lastUnescapedDollarSignIndex = _searchLast(envValue, /(?!(?<=\\))\$/g); + + // If we couldn't match any unescaped dollar sign + // let's return the string as is + if (lastUnescapedDollarSignIndex === -1) return envValue + + // This is the right-most group of variables in the string + const rightMostGroup = envValue.slice(lastUnescapedDollarSignIndex); + + /** + * This finds the inner most variable/group divided + * by variable name and default value (if present) + * ( + * (?!(?<=\\))\$ // only match dollar signs that are not escaped + * {? // optional opening curly brace + * ([\w]+) // match the variable name + * (?::-([^}\\]*))? // match an optional default value + * }? // optional closing curly brace + * ) + */ + const matchGroup = /((?!(?<=\\))\${?([\w]+)(?::-([^}\\]*))?}?)/; + const match = rightMostGroup.match(matchGroup); + + if (match != null) { + const [, group, variableName, defaultValue] = match; + + return _interpolate( + envValue.replace( + group, + environment[variableName] || + defaultValue || + config.parsed[variableName] || + '' + ), + environment, + config + ) + } + + return envValue +} + +function _resolveEscapeSequences (value) { + return value.replace(/\\\$/g, '$') +} + +function expand (config) { + // if ignoring process.env, use a blank object + const environment = config.ignoreProcessEnv ? {} : process.env; + + for (const configKey in config.parsed) { + const value = Object.prototype.hasOwnProperty.call(environment, configKey) + ? environment[configKey] + : config.parsed[configKey]; + + config.parsed[configKey] = _resolveEscapeSequences( + _interpolate(value, environment, config) + ); + } + + // PATCH: don't write to process.env + // for (const processKey in config.parsed) { + // environment[processKey] = config.parsed[processKey] + // } + + return config +} + +var expand_1 = expand; + +function getEnvFilesForMode(mode) { + return [ + /** default file */ `.env`, + /** local file */ `.env.local`, + /** mode file */ `.env.${mode}`, + /** mode local file */ `.env.${mode}.local`, + ]; +} +function loadEnv(mode, envDir, prefixes = 'VITE_') { + if (mode === 'local') { + throw new Error(`"local" cannot be used as a mode name because it conflicts with ` + + `the .local postfix for .env files.`); + } + prefixes = arraify(prefixes); + const env = {}; + const envFiles = getEnvFilesForMode(mode); + const parsed = Object.fromEntries(envFiles.flatMap((file) => { + const filePath = path$3.join(envDir, file); + if (!tryStatSync(filePath)?.isFile()) + return []; + return Object.entries(parse_1(fs$1.readFileSync(filePath))); + })); + // test NODE_ENV override before expand as otherwise process.env.NODE_ENV would override this + if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === undefined) { + process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV; + } + // support BROWSER and BROWSER_ARGS env variables + if (parsed.BROWSER && process.env.BROWSER === undefined) { + process.env.BROWSER = parsed.BROWSER; + } + if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === undefined) { + process.env.BROWSER_ARGS = parsed.BROWSER_ARGS; + } + // let environment variables use each other + // `expand` patched in patches/dotenv-expand@9.0.0.patch + expand_1({ parsed }); + // only keys that start with prefix are exposed to client + for (const [key, value] of Object.entries(parsed)) { + if (prefixes.some((prefix) => key.startsWith(prefix))) { + env[key] = value; + } + } + // check if there are actual env variables starting with VITE_* + // these are typically provided inline and should be prioritized + for (const key in process.env) { + if (prefixes.some((prefix) => key.startsWith(prefix))) { + env[key] = process.env[key]; + } + } + return env; +} +function resolveEnvPrefix({ envPrefix = 'VITE_', }) { + envPrefix = arraify(envPrefix); + if (envPrefix.includes('')) { + throw new Error(`envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`); + } + return envPrefix; +} + +exports.esbuildVersion = esbuild.version; +exports.rollupVersion = rollup.VERSION; +exports.createFilter = createFilter; +exports.createLogger = createLogger; +exports.isCSSRequest = isCSSRequest; +exports.isFileServingAllowed = isFileServingAllowed; +exports.loadEnv = loadEnv; +exports.mergeAlias = mergeAlias; +exports.mergeConfig = mergeConfig; +exports.normalizePath = normalizePath; +exports.resolveEnvPrefix = resolveEnvPrefix; +exports.searchForWorkspaceRoot = searchForWorkspaceRoot; +exports.send = send; +exports.splitVendorChunk = splitVendorChunk; +exports.splitVendorChunkPlugin = splitVendorChunkPlugin; +exports.version = VERSION; diff --git a/node_modules/vite/dist/node/chunks/dep-8a-6Quh6.js b/node_modules/vite/dist/node/chunks/dep-8a-6Quh6.js new file mode 100644 index 0000000..b471e60 --- /dev/null +++ b/node_modules/vite/dist/node/chunks/dep-8a-6Quh6.js @@ -0,0 +1,561 @@ +import { fileURLToPath as __cjs_fileURLToPath } from 'node:url'; +import { dirname as __cjs_dirname } from 'node:path'; +import { createRequire as __cjs_createRequire } from 'node:module'; + +const __filename = __cjs_fileURLToPath(import.meta.url); +const __dirname = __cjs_dirname(__filename); +const require = __cjs_createRequire(import.meta.url); +const __require = require; +var openParentheses = "(".charCodeAt(0); +var closeParentheses = ")".charCodeAt(0); +var singleQuote = "'".charCodeAt(0); +var doubleQuote = '"'.charCodeAt(0); +var backslash = "\\".charCodeAt(0); +var slash = "/".charCodeAt(0); +var comma = ",".charCodeAt(0); +var colon = ":".charCodeAt(0); +var star = "*".charCodeAt(0); +var uLower = "u".charCodeAt(0); +var uUpper = "U".charCodeAt(0); +var plus = "+".charCodeAt(0); +var isUnicodeRange = /^[a-f0-9?-]+$/i; + +var parse$1 = function(input) { + var tokens = []; + var value = input; + + var next, + quote, + prev, + token, + escape, + escapePos, + whitespacePos, + parenthesesOpenPos; + var pos = 0; + var code = value.charCodeAt(pos); + var max = value.length; + var stack = [{ nodes: tokens }]; + var balanced = 0; + var parent; + + var name = ""; + var before = ""; + var after = ""; + + while (pos < max) { + // Whitespaces + if (code <= 32) { + next = pos; + do { + next += 1; + code = value.charCodeAt(next); + } while (code <= 32); + token = value.slice(pos, next); + + prev = tokens[tokens.length - 1]; + if (code === closeParentheses && balanced) { + after = token; + } else if (prev && prev.type === "div") { + prev.after = token; + prev.sourceEndIndex += token.length; + } else if ( + code === comma || + code === colon || + (code === slash && + value.charCodeAt(next + 1) !== star && + (!parent || + (parent && parent.type === "function" && parent.value !== "calc"))) + ) { + before = token; + } else { + tokens.push({ + type: "space", + sourceIndex: pos, + sourceEndIndex: next, + value: token + }); + } + + pos = next; + + // Quotes + } else if (code === singleQuote || code === doubleQuote) { + next = pos; + quote = code === singleQuote ? "'" : '"'; + token = { + type: "string", + sourceIndex: pos, + quote: quote + }; + do { + escape = false; + next = value.indexOf(quote, next + 1); + if (~next) { + escapePos = next; + while (value.charCodeAt(escapePos - 1) === backslash) { + escapePos -= 1; + escape = !escape; + } + } else { + value += quote; + next = value.length - 1; + token.unclosed = true; + } + } while (escape); + token.value = value.slice(pos + 1, next); + token.sourceEndIndex = token.unclosed ? next : next + 1; + tokens.push(token); + pos = next + 1; + code = value.charCodeAt(pos); + + // Comments + } else if (code === slash && value.charCodeAt(pos + 1) === star) { + next = value.indexOf("*/", pos); + + token = { + type: "comment", + sourceIndex: pos, + sourceEndIndex: next + 2 + }; + + if (next === -1) { + token.unclosed = true; + next = value.length; + token.sourceEndIndex = next; + } + + token.value = value.slice(pos + 2, next); + tokens.push(token); + + pos = next + 2; + code = value.charCodeAt(pos); + + // Operation within calc + } else if ( + (code === slash || code === star) && + parent && + parent.type === "function" && + parent.value === "calc" + ) { + token = value[pos]; + tokens.push({ + type: "word", + sourceIndex: pos - before.length, + sourceEndIndex: pos + token.length, + value: token + }); + pos += 1; + code = value.charCodeAt(pos); + + // Dividers + } else if (code === slash || code === comma || code === colon) { + token = value[pos]; + + tokens.push({ + type: "div", + sourceIndex: pos - before.length, + sourceEndIndex: pos + token.length, + value: token, + before: before, + after: "" + }); + before = ""; + + pos += 1; + code = value.charCodeAt(pos); + + // Open parentheses + } else if (openParentheses === code) { + // Whitespaces after open parentheses + next = pos; + do { + next += 1; + code = value.charCodeAt(next); + } while (code <= 32); + parenthesesOpenPos = pos; + token = { + type: "function", + sourceIndex: pos - name.length, + value: name, + before: value.slice(parenthesesOpenPos + 1, next) + }; + pos = next; + + if (name === "url" && code !== singleQuote && code !== doubleQuote) { + next -= 1; + do { + escape = false; + next = value.indexOf(")", next + 1); + if (~next) { + escapePos = next; + while (value.charCodeAt(escapePos - 1) === backslash) { + escapePos -= 1; + escape = !escape; + } + } else { + value += ")"; + next = value.length - 1; + token.unclosed = true; + } + } while (escape); + // Whitespaces before closed + whitespacePos = next; + do { + whitespacePos -= 1; + code = value.charCodeAt(whitespacePos); + } while (code <= 32); + if (parenthesesOpenPos < whitespacePos) { + if (pos !== whitespacePos + 1) { + token.nodes = [ + { + type: "word", + sourceIndex: pos, + sourceEndIndex: whitespacePos + 1, + value: value.slice(pos, whitespacePos + 1) + } + ]; + } else { + token.nodes = []; + } + if (token.unclosed && whitespacePos + 1 !== next) { + token.after = ""; + token.nodes.push({ + type: "space", + sourceIndex: whitespacePos + 1, + sourceEndIndex: next, + value: value.slice(whitespacePos + 1, next) + }); + } else { + token.after = value.slice(whitespacePos + 1, next); + token.sourceEndIndex = next; + } + } else { + token.after = ""; + token.nodes = []; + } + pos = next + 1; + token.sourceEndIndex = token.unclosed ? next : pos; + code = value.charCodeAt(pos); + tokens.push(token); + } else { + balanced += 1; + token.after = ""; + token.sourceEndIndex = pos + 1; + tokens.push(token); + stack.push(token); + tokens = token.nodes = []; + parent = token; + } + name = ""; + + // Close parentheses + } else if (closeParentheses === code && balanced) { + pos += 1; + code = value.charCodeAt(pos); + + parent.after = after; + parent.sourceEndIndex += after.length; + after = ""; + balanced -= 1; + stack[stack.length - 1].sourceEndIndex = pos; + stack.pop(); + parent = stack[balanced]; + tokens = parent.nodes; + + // Words + } else { + next = pos; + do { + if (code === backslash) { + next += 1; + } + next += 1; + code = value.charCodeAt(next); + } while ( + next < max && + !( + code <= 32 || + code === singleQuote || + code === doubleQuote || + code === comma || + code === colon || + code === slash || + code === openParentheses || + (code === star && + parent && + parent.type === "function" && + parent.value === "calc") || + (code === slash && + parent.type === "function" && + parent.value === "calc") || + (code === closeParentheses && balanced) + ) + ); + token = value.slice(pos, next); + + if (openParentheses === code) { + name = token; + } else if ( + (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) && + plus === token.charCodeAt(1) && + isUnicodeRange.test(token.slice(2)) + ) { + tokens.push({ + type: "unicode-range", + sourceIndex: pos, + sourceEndIndex: next, + value: token + }); + } else { + tokens.push({ + type: "word", + sourceIndex: pos, + sourceEndIndex: next, + value: token + }); + } + + pos = next; + } + } + + for (pos = stack.length - 1; pos; pos -= 1) { + stack[pos].unclosed = true; + stack[pos].sourceEndIndex = value.length; + } + + return stack[0].nodes; +}; + +var walk$1 = function walk(nodes, cb, bubble) { + var i, max, node, result; + + for (i = 0, max = nodes.length; i < max; i += 1) { + node = nodes[i]; + if (!bubble) { + result = cb(node, i, nodes); + } + + if ( + result !== false && + node.type === "function" && + Array.isArray(node.nodes) + ) { + walk(node.nodes, cb, bubble); + } + + if (bubble) { + cb(node, i, nodes); + } + } +}; + +function stringifyNode(node, custom) { + var type = node.type; + var value = node.value; + var buf; + var customResult; + + if (custom && (customResult = custom(node)) !== undefined) { + return customResult; + } else if (type === "word" || type === "space") { + return value; + } else if (type === "string") { + buf = node.quote || ""; + return buf + value + (node.unclosed ? "" : buf); + } else if (type === "comment") { + return "/*" + value + (node.unclosed ? "" : "*/"); + } else if (type === "div") { + return (node.before || "") + value + (node.after || ""); + } else if (Array.isArray(node.nodes)) { + buf = stringify$1(node.nodes, custom); + if (type !== "function") { + return buf; + } + return ( + value + + "(" + + (node.before || "") + + buf + + (node.after || "") + + (node.unclosed ? "" : ")") + ); + } + return value; +} + +function stringify$1(nodes, custom) { + var result, i; + + if (Array.isArray(nodes)) { + result = ""; + for (i = nodes.length - 1; ~i; i -= 1) { + result = stringifyNode(nodes[i], custom) + result; + } + return result; + } + return stringifyNode(nodes, custom); +} + +var stringify_1 = stringify$1; + +var unit; +var hasRequiredUnit; + +function requireUnit () { + if (hasRequiredUnit) return unit; + hasRequiredUnit = 1; + var minus = "-".charCodeAt(0); + var plus = "+".charCodeAt(0); + var dot = ".".charCodeAt(0); + var exp = "e".charCodeAt(0); + var EXP = "E".charCodeAt(0); + + // Check if three code points would start a number + // https://www.w3.org/TR/css-syntax-3/#starts-with-a-number + function likeNumber(value) { + var code = value.charCodeAt(0); + var nextCode; + + if (code === plus || code === minus) { + nextCode = value.charCodeAt(1); + + if (nextCode >= 48 && nextCode <= 57) { + return true; + } + + var nextNextCode = value.charCodeAt(2); + + if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) { + return true; + } + + return false; + } + + if (code === dot) { + nextCode = value.charCodeAt(1); + + if (nextCode >= 48 && nextCode <= 57) { + return true; + } + + return false; + } + + if (code >= 48 && code <= 57) { + return true; + } + + return false; + } + + // Consume a number + // https://www.w3.org/TR/css-syntax-3/#consume-number + unit = function(value) { + var pos = 0; + var length = value.length; + var code; + var nextCode; + var nextNextCode; + + if (length === 0 || !likeNumber(value)) { + return false; + } + + code = value.charCodeAt(pos); + + if (code === plus || code === minus) { + pos++; + } + + while (pos < length) { + code = value.charCodeAt(pos); + + if (code < 48 || code > 57) { + break; + } + + pos += 1; + } + + code = value.charCodeAt(pos); + nextCode = value.charCodeAt(pos + 1); + + if (code === dot && nextCode >= 48 && nextCode <= 57) { + pos += 2; + + while (pos < length) { + code = value.charCodeAt(pos); + + if (code < 48 || code > 57) { + break; + } + + pos += 1; + } + } + + code = value.charCodeAt(pos); + nextCode = value.charCodeAt(pos + 1); + nextNextCode = value.charCodeAt(pos + 2); + + if ( + (code === exp || code === EXP) && + ((nextCode >= 48 && nextCode <= 57) || + ((nextCode === plus || nextCode === minus) && + nextNextCode >= 48 && + nextNextCode <= 57)) + ) { + pos += nextCode === plus || nextCode === minus ? 3 : 2; + + while (pos < length) { + code = value.charCodeAt(pos); + + if (code < 48 || code > 57) { + break; + } + + pos += 1; + } + } + + return { + number: value.slice(0, pos), + unit: value.slice(pos) + }; + }; + return unit; +} + +var parse = parse$1; +var walk = walk$1; +var stringify = stringify_1; + +function ValueParser(value) { + if (this instanceof ValueParser) { + this.nodes = parse(value); + return this; + } + return new ValueParser(value); +} + +ValueParser.prototype.toString = function() { + return Array.isArray(this.nodes) ? stringify(this.nodes) : ""; +}; + +ValueParser.prototype.walk = function(cb, bubble) { + walk(this.nodes, cb, bubble); + return this; +}; + +ValueParser.unit = requireUnit(); + +ValueParser.walk = walk; + +ValueParser.stringify = stringify; + +var lib = ValueParser; + +export { lib as l }; diff --git a/node_modules/vite/dist/node/chunks/dep-V3BH7oO1.js b/node_modules/vite/dist/node/chunks/dep-V3BH7oO1.js new file mode 100644 index 0000000..628c10d --- /dev/null +++ b/node_modules/vite/dist/node/chunks/dep-V3BH7oO1.js @@ -0,0 +1,68436 @@ +import fs$l, { promises as promises$1 } from 'node:fs'; +import fsp from 'node:fs/promises'; +import path$o, { posix as posix$1, isAbsolute as isAbsolute$2, join as join$2, extname as extname$1, dirname as dirname$2, relative as relative$2, basename as basename$2 } from 'node:path'; +import { fileURLToPath, URL as URL$3, URLSearchParams, parse as parse$i, pathToFileURL } from 'node:url'; +import { promisify as promisify$4, format as format$2, inspect } from 'node:util'; +import { performance } from 'node:perf_hooks'; +import { createRequire as createRequire$1, builtinModules } from 'node:module'; +import require$$0$3 from 'tty'; +import require$$0$4, { win32, posix, isAbsolute as isAbsolute$1, resolve as resolve$3, relative as relative$1, basename as basename$1, extname, dirname as dirname$1, join as join$1, sep, normalize } from 'path'; +import esbuild, { transform as transform$1, formatMessages, build as build$3 } from 'esbuild'; +import * as require$$0$2 from 'fs'; +import require$$0__default, { existsSync, readFileSync, statSync as statSync$1, readdirSync } from 'fs'; +import require$$0$5 from 'events'; +import require$$5 from 'assert'; +import { createServer as createServer$3, STATUS_CODES, get as get$2 } from 'node:http'; +import { createServer as createServer$2, get as get$1 } from 'node:https'; +import require$$0$6 from 'util'; +import require$$4$1 from 'net'; +import require$$0$9 from 'url'; +import require$$1$1 from 'http'; +import require$$0$7 from 'stream'; +import require$$2 from 'os'; +import require$$2$1 from 'child_process'; +import os$4 from 'node:os'; +import { exec } from 'node:child_process'; +import { createHash as createHash$2 } from 'node:crypto'; +import { promises } from 'node:dns'; +import { CLIENT_ENTRY, VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER, OPTIMIZABLE_ENTRY_RE, FS_PREFIX, wildcardHosts, loopbackHosts, CLIENT_PUBLIC_PATH, ENV_PUBLIC_PATH, ENV_ENTRY, DEP_VERSION_RE, SPECIAL_QUERY_RE, DEFAULT_MAIN_FIELDS, DEFAULT_EXTENSIONS, CSS_LANGS_RE, ESBUILD_MODULES_TARGET, KNOWN_ASSET_TYPES, VITE_PACKAGE_DIR, DEFAULT_DEV_PORT, CLIENT_DIR, JS_TYPES_RE, VERSION as VERSION$1, DEFAULT_PREVIEW_PORT, DEFAULT_ASSETS_RE, DEFAULT_CONFIG_FILES } from '../constants.js'; +import require$$0$a from 'crypto'; +import require$$0$8, { createRequire as createRequire$2 } from 'module'; +import assert$1 from 'node:assert'; +import process$1 from 'node:process'; +import v8 from 'node:v8'; +import { Buffer as Buffer$1 } from 'node:buffer'; +import { VERSION } from 'rollup'; +import { parseAstAsync, parseAst } from 'rollup/parseAst'; +import * as qs from 'querystring'; +import readline from 'node:readline'; +import { EventEmitter as EventEmitter$4 } from 'node:events'; +import require$$0$b from 'zlib'; +import require$$0$c from 'buffer'; +import require$$1$2 from 'https'; +import require$$4$2 from 'tls'; +import zlib$1, { gzip } from 'node:zlib'; +import require$$1 from 'worker_threads'; + +import { fileURLToPath as __cjs_fileURLToPath } from 'node:url'; +import { dirname as __cjs_dirname } from 'node:path'; +import { createRequire as __cjs_createRequire } from 'node:module'; + +const __filename = __cjs_fileURLToPath(import.meta.url); +const __dirname = __cjs_dirname(__filename); +const require = __cjs_createRequire(import.meta.url); +const __require = require; +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a () { + if (this instanceof a) { + return Reflect.construct(f, arguments, this.constructor); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} + +var picocolors = {exports: {}}; + +let tty = require$$0$3; + +let isColorSupported = + !("NO_COLOR" in process.env || process.argv.includes("--no-color")) && + ("FORCE_COLOR" in process.env || + process.argv.includes("--color") || + process.platform === "win32" || + (tty.isatty(1) && process.env.TERM !== "dumb") || + "CI" in process.env); + +let formatter = + (open, close, replace = open) => + input => { + let string = "" + input; + let index = string.indexOf(close, open.length); + return ~index + ? open + replaceClose(string, close, replace, index) + close + : open + string + close + }; + +let replaceClose = (string, close, replace, index) => { + let start = string.substring(0, index) + replace; + let end = string.substring(index + close.length); + let nextIndex = end.indexOf(close); + return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end +}; + +let createColors = (enabled = isColorSupported) => ({ + isColorSupported: enabled, + reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String, + bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String, + dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String, + italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String, + underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String, + inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String, + hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String, + strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String, + black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String, + red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String, + green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String, + yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String, + blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String, + magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String, + cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String, + white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String, + gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String, + bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String, + bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String, + bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String, + bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String, + bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String, + bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String, + bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String, + bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String, +}); + +picocolors.exports = createColors(); +picocolors.exports.createColors = createColors; + +var picocolorsExports = picocolors.exports; +var colors$1 = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports); + +function matches$1(pattern, importee) { + if (pattern instanceof RegExp) { + return pattern.test(importee); + } + if (importee.length < pattern.length) { + return false; + } + if (importee === pattern) { + return true; + } + // eslint-disable-next-line prefer-template + return importee.startsWith(pattern + '/'); +} +function getEntries({ entries, customResolver }) { + if (!entries) { + return []; + } + const resolverFunctionFromOptions = resolveCustomResolver(customResolver); + if (Array.isArray(entries)) { + return entries.map((entry) => { + return { + find: entry.find, + replacement: entry.replacement, + resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions + }; + }); + } + return Object.entries(entries).map(([key, value]) => { + return { find: key, replacement: value, resolverFunction: resolverFunctionFromOptions }; + }); +} +function getHookFunction(hook) { + if (typeof hook === 'function') { + return hook; + } + if (hook && 'handler' in hook && typeof hook.handler === 'function') { + return hook.handler; + } + return null; +} +function resolveCustomResolver(customResolver) { + if (typeof customResolver === 'function') { + return customResolver; + } + if (customResolver) { + return getHookFunction(customResolver.resolveId); + } + return null; +} +function alias$1(options = {}) { + const entries = getEntries(options); + if (entries.length === 0) { + return { + name: 'alias', + resolveId: () => null + }; + } + return { + name: 'alias', + async buildStart(inputOptions) { + await Promise.all([...(Array.isArray(options.entries) ? options.entries : []), options].map(({ customResolver }) => { var _a; return customResolver && ((_a = getHookFunction(customResolver.buildStart)) === null || _a === void 0 ? void 0 : _a.call(this, inputOptions)); })); + }, + resolveId(importee, importer, resolveOptions) { + // First match is supposed to be the correct one + const matchedEntry = entries.find((entry) => matches$1(entry.find, importee)); + if (!matchedEntry) { + return null; + } + const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement); + if (matchedEntry.resolverFunction) { + return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions); + } + return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => { + if (resolved) + return resolved; + if (!require$$0$4.isAbsolute(updatedId)) { + this.warn(`rewrote ${importee} to ${updatedId} but was not an abolute path and was not handled by other plugins. ` + + `This will lead to duplicated modules for the same path. ` + + `To avoid duplicating modules, you should resolve to an absolute path.`); + } + return { id: updatedId }; + }); + } + }; +} + +// @ts-check +/** @typedef { import('estree').BaseNode} BaseNode */ + +/** @typedef {{ + skip: () => void; + remove: () => void; + replace: (node: BaseNode) => void; +}} WalkerContext */ + +let WalkerBase$1 = class WalkerBase { + constructor() { + /** @type {boolean} */ + this.should_skip = false; + + /** @type {boolean} */ + this.should_remove = false; + + /** @type {BaseNode | null} */ + this.replacement = null; + + /** @type {WalkerContext} */ + this.context = { + skip: () => (this.should_skip = true), + remove: () => (this.should_remove = true), + replace: (node) => (this.replacement = node) + }; + } + + /** + * + * @param {any} parent + * @param {string} prop + * @param {number} index + * @param {BaseNode} node + */ + replace(parent, prop, index, node) { + if (parent) { + if (index !== null) { + parent[prop][index] = node; + } else { + parent[prop] = node; + } + } + } + + /** + * + * @param {any} parent + * @param {string} prop + * @param {number} index + */ + remove(parent, prop, index) { + if (parent) { + if (index !== null) { + parent[prop].splice(index, 1); + } else { + delete parent[prop]; + } + } + } +}; + +// @ts-check + +/** @typedef { import('estree').BaseNode} BaseNode */ +/** @typedef { import('./walker.js').WalkerContext} WalkerContext */ + +/** @typedef {( + * this: WalkerContext, + * node: BaseNode, + * parent: BaseNode, + * key: string, + * index: number + * ) => void} SyncHandler */ + +let SyncWalker$1 = class SyncWalker extends WalkerBase$1 { + /** + * + * @param {SyncHandler} enter + * @param {SyncHandler} leave + */ + constructor(enter, leave) { + super(); + + /** @type {SyncHandler} */ + this.enter = enter; + + /** @type {SyncHandler} */ + this.leave = leave; + } + + /** + * + * @param {BaseNode} node + * @param {BaseNode} parent + * @param {string} [prop] + * @param {number} [index] + * @returns {BaseNode} + */ + visit(node, parent, prop, index) { + if (node) { + if (this.enter) { + const _should_skip = this.should_skip; + const _should_remove = this.should_remove; + const _replacement = this.replacement; + this.should_skip = false; + this.should_remove = false; + this.replacement = null; + + this.enter.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const skipped = this.should_skip; + const removed = this.should_remove; + + this.should_skip = _should_skip; + this.should_remove = _should_remove; + this.replacement = _replacement; + + if (skipped) return node; + if (removed) return null; + } + + for (const key in node) { + const value = node[key]; + + if (typeof value !== "object") { + continue; + } else if (Array.isArray(value)) { + for (let i = 0; i < value.length; i += 1) { + if (value[i] !== null && typeof value[i].type === 'string') { + if (!this.visit(value[i], node, key, i)) { + // removed + i--; + } + } + } + } else if (value !== null && typeof value.type === "string") { + this.visit(value, node, key, null); + } + } + + if (this.leave) { + const _replacement = this.replacement; + const _should_remove = this.should_remove; + this.replacement = null; + this.should_remove = false; + + this.leave.call(this.context, node, parent, prop, index); + + if (this.replacement) { + node = this.replacement; + this.replace(parent, prop, index, node); + } + + if (this.should_remove) { + this.remove(parent, prop, index); + } + + const removed = this.should_remove; + + this.replacement = _replacement; + this.should_remove = _should_remove; + + if (removed) return null; + } + } + + return node; + } +}; + +// @ts-check + +/** @typedef { import('estree').BaseNode} BaseNode */ +/** @typedef { import('./sync.js').SyncHandler} SyncHandler */ +/** @typedef { import('./async.js').AsyncHandler} AsyncHandler */ + +/** + * + * @param {BaseNode} ast + * @param {{ + * enter?: SyncHandler + * leave?: SyncHandler + * }} walker + * @returns {BaseNode} + */ +function walk$3(ast, { enter, leave }) { + const instance = new SyncWalker$1(enter, leave); + return instance.visit(ast, null); +} + +var utils$k = {}; + +const path$n = require$$0$4; +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; + +/** + * Posix glob regex + */ + +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR$1 = `${QMARK}*?`; + +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR: STAR$1, + START_ANCHOR +}; + +/** + * Windows glob regex + */ + +const WINDOWS_CHARS = { + ...POSIX_CHARS, + + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` +}; + +/** + * POSIX Bracket Regex + */ + +const POSIX_REGEX_SOURCE$1 = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; + +var constants$6 = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, + + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, + + // Digits + CHAR_0: 48, /* 0 */ + CHAR_9: 57, /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 65, /* A */ + CHAR_LOWERCASE_A: 97, /* a */ + CHAR_UPPERCASE_Z: 90, /* Z */ + CHAR_LOWERCASE_Z: 122, /* z */ + + CHAR_LEFT_PARENTHESES: 40, /* ( */ + CHAR_RIGHT_PARENTHESES: 41, /* ) */ + + CHAR_ASTERISK: 42, /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, /* & */ + CHAR_AT: 64, /* @ */ + CHAR_BACKWARD_SLASH: 92, /* \ */ + CHAR_CARRIAGE_RETURN: 13, /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ + CHAR_COLON: 58, /* : */ + CHAR_COMMA: 44, /* , */ + CHAR_DOT: 46, /* . */ + CHAR_DOUBLE_QUOTE: 34, /* " */ + CHAR_EQUAL: 61, /* = */ + CHAR_EXCLAMATION_MARK: 33, /* ! */ + CHAR_FORM_FEED: 12, /* \f */ + CHAR_FORWARD_SLASH: 47, /* / */ + CHAR_GRAVE_ACCENT: 96, /* ` */ + CHAR_HASH: 35, /* # */ + CHAR_HYPHEN_MINUS: 45, /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ + CHAR_LEFT_CURLY_BRACE: 123, /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ + CHAR_LINE_FEED: 10, /* \n */ + CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ + CHAR_PERCENT: 37, /* % */ + CHAR_PLUS: 43, /* + */ + CHAR_QUESTION_MARK: 63, /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ + CHAR_SEMICOLON: 59, /* ; */ + CHAR_SINGLE_QUOTE: 39, /* ' */ + CHAR_SPACE: 32, /* */ + CHAR_TAB: 9, /* \t */ + CHAR_UNDERSCORE: 95, /* _ */ + CHAR_VERTICAL_LINE: 124, /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ + + SEP: path$n.sep, + + /** + * Create EXTGLOB_CHARS + */ + + extglobChars(chars) { + return { + '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` }, + '?': { type: 'qmark', open: '(?:', close: ')?' }, + '+': { type: 'plus', open: '(?:', close: ')+' }, + '*': { type: 'star', open: '(?:', close: ')*' }, + '@': { type: 'at', open: '(?:', close: ')' } + }; + }, + + /** + * Create GLOB_CHARS + */ + + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } +}; + +(function (exports) { + + const path = require$$0$4; + const win32 = process.platform === 'win32'; + const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL + } = constants$6; + + exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); + exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); + exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); + exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); + exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + + exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); + }; + + exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split('.').map(Number); + if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) { + return true; + } + return false; + }; + + exports.isWindows = options => { + if (options && typeof options.windows === 'boolean') { + return options.windows; + } + return win32 === true || path.sep === '\\'; + }; + + exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; + }; + + exports.removePrefix = (input, state = {}) => { + let output = input; + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + return output; + }; + + exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; + + let output = `${prepend}(?:${input})${append}`; + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + return output; + }; +} (utils$k)); + +const utils$j = utils$k; +const { + CHAR_ASTERISK, /* * */ + CHAR_AT, /* @ */ + CHAR_BACKWARD_SLASH, /* \ */ + CHAR_COMMA: CHAR_COMMA$1, /* , */ + CHAR_DOT: CHAR_DOT$1, /* . */ + CHAR_EXCLAMATION_MARK, /* ! */ + CHAR_FORWARD_SLASH, /* / */ + CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ + CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ + CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ + CHAR_PLUS, /* + */ + CHAR_QUESTION_MARK, /* ? */ + CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ + CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ + CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */ +} = constants$6; + +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; + +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } +}; + +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not + * with `!(`) and `negatedExtglob` (true if the path starts with `!(`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ + +const scan$2 = (input, options) => { + const opts = options || {}; + + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let negatedExtglob = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { value: '', depth: 0, isGlob: false }; + + const eos = () => index >= length; + const peek = () => str.charCodeAt(index + 1); + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + + while (index < length) { + code = advance(); + let next; + + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + + if (code === CHAR_LEFT_CURLY_BRACE$1) { + braceEscaped = true; + } + continue; + } + + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) { + braces++; + + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (code === CHAR_LEFT_CURLY_BRACE$1) { + braces++; + continue; + } + + if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (braceEscaped !== true && code === CHAR_COMMA$1) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_RIGHT_CURLY_BRACE$1) { + braces--; + + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { value: '', depth: 0, isGlob: false }; + + if (finished === true) continue; + if (prev === CHAR_DOT$1 && index === (start + 1)) { + start += 2; + continue; + } + + lastIndex = index + 1; + continue; + } + + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS + || code === CHAR_AT + || code === CHAR_ASTERISK + || code === CHAR_QUESTION_MARK + || code === CHAR_EXCLAMATION_MARK; + + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + if (code === CHAR_EXCLAMATION_MARK && index === start) { + negatedExtglob = true; + } + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES$1) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + continue; + } + break; + } + } + + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + break; + } + + if (code === CHAR_LEFT_SQUARE_BRACKET$1) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + break; + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) { + isGlob = token.isGlob = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES$1) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES$1) { + finished = true; + break; + } + } + continue; + } + break; + } + + if (isGlob === true) { + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + + let base = str; + let prefix = ''; + let glob = ''; + + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + + if (opts.unescape === true) { + if (glob) glob = utils$j.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils$j.removeBackslashes(base); + } + } + + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated, + negatedExtglob + }; + + if (opts.tokens === true) { + state.maxDepth = 0; + if (!isPathSeparator(code)) { + tokens.push(token); + } + state.tokens = tokens; + } + + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + if (idx !== 0 || value !== '') { + parts.push(value); + } + prevIndex = i; + } + + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + + state.slashes = slashes; + state.parts = parts; + } + + return state; +}; + +var scan_1 = scan$2; + +const constants$5 = constants$6; +const utils$i = utils$k; + +/** + * Constants + */ + +const { + MAX_LENGTH: MAX_LENGTH$1, + POSIX_REGEX_SOURCE, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants$5; + +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.join('-')}]`; + + return value; +}; + +/** + * Create the message for a syntax error + */ + +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; + +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + +const parse$h = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + input = REPLACEMENTS[input] || input; + + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; + + let len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + const bos = { type: 'bos', value: '', output: opts.prepend || '' }; + const tokens = [bos]; + + const capture = opts.capture ? '' : '?:'; + const win32 = utils$i.isWindows(options); + + // create constants based on platform, for windows or posix + const PLATFORM_CHARS = constants$5.globChars(win32); + const EXTGLOB_CHARS = constants$5.extglobChars(PLATFORM_CHARS); + + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + + const globstar = opts => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + // minimatch options support + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } + + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + + input = utils$i.removePrefix(input, state); + len = input.length; + + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + const peek = state.peek = (n = 1) => input[state.index + n]; + const advance = state.advance = () => input[++state.index] || ''; + const remaining = () => input.slice(state.index + 1); + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; + } + + if (count % 2 === 0) { + return false; + } + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren')); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } + } + + if (extglobs.length && tok.type !== 'paren') { + extglobs[extglobs.length - 1].inner += tok.value; + } + + if (tok.value || tok.output) append(tok); + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + prev.output = (prev.output || '') + tok.value; + return; + } + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; + + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; + + increment('parens'); + push({ type, value, output: state.output ? '' : ONE_CHAR }); + push({ type: 'paren', extglob: true, value: advance(), output }); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + let rest; + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { + // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis. + // In this case, we need to parse the string and use it in the output of the original pattern. + // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`. + // + // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`. + const expression = parse$h(rest, { ...options, fastpaths: false }).output; + + output = token.close = `)${expression})${extglobStar})`; + } + + if (token.prev.type === 'bos') { + state.negatedExtglob = true; + } + } + + push({ type: 'paren', extglob: true, value, output }); + decrement('parens'); + }; + + /** + * Fast paths + */ + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); + } + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); + } + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); + } + return star; + } + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : ''); + }); + } + } + + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + + state.output = utils$i.wrapOutput(output, state, options); + return state; + } + + /** + * Tokenize input until we reach end-of-string + */ + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; + } + + /** + * Escaped characters + */ + + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ type: 'text', value }); + continue; + } + + // collapse slashes to reduce potential for exploits + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + if (slashes % 2 !== 0) { + value += '\\'; + } + } + + if (opts.unescape === true) { + value = advance(); + } else { + value += advance(); + } + + if (state.brackets === 0) { + push({ type: 'text', value }); + continue; + } + } + + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE[rest]; + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + continue; + } + } + } + } + + if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ value }); + continue; + } + + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + if (state.quotes === 1 && value !== '"') { + value = utils$i.escapeRegex(value); + prev.value += value; + append({ value }); + continue; + } + + /** + * Double quotes + */ + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + if (opts.keepQuotes === true) { + push({ type: 'text', value }); + } + continue; + } + + /** + * Parentheses + */ + + if (value === '(') { + increment('parens'); + push({ type: 'paren', value }); + continue; + } + + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } + + const extglob = extglobs[extglobs.length - 1]; + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + + push({ type: 'paren', value, output: state.parens ? ')' : '\\)' }); + decrement('parens'); + continue; + } + + /** + * Square brackets + */ + + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); + } + + value = `\\${value}`; + } else { + increment('brackets'); + } + + push({ type: 'bracket', value }); + continue; + } + + if (value === ']') { + if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) { + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); + } + + push({ type: 'text', value, output: `\\${value}` }); + continue; + } + + decrement('brackets'); + + const prevValue = prev.value.slice(1); + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + + prev.value += value; + append({ value }); + + // when literal brackets are explicitly disabled + // assume we should match with a regex character class + if (opts.literalBrackets === false || utils$i.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils$i.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); + + // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } + + // when the user specifies nothing, try to match both + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + + /** + * Braces + */ + + if (value === '{' && opts.nobrace !== true) { + increment('braces'); + + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + + braces.push(open); + push(open); + continue; + } + + if (value === '}') { + const brace = braces[braces.length - 1]; + + if (opts.nobrace === true || !brace) { + push({ type: 'text', value, output: value }); + continue; + } + + let output = ')'; + + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + if (arr[i].type === 'brace') { + break; + } + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; + } + + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = '\\}'; + state.output = out; + for (const t of toks) { + state.output += (t.output || t.value); + } + } + + push({ type: 'brace', value, output }); + decrement('braces'); + braces.pop(); + continue; + } + + /** + * Pipes + */ + + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + push({ type: 'text', value }); + continue; + } + + /** + * Commas + */ + + if (value === ',') { + let output = value; + + const brace = braces[braces.length - 1]; + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } + + push({ type: 'comma', value, output }); + continue; + } + + /** + * Slashes + */ + + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + continue; + } + + push({ type: 'slash', value, output: SLASH_LITERAL }); + continue; + } + + /** + * Dots + */ + + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + + if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ type: 'text', value, output: DOT_LITERAL }); + continue; + } + + push({ type: 'dot', value, output: DOT_LITERAL }); + continue; + } + + /** + * Question marks + */ + + if (value === '?') { + const isGroup = prev && prev.value === '('; + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } + + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; + + if (next === '<' && !utils$i.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } + + if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) { + output = `\\${value}`; + } + + push({ type: 'text', value, output }); + continue; + } + + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ type: 'qmark', value, output: QMARK_NO_DOT }); + continue; + } + + push({ type: 'qmark', value, output: QMARK }); + continue; + } + + /** + * Exclamation + */ + + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } + + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + + /** + * Plus + */ + + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } + + if ((prev && prev.value === '(') || opts.regex === false) { + push({ type: 'plus', value, output: PLUS_LITERAL }); + continue; + } + + if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) { + push({ type: 'plus', value }); + continue; + } + + push({ type: 'plus', value: PLUS_LITERAL }); + continue; + } + + /** + * Plain text + */ + + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ type: 'at', extglob: true, value, output: '' }); + continue; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Plain text + */ + + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } + + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + if (match) { + value += match[0]; + state.index += match[0].length; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Stars + */ + + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + + let rest = remaining(); + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } + + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + + if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) { + push({ type: 'star', value, output: '' }); + continue; + } + + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ type: 'star', value, output: '' }); + continue; + } + + // strip consecutive `/**/` + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + if (after && after !== '/') { + break; + } + rest = rest.slice(3); + consume('/**', 3); + } + + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; + + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + + state.output += prior.output + prev.output; + state.globstar = true; + + consume(value + advance()); + + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ type: 'slash', value: '/', output: '' }); + continue; + } + + // remove single star from output + state.output = state.output.slice(0, -prev.output.length); + + // reset previous token to globstar + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; + + // reset output with globstar + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + + const token = { type: 'star', value, output: star }; + + if (opts.bash === true) { + token.output = '.*?'; + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + push(token); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } + + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + + } else { + state.output += nodot; + prev.output += nodot; + } + + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + + push(token); + } + + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils$i.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils$i.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils$i.escapeLast(state.output, '{'); + decrement('braces'); + } + + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` }); + } + + // rebuild the output if we had to backtrack at any point + if (state.backtrack === true) { + state.output = ''; + + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + + if (token.suffix) { + state.output += token.suffix; + } + } + } + + return state; +}; + +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + +parse$h.fastpaths = (input, options) => { + const opts = { ...options }; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; + const len = input.length; + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + input = REPLACEMENTS[input] || input; + const win32 = utils$i.isWindows(options); + + // create constants based on platform, for windows or posix + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants$5.globChars(win32); + + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { negated: false, prefix: '' }; + let star = opts.bash === true ? '.*?' : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + const globstar = opts => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; + + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + + case '**': + return nodot + globstar(opts); + + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + + default: { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + + const source = create(match[1]); + if (!source) return; + + return source + DOT_LITERAL + match[2]; + } + } + }; + + const output = utils$i.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +var parse_1$3 = parse$h; + +const path$m = require$$0$4; +const scan$1 = scan_1; +const parse$g = parse_1$3; +const utils$h = utils$k; +const constants$4 = constants$6; +const isObject$3 = val => val && typeof val === 'object' && !Array.isArray(val); + +/** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ + +const picomatch$5 = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch$5(input, options, returnState)); + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + return false; + }; + return arrayMatcher; + } + + const isState = isObject$3(glob) && glob.tokens && glob.input; + + if (glob === '' || (typeof glob !== 'string' && !isState)) { + throw new TypeError('Expected pattern to be a non-empty string'); + } + + const opts = options || {}; + const posix = utils$h.isWindows(options); + const regex = isState + ? picomatch$5.compileRe(glob, options) + : picomatch$5.makeRe(glob, options, false, true); + + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + if (opts.ignore) { + const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null }; + isIgnored = picomatch$5(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { isMatch, match, output } = picomatch$5.test(input, regex, options, { glob, posix }); + const result = { glob, state, regex, posix, input, output, match, isMatch }; + + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } + + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; +}; + +/** + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public + */ + +picomatch$5.test = (input, regex, options, { glob, posix } = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); + } + + if (input === '') { + return { isMatch: false, output: '' }; + } + + const opts = options || {}; + const format = opts.format || (posix ? utils$h.toPosixSlashes : null); + let match = input === glob; + let output = (match && format) ? format(input) : input; + + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch$5.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } + } + + return { isMatch: Boolean(match), match, output }; +}; + +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + +picomatch$5.matchBase = (input, glob, options, posix = utils$h.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch$5.makeRe(glob, options); + return regex.test(path$m.basename(input)); +}; + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +picomatch$5.isMatch = (str, patterns, options) => picomatch$5(patterns, options)(str); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ + +picomatch$5.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch$5.parse(p, options)); + return parse$g(pattern, { ...options, fastpaths: false }); +}; + +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +picomatch$5.scan = (input, options) => scan$1(input, options); + +/** + * Compile a regular expression from the `state` object returned by the + * [parse()](#parse) method. + * + * @param {Object} `state` + * @param {Object} `options` + * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser. + * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. + * @return {RegExp} + * @api public + */ + +picomatch$5.compileRe = (state, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return state.output; + } + + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; + + let source = `${prepend}(?:${state.output})${append}`; + if (state && state.negated === true) { + source = `^(?!${source}).*$`; + } + + const regex = picomatch$5.toRegex(source, options); + if (returnState === true) { + regex.state = state; + } + + return regex; +}; + +/** + * Create a regular expression from a parsed glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. + * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +picomatch$5.makeRe = (input, options = {}, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } + + let parsed = { negated: false, fastpaths: true }; + + if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + parsed.output = parse$g.fastpaths(input, options); + } + + if (!parsed.output) { + parsed = parse$g(input, options); + } + + return picomatch$5.compileRe(parsed, options, returnOutput, returnState); +}; + +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +picomatch$5.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; + +/** + * Picomatch constants. + * @return {Object} + */ + +picomatch$5.constants = constants$4; + +/** + * Expose "picomatch" + */ + +var picomatch_1 = picomatch$5; + +var picomatch$3 = picomatch_1; + +var picomatch$4 = /*@__PURE__*/getDefaultExportFromCjs(picomatch$3); + +const extractors = { + ArrayPattern(names, param) { + for (const element of param.elements) { + if (element) + extractors[element.type](names, element); + } + }, + AssignmentPattern(names, param) { + extractors[param.left.type](names, param.left); + }, + Identifier(names, param) { + names.push(param.name); + }, + MemberExpression() { }, + ObjectPattern(names, param) { + for (const prop of param.properties) { + // @ts-ignore Typescript reports that this is not a valid type + if (prop.type === 'RestElement') { + extractors.RestElement(names, prop); + } + else { + extractors[prop.value.type](names, prop.value); + } + } + }, + RestElement(names, param) { + extractors[param.argument.type](names, param.argument); + } +}; +const extractAssignedNames = function extractAssignedNames(param) { + const names = []; + extractors[param.type](names, param); + return names; +}; + +const blockDeclarations = { + const: true, + let: true +}; +let Scope$1 = class Scope { + constructor(options = {}) { + this.parent = options.parent; + this.isBlockScope = !!options.block; + this.declarations = Object.create(null); + if (options.params) { + options.params.forEach((param) => { + extractAssignedNames(param).forEach((name) => { + this.declarations[name] = true; + }); + }); + } + } + addDeclaration(node, isBlockDeclaration, isVar) { + if (!isBlockDeclaration && this.isBlockScope) { + // it's a `var` or function node, and this + // is a block scope, so we need to go up + this.parent.addDeclaration(node, isBlockDeclaration, isVar); + } + else if (node.id) { + extractAssignedNames(node.id).forEach((name) => { + this.declarations[name] = true; + }); + } + } + contains(name) { + return this.declarations[name] || (this.parent ? this.parent.contains(name) : false); + } +}; +const attachScopes = function attachScopes(ast, propertyName = 'scope') { + let scope = new Scope$1(); + walk$3(ast, { + enter(n, parent) { + const node = n; + // function foo () {...} + // class Foo {...} + if (/(Function|Class)Declaration/.test(node.type)) { + scope.addDeclaration(node, false, false); + } + // var foo = 1 + if (node.type === 'VariableDeclaration') { + const { kind } = node; + const isBlockDeclaration = blockDeclarations[kind]; + node.declarations.forEach((declaration) => { + scope.addDeclaration(declaration, isBlockDeclaration, true); + }); + } + let newScope; + // create new function scope + if (/Function/.test(node.type)) { + const func = node; + newScope = new Scope$1({ + parent: scope, + block: false, + params: func.params + }); + // named function expressions - the name is considered + // part of the function's scope + if (func.type === 'FunctionExpression' && func.id) { + newScope.addDeclaration(func, false, false); + } + } + // create new for scope + if (/For(In|Of)?Statement/.test(node.type)) { + newScope = new Scope$1({ + parent: scope, + block: true + }); + } + // create new block scope + if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) { + newScope = new Scope$1({ + parent: scope, + block: true + }); + } + // catch clause has its own block scope + if (node.type === 'CatchClause') { + newScope = new Scope$1({ + parent: scope, + params: node.param ? [node.param] : [], + block: true + }); + } + if (newScope) { + Object.defineProperty(node, propertyName, { + value: newScope, + configurable: true + }); + scope = newScope; + } + }, + leave(n) { + const node = n; + if (node[propertyName]) + scope = scope.parent; + } + }); + return scope; +}; + +// Helper since Typescript can't detect readonly arrays with Array.isArray +function isArray$2(arg) { + return Array.isArray(arg); +} +function ensureArray(thing) { + if (isArray$2(thing)) + return thing; + if (thing == null) + return []; + return [thing]; +} + +const normalizePath$5 = function normalizePath(filename) { + return filename.split(win32.sep).join(posix.sep); +}; + +function getMatcherString(id, resolutionBase) { + if (resolutionBase === false || isAbsolute$1(id) || id.startsWith('**')) { + return normalizePath$5(id); + } + // resolve('') is valid and will default to process.cwd() + const basePath = normalizePath$5(resolve$3(resolutionBase || '')) + // escape all possible (posix + win) path characters that might interfere with regex + .replace(/[-^$*+?.()|[\]{}]/g, '\\$&'); + // Note that we use posix.join because: + // 1. the basePath has been normalized to use / + // 2. the incoming glob (id) matcher, also uses / + // otherwise Node will force backslash (\) on windows + return posix.join(basePath, normalizePath$5(id)); +} +const createFilter$1 = function createFilter(include, exclude, options) { + const resolutionBase = options && options.resolve; + const getMatcher = (id) => id instanceof RegExp + ? id + : { + test: (what) => { + // this refactor is a tad overly verbose but makes for easy debugging + const pattern = getMatcherString(id, resolutionBase); + const fn = picomatch$4(pattern, { dot: true }); + const result = fn(what); + return result; + } + }; + const includeMatchers = ensureArray(include).map(getMatcher); + const excludeMatchers = ensureArray(exclude).map(getMatcher); + return function result(id) { + if (typeof id !== 'string') + return false; + if (/\0/.test(id)) + return false; + const pathId = normalizePath$5(id); + for (let i = 0; i < excludeMatchers.length; ++i) { + const matcher = excludeMatchers[i]; + if (matcher.test(pathId)) + return false; + } + for (let i = 0; i < includeMatchers.length; ++i) { + const matcher = includeMatchers[i]; + if (matcher.test(pathId)) + return true; + } + return !includeMatchers.length; + }; +}; + +const reservedWords$1 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'; +const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'; +const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins}`.split(' ')); +forbiddenIdentifiers.add(''); +const makeLegalIdentifier = function makeLegalIdentifier(str) { + let identifier = str + .replace(/-(\w)/g, (_, letter) => letter.toUpperCase()) + .replace(/[^$_a-zA-Z0-9]/g, '_'); + if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) { + identifier = `_${identifier}`; + } + return identifier || '_'; +}; + +function stringify$8(obj) { + return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`); +} +function serializeArray(arr, indent, baseIndent) { + let output = '['; + const separator = indent ? `\n${baseIndent}${indent}` : ''; + for (let i = 0; i < arr.length; i++) { + const key = arr[i]; + output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`; + } + return `${output}${indent ? `\n${baseIndent}` : ''}]`; +} +function serializeObject(obj, indent, baseIndent) { + let output = '{'; + const separator = indent ? `\n${baseIndent}${indent}` : ''; + const entries = Object.entries(obj); + for (let i = 0; i < entries.length; i++) { + const [key, value] = entries[i]; + const stringKey = makeLegalIdentifier(key) === key ? key : stringify$8(key); + output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`; + } + return `${output}${indent ? `\n${baseIndent}` : ''}}`; +} +function serialize(obj, indent, baseIndent) { + if (typeof obj === 'object' && obj !== null) { + if (Array.isArray(obj)) + return serializeArray(obj, indent, baseIndent); + if (obj instanceof Date) + return `new Date(${obj.getTime()})`; + if (obj instanceof RegExp) + return obj.toString(); + return serializeObject(obj, indent, baseIndent); + } + if (typeof obj === 'number') { + if (obj === Infinity) + return 'Infinity'; + if (obj === -Infinity) + return '-Infinity'; + if (obj === 0) + return 1 / obj === Infinity ? '0' : '-0'; + if (obj !== obj) + return 'NaN'; // eslint-disable-line no-self-compare + } + if (typeof obj === 'symbol') { + const key = Symbol.keyFor(obj); + // eslint-disable-next-line no-undefined + if (key !== undefined) + return `Symbol.for(${stringify$8(key)})`; + } + if (typeof obj === 'bigint') + return `${obj}n`; + return stringify$8(obj); +} +// isWellFormed exists from Node.js 20 +const hasStringIsWellFormed = 'isWellFormed' in String.prototype; +function isWellFormedString(input) { + // @ts-expect-error String::isWellFormed exists from ES2024. tsconfig lib is set to ES6 + if (hasStringIsWellFormed) + return input.isWellFormed(); + // https://github.com/tc39/proposal-is-usv-string/blob/main/README.md#algorithm + return !/\p{Surrogate}/u.test(input); +} +const dataToEsm = function dataToEsm(data, options = {}) { + var _a, _b; + const t = options.compact ? '' : 'indent' in options ? options.indent : '\t'; + const _ = options.compact ? '' : ' '; + const n = options.compact ? '' : '\n'; + const declarationType = options.preferConst ? 'const' : 'var'; + if (options.namedExports === false || + typeof data !== 'object' || + Array.isArray(data) || + data instanceof Date || + data instanceof RegExp || + data === null) { + const code = serialize(data, options.compact ? null : t, ''); + const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape + return `export default${magic}${code};`; + } + let maxUnderbarPrefixLength = 0; + for (const key of Object.keys(data)) { + const underbarPrefixLength = (_b = (_a = key.match(/^(_+)/)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0; + if (underbarPrefixLength > maxUnderbarPrefixLength) { + maxUnderbarPrefixLength = underbarPrefixLength; + } + } + const arbitraryNamePrefix = `${'_'.repeat(maxUnderbarPrefixLength + 1)}arbitrary`; + let namedExportCode = ''; + const defaultExportRows = []; + const arbitraryNameExportRows = []; + for (const [key, value] of Object.entries(data)) { + if (key === makeLegalIdentifier(key)) { + if (options.objectShorthand) + defaultExportRows.push(key); + else + defaultExportRows.push(`${key}:${_}${key}`); + namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`; + } + else { + defaultExportRows.push(`${stringify$8(key)}:${_}${serialize(value, options.compact ? null : t, '')}`); + if (options.includeArbitraryNames && isWellFormedString(key)) { + const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`; + namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`; + arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`); + } + } + } + const arbitraryExportCode = arbitraryNameExportRows.length > 0 + ? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}` + : ''; + const defaultExportCode = `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`; + return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`; +}; + +var path$l = require$$0$4; + +var commondir = function (basedir, relfiles) { + if (relfiles) { + var files = relfiles.map(function (r) { + return path$l.resolve(basedir, r); + }); + } + else { + var files = basedir; + } + + var res = files.slice(1).reduce(function (ps, file) { + if (!file.match(/^([A-Za-z]:)?\/|\\/)) { + throw new Error('relative path without a basedir'); + } + + var xs = file.split(/\/+|\\+/); + for ( + var i = 0; + ps[i] === xs[i] && i < Math.min(ps.length, xs.length); + i++ + ); + return ps.slice(0, i); + }, files[0].split(/\/+|\\+/)); + + // Windows correctly handles paths with forward-slashes + return res.length > 1 ? res.join('/') : '/' +}; + +var getCommonDir = /*@__PURE__*/getDefaultExportFromCjs(commondir); + +var old$1 = {}; + +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +var pathModule = require$$0$4; +var isWindows$6 = process.platform === 'win32'; +var fs$k = require$$0__default; + +// JavaScript implementation of realpath, ported from node pre-v6 + +var DEBUG$1 = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG$1) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; + + return callback; + + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } + } + + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } + } + } +} + +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); +} + +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows$6) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} + +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows$6) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} + +old$1.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows$6 && !knownHard[base]) { + fs$k.lstatSync(base); + knownHard[base] = true; + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } + + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs$k.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } + + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows$6) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs$k.statSync(base); + linkTarget = fs$k.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows$6) seenLinks[id] = linkTarget; + } + + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } + + if (cache) cache[original] = p; + + return p; +}; + + +old$1.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } + + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows$6 && !knownHard[base]) { + fs$k.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } + + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } + + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } + + return fs$k.lstat(base, gotStat); + } + + function gotStat(err, stat) { + if (err) return cb(err); + + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } + + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows$6) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs$k.stat(base, function(err) { + if (err) return cb(err); + + fs$k.readlink(base, function(err, target) { + if (!isWindows$6) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } + + function gotTarget(err, target, base) { + if (err) return cb(err); + + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } + + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; + +var fs_realpath = realpath$2; +realpath$2.realpath = realpath$2; +realpath$2.sync = realpathSync; +realpath$2.realpathSync = realpathSync; +realpath$2.monkeypatch = monkeypatch; +realpath$2.unmonkeypatch = unmonkeypatch; + +var fs$j = require$$0__default; +var origRealpath = fs$j.realpath; +var origRealpathSync = fs$j.realpathSync; + +var version$4 = process.version; +var ok = /^v[0-5]\./.test(version$4); +var old = old$1; + +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) +} + +function realpath$2 (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } + + if (typeof cache === 'function') { + cb = cache; + cache = null; + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb); + } else { + cb(er, result); + } + }); +} + +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) + } + + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } + } +} + +function monkeypatch () { + fs$j.realpath = realpath$2; + fs$j.realpathSync = realpathSync; +} + +function unmonkeypatch () { + fs$j.realpath = origRealpath; + fs$j.realpathSync = origRealpathSync; +} + +const isWindows$5 = typeof process === 'object' && + process && + process.platform === 'win32'; +var path$k = isWindows$5 ? { sep: '\\' } : { sep: '/' }; + +var balancedMatch = balanced$1; +function balanced$1(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range$1(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced$1.range = range$1; +function range$1(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + if(a===b) { + return [ai, bi]; + } + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} + +var balanced = balancedMatch; + +var braceExpansion = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand$4(escapeBraces(str), true).map(unescapeBraces); +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand$4(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m) return [str]; + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand$4(m.post, false) + : ['']; + + if (/\$$/.test(m.pre)) { + for (var k = 0; k < post.length; k++) { + var expansion = pre+ '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } else { + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand$4(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand$4(n[0], false).map(embrace); + if (n.length === 1) { + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length); + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = []; + + for (var j = 0; j < n.length; j++) { + N.push.apply(N, expand$4(n[j], false)); + } + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + } + + return expansions; +} + +const minimatch$1 = minimatch_1 = (p, pattern, options = {}) => { + assertValidPattern(pattern); + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + return new Minimatch$1(pattern, options).match(p) +}; + +var minimatch_1 = minimatch$1; + +const path$j = path$k; +minimatch$1.sep = path$j.sep; + +const GLOBSTAR$2 = Symbol('globstar **'); +minimatch$1.GLOBSTAR = GLOBSTAR$2; +const expand$3 = braceExpansion; + +const plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +}; + +// any single thing other than / +// don't need to escape / when using new RegExp() +const qmark = '[^/]'; + +// * => any number of characters +const star = qmark + '*?'; + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; + +// "abc" -> { a:true, b:true, c:true } +const charSet = s => s.split('').reduce((set, c) => { + set[c] = true; + return set +}, {}); + +// characters that need to be escaped in RegExp. +const reSpecials = charSet('().*{}+?[]^$\\!'); + +// characters that indicate we have to add the pattern start +const addPatternStartSet = charSet('[.('); + +// normalizes slashes. +const slashSplit = /\/+/; + +minimatch$1.filter = (pattern, options = {}) => + (p, i, list) => minimatch$1(p, pattern, options); + +const ext = (a, b = {}) => { + const t = {}; + Object.keys(a).forEach(k => t[k] = a[k]); + Object.keys(b).forEach(k => t[k] = b[k]); + return t +}; + +minimatch$1.defaults = def => { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch$1 + } + + const orig = minimatch$1; + + const m = (p, pattern, options) => orig(p, pattern, ext(def, options)); + m.Minimatch = class Minimatch extends orig.Minimatch { + constructor (pattern, options) { + super(pattern, ext(def, options)); + } + }; + m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch; + m.filter = (pattern, options) => orig.filter(pattern, ext(def, options)); + m.defaults = options => orig.defaults(ext(def, options)); + m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options)); + m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options)); + m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options)); + + return m +}; + + + + + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch$1.braceExpand = (pattern, options) => braceExpand(pattern, options); + +const braceExpand = (pattern, options = {}) => { + assertValidPattern(pattern); + + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand$3(pattern) +}; + +const MAX_PATTERN_LENGTH = 1024 * 64; +const assertValidPattern = pattern => { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } + + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } +}; + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +const SUBPARSE = Symbol('subparse'); + +minimatch$1.makeRe = (pattern, options) => + new Minimatch$1(pattern, options || {}).makeRe(); + +minimatch$1.match = (list, pattern, options = {}) => { + const mm = new Minimatch$1(pattern, options); + list = list.filter(f => mm.match(f)); + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + return list +}; + +// replace stuff like \* with * +const globUnescape = s => s.replace(/\\(.)/g, '$1'); +const charUnescape = s => s.replace(/\\([^-\]])/g, '$1'); +const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +const braExpEscape = s => s.replace(/[[\]\\]/g, '\\$&'); + +let Minimatch$1 = class Minimatch { + constructor (pattern, options) { + assertValidPattern(pattern); + + if (!options) options = {}; + + this.options = options; + this.set = []; + this.pattern = pattern; + this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || + options.allowWindowsEscape === false; + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, '/'); + } + this.regexp = null; + this.negate = false; + this.comment = false; + this.empty = false; + this.partial = !!options.partial; + + // make the set of regexps etc. + this.make(); + } + + debug () {} + + make () { + const pattern = this.pattern; + const options = this.options; + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true; + return + } + if (!pattern) { + this.empty = true; + return + } + + // step 1: figure out negation, etc. + this.parseNegate(); + + // step 2: expand braces + let set = this.globSet = this.braceExpand(); + + if (options.debug) this.debug = (...args) => console.error(...args); + + this.debug(this.pattern, set); + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(s => s.split(slashSplit)); + + this.debug(this.pattern, set); + + // glob --> regexps + set = set.map((s, si, set) => s.map(this.parse, this)); + + this.debug(this.pattern, set); + + // filter out everything that didn't compile properly. + set = set.filter(s => s.indexOf(false) === -1); + + this.debug(this.pattern, set); + + this.set = set; + } + + parseNegate () { + if (this.options.nonegate) return + + const pattern = this.pattern; + let negate = false; + let negateOffset = 0; + + for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { + negate = !negate; + negateOffset++; + } + + if (negateOffset) this.pattern = pattern.slice(negateOffset); + this.negate = negate; + } + + // set partial to true to test if, for example, + // "/a/b" matches the start of "/*/b/*/d" + // Partial means, if you run out of file before you run + // out of pattern, then that's fine, as long as all + // the parts match. + matchOne (file, pattern, partial) { + var options = this.options; + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }); + + this.debug('matchOne', file.length, pattern.length); + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop'); + var p = pattern[pi]; + var f = file[fi]; + + this.debug(pattern, p, f); + + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false + + if (p === GLOBSTAR$2) { + this.debug('GLOBSTAR', [pattern, p, f]); + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi; + var pr = pi + 1; + if (pr === pl) { + this.debug('** at the end'); + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr]; + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee); + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr); + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue'); + fr++; + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr); + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit; + if (typeof p === 'string') { + hit = f === p; + this.debug('string match', p, f, hit); + } else { + hit = f.match(p); + this.debug('pattern match', p, f, hit); + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore else */ if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return (fi === fl - 1) && (file[fi] === '') + } + + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') + } + + braceExpand () { + return braceExpand(this.pattern, this.options) + } + + parse (pattern, isSub) { + assertValidPattern(pattern); + + const options = this.options; + + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR$2 + else + pattern = '*'; + } + if (pattern === '') return '' + + let re = ''; + let hasMagic = false; + let escaping = false; + // ? => one single character + const patternListStack = []; + const negativeLists = []; + let stateChar; + let inClass = false; + let reClassStart = -1; + let classStart = -1; + let cs; + let pl; + let sp; + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. However, if the pattern + // starts with ., then traversal patterns can match. + let dotTravAllowed = pattern.charAt(0) === '.'; + let dotFileAllowed = options.dot || dotTravAllowed; + const patternStart = () => + dotTravAllowed + ? '' + : dotFileAllowed + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)'; + const subPatternStart = (p) => + p.charAt(0) === '.' + ? '' + : options.dot + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)'; + + + const clearStateChar = () => { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star; + hasMagic = true; + break + case '?': + re += qmark; + hasMagic = true; + break + default: + re += '\\' + stateChar; + break + } + this.debug('clearStateChar %j %j', stateChar, re); + stateChar = false; + } + }; + + for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c); + + // skip over any that are escaped. + if (escaping) { + /* istanbul ignore next - completely not allowed, even escaped. */ + if (c === '/') { + return false + } + + if (reSpecials[c]) { + re += '\\'; + } + re += c; + escaping = false; + continue + } + + switch (c) { + /* istanbul ignore next */ + case '/': { + // Should already be path-split by now. + return false + } + + case '\\': + if (inClass && pattern.charAt(i + 1) === '-') { + re += c; + continue + } + + clearStateChar(); + escaping = true; + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class'); + if (c === '!' && i === classStart + 1) c = '^'; + re += c; + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + this.debug('call clearStateChar %j', stateChar); + clearStateChar(); + stateChar = c; + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar(); + continue + + case '(': { + if (inClass) { + re += '('; + continue + } + + if (!stateChar) { + re += '\\('; + continue + } + + const plEntry = { + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close, + }; + this.debug(this.pattern, '\t', plEntry); + patternListStack.push(plEntry); + // negation is (?:(?!(?:js)(?:))[^/]*) + re += plEntry.open; + // next entry starts with a dot maybe? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true; + re += subPatternStart(pattern.slice(i + 1)); + } + this.debug('plType %j %j', stateChar, re); + stateChar = false; + continue + } + + case ')': { + const plEntry = patternListStack[patternListStack.length - 1]; + if (inClass || !plEntry) { + re += '\\)'; + continue + } + patternListStack.pop(); + + // closing an extglob + clearStateChar(); + hasMagic = true; + pl = plEntry; + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close; + if (pl.type === '!') { + negativeLists.push(Object.assign(pl, { reEnd: re.length })); + } + continue + } + + case '|': { + const plEntry = patternListStack[patternListStack.length - 1]; + if (inClass || !plEntry) { + re += '\\|'; + continue + } + + clearStateChar(); + re += '|'; + // next subpattern can start with a dot? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true; + re += subPatternStart(pattern.slice(i + 1)); + } + continue + } + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar(); + + if (inClass) { + re += '\\' + c; + continue + } + + inClass = true; + classStart = i; + reClassStart = re.length; + re += c; + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c; + continue + } + + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + cs = pattern.substring(classStart + 1, i); + try { + RegExp('[' + braExpEscape(charUnescape(cs)) + ']'); + // looks good, finish up the class. + re += c; + } catch (er) { + // out of order ranges in JS are errors, but in glob syntax, + // they're just a range that matches nothing. + re = re.substring(0, reClassStart) + '(?:$.)'; // match nothing ever + } + hasMagic = true; + inClass = false; + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar(); + + if (reSpecials[c] && !(c === '^' && inClass)) { + re += '\\'; + } + + re += c; + break + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.slice(classStart + 1); + sp = this.parse(cs, SUBPARSE); + re = re.substring(0, reClassStart) + '\\[' + sp[0]; + hasMagic = hasMagic || sp[1]; + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + let tail; + tail = re.slice(pl.reStart + pl.open.length); + this.debug('setting tail', re, pl); + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { + /* istanbul ignore else - should already be done */ + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\'; + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }); + + this.debug('tail=%j\n %s', tail, tail, pl, re); + const t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type; + + hasMagic = true; + re = re.slice(0, pl.reStart) + t + '\\(' + tail; + } + + // handle trailing things that only matter at the very end. + clearStateChar(); + if (escaping) { + // trailing \\ + re += '\\\\'; + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + const addPatternStart = addPatternStartSet[re.charAt(0)]; + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (let n = negativeLists.length - 1; n > -1; n--) { + const nl = negativeLists[n]; + + const nlBefore = re.slice(0, nl.reStart); + const nlFirst = re.slice(nl.reStart, nl.reEnd - 8); + let nlAfter = re.slice(nl.reEnd); + const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter; + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + const closeParensBefore = nlBefore.split(')').length; + const openParensBefore = nlBefore.split('(').length - closeParensBefore; + let cleanAfter = nlAfter; + for (let i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, ''); + } + nlAfter = cleanAfter; + + const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\/)' : ''; + + re = nlBefore + nlFirst + nlAfter + dollar + nlLast; + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re; + } + + if (addPatternStart) { + re = patternStart() + re; + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // if it's nocase, and the lcase/uppercase don't match, it's magic + if (options.nocase && !hasMagic) { + hasMagic = pattern.toUpperCase() !== pattern.toLowerCase(); + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + const flags = options.nocase ? 'i' : ''; + try { + return Object.assign(new RegExp('^' + re + '$', flags), { + _glob: pattern, + _src: re, + }) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + } + + makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + const set = this.set; + + if (!set.length) { + this.regexp = false; + return this.regexp + } + const options = this.options; + + const twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot; + const flags = options.nocase ? 'i' : ''; + + // coalesce globstars and regexpify non-globstar patterns + // if it's the only item, then we just do one twoStar + // if it's the first, and there are more, prepend (\/|twoStar\/)? to next + // if it's the last, append (\/twoStar|) to previous + // if it's in the middle, append (\/|\/twoStar\/) to previous + // then filter out GLOBSTAR symbols + let re = set.map(pattern => { + pattern = pattern.map(p => + typeof p === 'string' ? regExpEscape(p) + : p === GLOBSTAR$2 ? GLOBSTAR$2 + : p._src + ).reduce((set, p) => { + if (!(set[set.length - 1] === GLOBSTAR$2 && p === GLOBSTAR$2)) { + set.push(p); + } + return set + }, []); + pattern.forEach((p, i) => { + if (p !== GLOBSTAR$2 || pattern[i-1] === GLOBSTAR$2) { + return + } + if (i === 0) { + if (pattern.length > 1) { + pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1]; + } else { + pattern[i] = twoStar; + } + } else if (i === pattern.length - 1) { + pattern[i-1] += '(?:\\\/|' + twoStar + ')?'; + } else { + pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1]; + pattern[i+1] = GLOBSTAR$2; + } + }); + return pattern.filter(p => p !== GLOBSTAR$2).join('/') + }).join('|'); + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$'; + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$'; + + try { + this.regexp = new RegExp(re, flags); + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false; + } + return this.regexp + } + + match (f, partial = this.partial) { + this.debug('match', f, this.pattern); + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + const options = this.options; + + // windows: need to use /, not \ + if (path$j.sep !== '/') { + f = f.split(path$j.sep).join('/'); + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit); + this.debug(this.pattern, 'split', f); + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + const set = this.set; + this.debug(this.pattern, 'set', set); + + // Find the basename of the path by looking for the last non-empty segment + let filename; + for (let i = f.length - 1; i >= 0; i--) { + filename = f[i]; + if (filename) break + } + + for (let i = 0; i < set.length; i++) { + const pattern = set[i]; + let file = f; + if (options.matchBase && pattern.length === 1) { + file = [filename]; + } + const hit = this.matchOne(file, pattern, partial); + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate + } + + static defaults (def) { + return minimatch$1.defaults(def).Minimatch + } +}; + +minimatch$1.Minimatch = Minimatch$1; + +var inherits = {exports: {}}; + +var inherits_browser = {exports: {}}; + +var hasRequiredInherits_browser; + +function requireInherits_browser () { + if (hasRequiredInherits_browser) return inherits_browser.exports; + hasRequiredInherits_browser = 1; + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + inherits_browser.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; + } else { + // old school shim for old browsers + inherits_browser.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; + } + return inherits_browser.exports; +} + +try { + var util$2 = require('util'); + /* istanbul ignore next */ + if (typeof util$2.inherits !== 'function') throw ''; + inherits.exports = util$2.inherits; +} catch (e) { + /* istanbul ignore next */ + inherits.exports = requireInherits_browser(); +} + +var inheritsExports = inherits.exports; + +var common$c = {}; + +common$c.setopts = setopts; +common$c.ownProp = ownProp; +common$c.makeAbs = makeAbs; +common$c.finish = finish; +common$c.mark = mark; +common$c.isIgnored = isIgnored; +common$c.childrenIgnored = childrenIgnored; + +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} + +var fs$i = require$$0__default; +var path$i = require$$0$4; +var minimatch = minimatch_1; +var isAbsolute = require$$0$4.isAbsolute; +var Minimatch = minimatch.Minimatch; + +function alphasort (a, b) { + return a.localeCompare(b, 'en') +} + +function setupIgnores (self, options) { + self.ignore = options.ignore || []; + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore]; + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap); + } +} + +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null; + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, ''); + gmatcher = new Minimatch(gpattern, { dot: true }); + } + + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher + } +} + +function setopts (self, pattern, options) { + if (!options) + options = {}; + + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern; + } + + self.windowsPathsNoEscape = !!options.windowsPathsNoEscape || + options.allowWindowsEscape === false; + if (self.windowsPathsNoEscape) { + pattern = pattern.replace(/\\/g, '/'); + } + + self.silent = !!options.silent; + self.pattern = pattern; + self.strict = options.strict !== false; + self.realpath = !!options.realpath; + self.realpathCache = options.realpathCache || Object.create(null); + self.follow = !!options.follow; + self.dot = !!options.dot; + self.mark = !!options.mark; + self.nodir = !!options.nodir; + if (self.nodir) + self.mark = true; + self.sync = !!options.sync; + self.nounique = !!options.nounique; + self.nonull = !!options.nonull; + self.nosort = !!options.nosort; + self.nocase = !!options.nocase; + self.stat = !!options.stat; + self.noprocess = !!options.noprocess; + self.absolute = !!options.absolute; + self.fs = options.fs || fs$i; + + self.maxLength = options.maxLength || Infinity; + self.cache = options.cache || Object.create(null); + self.statCache = options.statCache || Object.create(null); + self.symlinks = options.symlinks || Object.create(null); + + setupIgnores(self, options); + + self.changedCwd = false; + var cwd = process.cwd(); + if (!ownProp(options, "cwd")) + self.cwd = path$i.resolve(cwd); + else { + self.cwd = path$i.resolve(options.cwd); + self.changedCwd = self.cwd !== cwd; + } + + self.root = options.root || path$i.resolve(self.cwd, "/"); + self.root = path$i.resolve(self.root); + + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd); + self.nomount = !!options.nomount; + + if (process.platform === "win32") { + self.root = self.root.replace(/\\/g, "/"); + self.cwd = self.cwd.replace(/\\/g, "/"); + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/"); + } + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true; + options.nocomment = true; + + self.minimatch = new Minimatch(pattern, options); + self.options = self.minimatch.options; +} + +function finish (self) { + var nou = self.nounique; + var all = nou ? [] : Object.create(null); + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i]; + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i]; + if (nou) + all.push(literal); + else + all[literal] = true; + } + } else { + // had matches + var m = Object.keys(matches); + if (nou) + all.push.apply(all, m); + else + m.forEach(function (m) { + all[m] = true; + }); + } + } + + if (!nou) + all = Object.keys(all); + + if (!self.nosort) + all = all.sort(alphasort); + + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]); + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)); + var c = self.cache[e] || self.cache[makeAbs(self, e)]; + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c); + return notDir + }); + } + } + + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }); + + self.found = all; +} + +function mark (self, p) { + var abs = makeAbs(self, p); + var c = self.cache[abs]; + var m = p; + if (c) { + var isDir = c === 'DIR' || Array.isArray(c); + var slash = p.slice(-1) === '/'; + + if (isDir && !slash) + m += '/'; + else if (!isDir && slash) + m = m.slice(0, -1); + + if (m !== p) { + var mabs = makeAbs(self, m); + self.statCache[mabs] = self.statCache[abs]; + self.cache[mabs] = self.cache[abs]; + } + } + + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f; + if (f.charAt(0) === '/') { + abs = path$i.join(self.root, f); + } else if (isAbsolute(f) || f === '') { + abs = f; + } else if (self.changedCwd) { + abs = path$i.resolve(self.cwd, f); + } else { + abs = path$i.resolve(f); + } + + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/'); + + return abs +} + + +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +var sync$9; +var hasRequiredSync; + +function requireSync () { + if (hasRequiredSync) return sync$9; + hasRequiredSync = 1; + sync$9 = globSync; + globSync.GlobSync = GlobSync; + + var rp = fs_realpath; + var minimatch = minimatch_1; + requireGlob().Glob; + var path = require$$0$4; + var assert = require$$5; + var isAbsolute = require$$0$4.isAbsolute; + var common = common$c; + var setopts = common.setopts; + var ownProp = common.ownProp; + var childrenIgnored = common.childrenIgnored; + var isIgnored = common.isIgnored; + + function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found + } + + function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) + + setopts(this, pattern, options); + + if (this.noprocess) + return this + + var n = this.minimatch.set.length; + this.matches = new Array(n); + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false); + } + this._finish(); + } + + GlobSync.prototype._finish = function () { + assert.ok(this instanceof GlobSync); + if (this.realpath) { + var self = this; + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null); + for (var p in matchset) { + try { + p = self._makeAbs(p); + var real = rp.realpathSync(p, self.realpathCache); + set[real] = true; + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true; + else + throw er + } + } + }); + } + common.finish(this); + }; + + + GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert.ok(this instanceof GlobSync); + + // Get the first [n] parts of pattern that are all strings. + var n = 0; + while (typeof pattern[n] === 'string') { + n ++; + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix; + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index); + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null; + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/'); + break + } + + var remain = pattern.slice(n); + + // get the list of entries. + var read; + if (prefix === null) + read = '.'; + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix; + read = prefix; + } else + read = prefix; + + var abs = this._makeAbs(read); + + //if ignored, skip processing + if (childrenIgnored(this, read)) + return + + var isGlobStar = remain[0] === minimatch.GLOBSTAR; + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar); + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar); + }; + + + GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar); + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0]; + var negate = !!this.minimatch.negate; + var rawGlob = pn._glob; + var dotOk = this.dot || rawGlob.charAt(0) === '.'; + + var matchedEntries = []; + for (var i = 0; i < entries.length; i++) { + var e = entries[i]; + if (e.charAt(0) !== '.' || dotOk) { + var m; + if (negate && !prefix) { + m = !e.match(pn); + } else { + m = e.match(pn); + } + if (m) + matchedEntries.push(e); + } + } + + var len = matchedEntries.length; + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e); + } + this._emitMatch(index, e); + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift(); + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + var newPattern; + if (prefix) + newPattern = [prefix, e]; + else + newPattern = [e]; + this._process(newPattern.concat(remain), index, inGlobStar); + } + }; + + + GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return + + var abs = this._makeAbs(e); + + if (this.mark) + e = this._mark(e); + + if (this.absolute) { + e = abs; + } + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs]; + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true; + + if (this.stat) + this._stat(e); + }; + + + GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries; + var lstat; + try { + lstat = this.fs.lstatSync(abs); + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } + + var isSym = lstat && lstat.isSymbolicLink(); + this.symlinks[abs] = isSym; + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE'; + else + entries = this._readdir(abs, false); + + return entries + }; + + GlobSync.prototype._readdir = function (abs, inGlobStar) { + + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs]; + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, this.fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er); + return null + } + }; + + GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i]; + if (abs === '/') + e = abs + e; + else + e = abs + '/' + e; + this.cache[e] = true; + } + } + + this.cache[abs] = entries; + + // mark and cache dir-ness + return entries + }; + + GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f); + this.cache[abs] = 'FILE'; + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd); + error.path = this.cwd; + error.code = er.code; + throw error + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false; + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false; + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er); + break + } + }; + + GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar); + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1); + var gspref = prefix ? [ prefix ] : []; + var noGlobStar = gspref.concat(remainWithoutGlobStar); + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false); + + var len = entries.length; + var isSym = this.symlinks[abs]; + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i]; + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar); + this._process(instead, index, true); + + var below = gspref.concat(entries[i], remain); + this._process(below, index, true); + } + }; + + GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix); + + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix); + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix); + } else { + prefix = path.resolve(this.root, prefix); + if (trail) + prefix += '/'; + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/'); + + // Mark this as a match + this._emitMatch(index, prefix); + }; + + // Returns either 'DIR', 'FILE', or false + GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f); + var needDir = f.slice(-1) === '/'; + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs]; + + if (Array.isArray(c)) + c = 'DIR'; + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + var stat = this.statCache[abs]; + if (!stat) { + var lstat; + try { + lstat = this.fs.lstatSync(abs); + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false; + return false + } + } + + if (lstat && lstat.isSymbolicLink()) { + try { + stat = this.fs.statSync(abs); + } catch (er) { + stat = lstat; + } + } else { + stat = lstat; + } + } + + this.statCache[abs] = stat; + + var c = true; + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE'; + + this.cache[abs] = this.cache[abs] || c; + + if (needDir && c === 'FILE') + return false + + return c + }; + + GlobSync.prototype._mark = function (p) { + return common.mark(this, p) + }; + + GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) + }; + return sync$9; +} + +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +var wrappy_1 = wrappy$2; +function wrappy$2 (fn, cb) { + if (fn && cb) return wrappy$2(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k]; + }); + + return wrapper + + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + var ret = fn.apply(this, args); + var cb = args[args.length-1]; + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k]; + }); + } + return ret + } +} + +var once$2 = {exports: {}}; + +var wrappy$1 = wrappy_1; +once$2.exports = wrappy$1(once$1); +once$2.exports.strict = wrappy$1(onceStrict); + +once$1.proto = once$1(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once$1(this) + }, + configurable: true + }); + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }); +}); + +function once$1 (fn) { + var f = function () { + if (f.called) return f.value + f.called = true; + return f.value = fn.apply(this, arguments) + }; + f.called = false; + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true; + return f.value = fn.apply(this, arguments) + }; + var name = fn.name || 'Function wrapped with `once`'; + f.onceError = name + " shouldn't be called more than once"; + f.called = false; + return f +} + +var onceExports = once$2.exports; + +var wrappy = wrappy_1; +var reqs = Object.create(null); +var once = onceExports; + +var inflight_1 = wrappy(inflight); + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb); + return null + } else { + reqs[key] = [cb]; + return makeres(key) + } +} + +function makeres (key) { + return once(function RES () { + var cbs = reqs[key]; + var len = cbs.length; + var args = slice$3(arguments); + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args); + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len); + process.nextTick(function () { + RES.apply(null, args); + }); + } else { + delete reqs[key]; + } + } + }) +} + +function slice$3 (args) { + var length = args.length; + var array = []; + + for (var i = 0; i < length; i++) array[i] = args[i]; + return array +} + +var glob_1; +var hasRequiredGlob; + +function requireGlob () { + if (hasRequiredGlob) return glob_1; + hasRequiredGlob = 1; + // Approach: + // + // 1. Get the minimatch set + // 2. For each pattern in the set, PROCESS(pattern, false) + // 3. Store matches per-set, then uniq them + // + // PROCESS(pattern, inGlobStar) + // Get the first [n] items from pattern that are all strings + // Join these together. This is PREFIX. + // If there is no more remaining, then stat(PREFIX) and + // add to matches if it succeeds. END. + // + // If inGlobStar and PREFIX is symlink and points to dir + // set ENTRIES = [] + // else readdir(PREFIX) as ENTRIES + // If fail, END + // + // with ENTRIES + // If pattern[n] is GLOBSTAR + // // handle the case where the globstar match is empty + // // by pruning it out, and testing the resulting pattern + // PROCESS(pattern[0..n] + pattern[n+1 .. $], false) + // // handle other cases. + // for ENTRY in ENTRIES (not dotfiles) + // // attach globstar + tail onto the entry + // // Mark that this entry is a globstar match + // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) + // + // else // not globstar + // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) + // Test ENTRY against pattern[n] + // If fails, continue + // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) + // + // Caveat: + // Cache all stats and readdirs results to minimize syscall. Since all + // we ever care about is existence and directory-ness, we can just keep + // `true` for files, and [children,...] for directories, or `false` for + // things that don't exist. + + glob_1 = glob; + + var rp = fs_realpath; + var minimatch = minimatch_1; + var inherits = inheritsExports; + var EE = require$$0$5.EventEmitter; + var path = require$$0$4; + var assert = require$$5; + var isAbsolute = require$$0$4.isAbsolute; + var globSync = requireSync(); + var common = common$c; + var setopts = common.setopts; + var ownProp = common.ownProp; + var inflight = inflight_1; + var childrenIgnored = common.childrenIgnored; + var isIgnored = common.isIgnored; + + var once = onceExports; + + function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {}; + if (!options) options = {}; + + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } + + return new Glob(pattern, options, cb) + } + + glob.sync = globSync; + var GlobSync = glob.GlobSync = globSync.GlobSync; + + // old api surface + glob.glob = glob; + + function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin + } + + glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_); + options.noprocess = true; + + var g = new Glob(pattern, options); + var set = g.minimatch.set; + + if (!pattern) + return false + + if (set.length > 1) + return true + + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } + + return false + }; + + glob.Glob = Glob; + inherits(Glob, EE); + function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options; + options = null; + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts(this, pattern, options); + this._didRealPath = false; + + // process each pattern in the minimatch set + var n = this.minimatch.set.length; + + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n); + + if (typeof cb === 'function') { + cb = once(cb); + this.on('error', cb); + this.on('end', function (matches) { + cb(null, matches); + }); + } + + var self = this; + this._processing = 0; + + this._emitQueue = []; + this._processQueue = []; + this.paused = false; + + if (this.noprocess) + return this + + if (n === 0) + return done() + + var sync = true; + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done); + } + sync = false; + + function done () { + --self._processing; + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish(); + }); + } else { + self._finish(); + } + } + } + } + + Glob.prototype._finish = function () { + assert(this instanceof Glob); + if (this.aborted) + return + + if (this.realpath && !this._didRealpath) + return this._realpath() + + common.finish(this); + this.emit('end', this.found); + }; + + Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true; + + var n = this.matches.length; + if (n === 0) + return this._finish() + + var self = this; + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next); + + function next () { + if (--n === 0) + self._finish(); + } + }; + + Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index]; + if (!matchset) + return cb() + + var found = Object.keys(matchset); + var self = this; + var n = found.length; + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null); + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p); + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true; + else if (er.syscall === 'stat') + set[p] = true; + else + self.emit('error', er); // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set; + cb(); + } + }); + }); + }; + + Glob.prototype._mark = function (p) { + return common.mark(this, p) + }; + + Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) + }; + + Glob.prototype.abort = function () { + this.aborted = true; + this.emit('abort'); + }; + + Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true; + this.emit('pause'); + } + }; + + Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume'); + this.paused = false; + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0); + this._emitQueue.length = 0; + for (var i = 0; i < eq.length; i ++) { + var e = eq[i]; + this._emitMatch(e[0], e[1]); + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0); + this._processQueue.length = 0; + for (var i = 0; i < pq.length; i ++) { + var p = pq[i]; + this._processing--; + this._process(p[0], p[1], p[2], p[3]); + } + } + } + }; + + Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob); + assert(typeof cb === 'function'); + + if (this.aborted) + return + + this._processing++; + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]); + return + } + + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0; + while (typeof pattern[n] === 'string') { + n ++; + } + // now n is the index of the first one that is *not* a string. + + // see if there's anything else + var prefix; + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb); + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null; + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/'); + break + } + + var remain = pattern.slice(n); + + // get the list of entries. + var read; + if (prefix === null) + read = '.'; + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix; + read = prefix; + } else + read = prefix; + + var abs = this._makeAbs(read); + + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch.GLOBSTAR; + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb); + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb); + }; + + Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this; + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }); + }; + + Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0]; + var negate = !!this.minimatch.negate; + var rawGlob = pn._glob; + var dotOk = this.dot || rawGlob.charAt(0) === '.'; + + var matchedEntries = []; + for (var i = 0; i < entries.length; i++) { + var e = entries[i]; + if (e.charAt(0) !== '.' || dotOk) { + var m; + if (negate && !prefix) { + m = !e.match(pn); + } else { + m = e.match(pn); + } + if (m) + matchedEntries.push(e); + } + } + + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + + var len = matchedEntries.length; + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e); + } + this._emitMatch(index, e); + } + // This was the last one, and no stats were needed + return cb() + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift(); + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i]; + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e; + else + e = prefix + e; + } + this._process([e].concat(remain), index, inGlobStar, cb); + } + cb(); + }; + + Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return + + if (isIgnored(this, e)) + return + + if (this.paused) { + this._emitQueue.push([index, e]); + return + } + + var abs = isAbsolute(e) ? e : this._makeAbs(e); + + if (this.mark) + e = this._mark(e); + + if (this.absolute) + e = abs; + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs]; + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true; + + var st = this.statCache[abs]; + if (st) + this.emit('stat', e, st); + + this.emit('match', e); + }; + + Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) + + var lstatkey = 'lstat\0' + abs; + var self = this; + var lstatcb = inflight(lstatkey, lstatcb_); + + if (lstatcb) + self.fs.lstat(abs, lstatcb); + + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() + + var isSym = lstat && lstat.isSymbolicLink(); + self.symlinks[abs] = isSym; + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE'; + cb(); + } else + self._readdir(abs, false, cb); + } + }; + + Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb); + if (!cb) + return + + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs]; + if (!c || c === 'FILE') + return cb() + + if (Array.isArray(c)) + return cb(null, c) + } + + var self = this; + self.fs.readdir(abs, readdirCb(this, abs, cb)); + }; + + function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb); + else + self._readdirEntries(abs, entries, cb); + } + } + + Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i]; + if (abs === '/') + e = abs + e; + else + e = abs + '/' + e; + this.cache[e] = true; + } + } + + this.cache[abs] = entries; + return cb(null, entries) + }; + + Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f); + this.cache[abs] = 'FILE'; + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd); + error.path = this.cwd; + error.code = er.code; + this.emit('error', error); + this.abort(); + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false; + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false; + if (this.strict) { + this.emit('error', er); + // If the error is handled, then we abort + // if not, we threw out of here + this.abort(); + } + if (!this.silent) + console.error('glob error', er); + break + } + + return cb() + }; + + Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this; + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb); + }); + }; + + + Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1); + var gspref = prefix ? [ prefix ] : []; + var noGlobStar = gspref.concat(remainWithoutGlobStar); + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb); + + var isSym = this.symlinks[abs]; + var len = entries.length; + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() + + for (var i = 0; i < len; i++) { + var e = entries[i]; + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar); + this._process(instead, index, true, cb); + + var below = gspref.concat(entries[i], remain); + this._process(below, index, true, cb); + } + + cb(); + }; + + Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this; + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb); + }); + }; + Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + + //console.error('ps2', prefix, exists) + + if (!this.matches[index]) + this.matches[index] = Object.create(null); + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix); + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix); + } else { + prefix = path.resolve(this.root, prefix); + if (trail) + prefix += '/'; + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/'); + + // Mark this as a match + this._emitMatch(index, prefix); + cb(); + }; + + // Returns either 'DIR', 'FILE', or false + Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f); + var needDir = f.slice(-1) === '/'; + + if (f.length > this.maxLength) + return cb() + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs]; + + if (Array.isArray(c)) + c = 'DIR'; + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) + + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + var stat = this.statCache[abs]; + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE'; + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } + + var self = this; + var statcb = inflight('stat\0' + abs, lstatcb_); + if (statcb) + self.fs.lstat(abs, statcb); + + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return self.fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb); + else + self._stat2(f, abs, er, stat, cb); + }) + } else { + self._stat2(f, abs, er, lstat, cb); + } + } + }; + + Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false; + return cb() + } + + var needDir = f.slice(-1) === '/'; + this.statCache[abs] = stat; + + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) + + var c = true; + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE'; + this.cache[abs] = this.cache[abs] || c; + + if (needDir && c === 'FILE') + return cb() + + return cb(null, c, stat) + }; + return glob_1; +} + +var globExports = requireGlob(); +var glob$1 = /*@__PURE__*/getDefaultExportFromCjs(globExports); + +const comma = ','.charCodeAt(0); +const semicolon = ';'.charCodeAt(0); +const chars$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII +for (let i = 0; i < chars$1.length; i++) { + const c = chars$1.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +// Provide a fallback for older environments. +const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; +function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; +} +function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} +function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; +} +function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; +} +function sort(line) { + line.sort(sortComparator$1); +} +function sortComparator$1(a, b) { + return a[0] - b[0]; +} +function encode$1(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); +} +function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; +} + +class BitSet { + constructor(arg) { + this.bits = arg instanceof BitSet ? arg.bits.slice() : []; + } + + add(n) { + this.bits[n >> 5] |= 1 << (n & 31); + } + + has(n) { + return !!(this.bits[n >> 5] & (1 << (n & 31))); + } +} + +class Chunk { + constructor(start, end, content) { + this.start = start; + this.end = end; + this.original = content; + + this.intro = ''; + this.outro = ''; + + this.content = content; + this.storeName = false; + this.edited = false; + + { + this.previous = null; + this.next = null; + } + } + + appendLeft(content) { + this.outro += content; + } + + appendRight(content) { + this.intro = this.intro + content; + } + + clone() { + const chunk = new Chunk(this.start, this.end, this.original); + + chunk.intro = this.intro; + chunk.outro = this.outro; + chunk.content = this.content; + chunk.storeName = this.storeName; + chunk.edited = this.edited; + + return chunk; + } + + contains(index) { + return this.start < index && index < this.end; + } + + eachNext(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.next; + } + } + + eachPrevious(fn) { + let chunk = this; + while (chunk) { + fn(chunk); + chunk = chunk.previous; + } + } + + edit(content, storeName, contentOnly) { + this.content = content; + if (!contentOnly) { + this.intro = ''; + this.outro = ''; + } + this.storeName = storeName; + + this.edited = true; + + return this; + } + + prependLeft(content) { + this.outro = content + this.outro; + } + + prependRight(content) { + this.intro = content + this.intro; + } + + split(index) { + const sliceIndex = index - this.start; + + const originalBefore = this.original.slice(0, sliceIndex); + const originalAfter = this.original.slice(sliceIndex); + + this.original = originalBefore; + + const newChunk = new Chunk(index, this.end, originalAfter); + newChunk.outro = this.outro; + this.outro = ''; + + this.end = index; + + if (this.edited) { + // after split we should save the edit content record into the correct chunk + // to make sure sourcemap correct + // For example: + // ' test'.trim() + // split -> ' ' + 'test' + // ✔️ edit -> '' + 'test' + // ✖️ edit -> 'test' + '' + // TODO is this block necessary?... + newChunk.edit('', false); + this.content = ''; + } else { + this.content = originalBefore; + } + + newChunk.next = this.next; + if (newChunk.next) newChunk.next.previous = newChunk; + newChunk.previous = this; + this.next = newChunk; + + return newChunk; + } + + toString() { + return this.intro + this.content + this.outro; + } + + trimEnd(rx) { + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + this.split(this.start + trimmed.length).edit('', undefined, true); + if (this.edited) { + // save the change, if it has been edited + this.edit(trimmed, this.storeName, true); + } + } + return true; + } else { + this.edit('', undefined, true); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + } + } + + trimStart(rx) { + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + const trimmed = this.content.replace(rx, ''); + + if (trimmed.length) { + if (trimmed !== this.content) { + const newChunk = this.split(this.end - trimmed.length); + if (this.edited) { + // save the change, if it has been edited + newChunk.edit(trimmed, this.storeName, true); + } + this.edit('', undefined, true); + } + return true; + } else { + this.edit('', undefined, true); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + } + } +} + +function getBtoa() { + if (typeof window !== 'undefined' && typeof window.btoa === 'function') { + return (str) => window.btoa(unescape(encodeURIComponent(str))); + } else if (typeof Buffer === 'function') { + return (str) => Buffer.from(str, 'utf-8').toString('base64'); + } else { + return () => { + throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.'); + }; + } +} + +const btoa$1 = /*#__PURE__*/ getBtoa(); + +let SourceMap$1 = class SourceMap { + constructor(properties) { + this.version = 3; + this.file = properties.file; + this.sources = properties.sources; + this.sourcesContent = properties.sourcesContent; + this.names = properties.names; + this.mappings = encode$1(properties.mappings); + if (typeof properties.x_google_ignoreList !== 'undefined') { + this.x_google_ignoreList = properties.x_google_ignoreList; + } + } + + toString() { + return JSON.stringify(this); + } + + toUrl() { + return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString()); + } +}; + +function guessIndent(code) { + const lines = code.split('\n'); + + const tabbed = lines.filter((line) => /^\t+/.test(line)); + const spaced = lines.filter((line) => /^ {2,}/.test(line)); + + if (tabbed.length === 0 && spaced.length === 0) { + return null; + } + + // More lines tabbed than spaced? Assume tabs, and + // default to tabs in the case of a tie (or nothing + // to go on) + if (tabbed.length >= spaced.length) { + return '\t'; + } + + // Otherwise, we need to guess the multiple + const min = spaced.reduce((previous, current) => { + const numSpaces = /^ +/.exec(current)[0].length; + return Math.min(numSpaces, previous); + }, Infinity); + + return new Array(min + 1).join(' '); +} + +function getRelativePath(from, to) { + const fromParts = from.split(/[/\\]/); + const toParts = to.split(/[/\\]/); + + fromParts.pop(); // get dirname + + while (fromParts[0] === toParts[0]) { + fromParts.shift(); + toParts.shift(); + } + + if (fromParts.length) { + let i = fromParts.length; + while (i--) fromParts[i] = '..'; + } + + return fromParts.concat(toParts).join('/'); +} + +const toString$3 = Object.prototype.toString; + +function isObject$2(thing) { + return toString$3.call(thing) === '[object Object]'; +} + +function getLocator(source) { + const originalLines = source.split('\n'); + const lineOffsets = []; + + for (let i = 0, pos = 0; i < originalLines.length; i++) { + lineOffsets.push(pos); + pos += originalLines[i].length + 1; + } + + return function locate(index) { + let i = 0; + let j = lineOffsets.length; + while (i < j) { + const m = (i + j) >> 1; + if (index < lineOffsets[m]) { + j = m; + } else { + i = m + 1; + } + } + const line = i - 1; + const column = index - lineOffsets[line]; + return { line, column }; + }; +} + +const wordRegex = /\w/; + +class Mappings { + constructor(hires) { + this.hires = hires; + this.generatedCodeLine = 0; + this.generatedCodeColumn = 0; + this.raw = []; + this.rawSegments = this.raw[this.generatedCodeLine] = []; + this.pending = null; + } + + addEdit(sourceIndex, content, loc, nameIndex) { + if (content.length) { + let contentLineEnd = content.indexOf('\n', 0); + let previousContentLineEnd = -1; + while (contentLineEnd >= 0) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + + previousContentLineEnd = contentLineEnd; + contentLineEnd = content.indexOf('\n', contentLineEnd + 1); + } + + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + if (nameIndex >= 0) { + segment.push(nameIndex); + } + this.rawSegments.push(segment); + + this.advance(content.slice(previousContentLineEnd + 1)); + } else if (this.pending) { + this.rawSegments.push(this.pending); + this.advance(content); + } + + this.pending = null; + } + + addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) { + let originalCharIndex = chunk.start; + let first = true; + // when iterating each char, check if it's in a word boundary + let charInHiresBoundary = false; + + while (originalCharIndex < chunk.end) { + if (this.hires || first || sourcemapLocations.has(originalCharIndex)) { + const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column]; + + if (this.hires === 'boundary') { + // in hires "boundary", group segments per word boundary than per char + if (wordRegex.test(original[originalCharIndex])) { + // for first char in the boundary found, start the boundary by pushing a segment + if (!charInHiresBoundary) { + this.rawSegments.push(segment); + charInHiresBoundary = true; + } + } else { + // for non-word char, end the boundary by pushing a segment + this.rawSegments.push(segment); + charInHiresBoundary = false; + } + } else { + this.rawSegments.push(segment); + } + } + + if (original[originalCharIndex] === '\n') { + loc.line += 1; + loc.column = 0; + this.generatedCodeLine += 1; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + this.generatedCodeColumn = 0; + first = true; + } else { + loc.column += 1; + this.generatedCodeColumn += 1; + first = false; + } + + originalCharIndex += 1; + } + + this.pending = null; + } + + advance(str) { + if (!str) return; + + const lines = str.split('\n'); + + if (lines.length > 1) { + for (let i = 0; i < lines.length - 1; i++) { + this.generatedCodeLine++; + this.raw[this.generatedCodeLine] = this.rawSegments = []; + } + this.generatedCodeColumn = 0; + } + + this.generatedCodeColumn += lines[lines.length - 1].length; + } +} + +const n$1 = '\n'; + +const warned = { + insertLeft: false, + insertRight: false, + storeName: false, +}; + +class MagicString { + constructor(string, options = {}) { + const chunk = new Chunk(0, string.length, string); + + Object.defineProperties(this, { + original: { writable: true, value: string }, + outro: { writable: true, value: '' }, + intro: { writable: true, value: '' }, + firstChunk: { writable: true, value: chunk }, + lastChunk: { writable: true, value: chunk }, + lastSearchedChunk: { writable: true, value: chunk }, + byStart: { writable: true, value: {} }, + byEnd: { writable: true, value: {} }, + filename: { writable: true, value: options.filename }, + indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, + sourcemapLocations: { writable: true, value: new BitSet() }, + storedNames: { writable: true, value: {} }, + indentStr: { writable: true, value: undefined }, + ignoreList: { writable: true, value: options.ignoreList }, + }); + + this.byStart[0] = chunk; + this.byEnd[string.length] = chunk; + } + + addSourcemapLocation(char) { + this.sourcemapLocations.add(char); + } + + append(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.outro += content; + return this; + } + + appendLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.appendLeft(content); + } else { + this.intro += content; + } + return this; + } + + appendRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.appendRight(content); + } else { + this.outro += content; + } + return this; + } + + clone() { + const cloned = new MagicString(this.original, { filename: this.filename }); + + let originalChunk = this.firstChunk; + let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone()); + + while (originalChunk) { + cloned.byStart[clonedChunk.start] = clonedChunk; + cloned.byEnd[clonedChunk.end] = clonedChunk; + + const nextOriginalChunk = originalChunk.next; + const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); + + if (nextClonedChunk) { + clonedChunk.next = nextClonedChunk; + nextClonedChunk.previous = clonedChunk; + + clonedChunk = nextClonedChunk; + } + + originalChunk = nextOriginalChunk; + } + + cloned.lastChunk = clonedChunk; + + if (this.indentExclusionRanges) { + cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); + } + + cloned.sourcemapLocations = new BitSet(this.sourcemapLocations); + + cloned.intro = this.intro; + cloned.outro = this.outro; + + return cloned; + } + + generateDecodedMap(options) { + options = options || {}; + + const sourceIndex = 0; + const names = Object.keys(this.storedNames); + const mappings = new Mappings(options.hires); + + const locate = getLocator(this.original); + + if (this.intro) { + mappings.advance(this.intro); + } + + this.firstChunk.eachNext((chunk) => { + const loc = locate(chunk.start); + + if (chunk.intro.length) mappings.advance(chunk.intro); + + if (chunk.edited) { + mappings.addEdit( + sourceIndex, + chunk.content, + loc, + chunk.storeName ? names.indexOf(chunk.original) : -1, + ); + } else { + mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations); + } + + if (chunk.outro.length) mappings.advance(chunk.outro); + }); + + return { + file: options.file ? options.file.split(/[/\\]/).pop() : undefined, + sources: [ + options.source ? getRelativePath(options.file || '', options.source) : options.file || '', + ], + sourcesContent: options.includeContent ? [this.original] : undefined, + names, + mappings: mappings.raw, + x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined, + }; + } + + generateMap(options) { + return new SourceMap$1(this.generateDecodedMap(options)); + } + + _ensureindentStr() { + if (this.indentStr === undefined) { + this.indentStr = guessIndent(this.original); + } + } + + _getRawIndentString() { + this._ensureindentStr(); + return this.indentStr; + } + + getIndentString() { + this._ensureindentStr(); + return this.indentStr === null ? '\t' : this.indentStr; + } + + indent(indentStr, options) { + const pattern = /^[^\r\n]/gm; + + if (isObject$2(indentStr)) { + options = indentStr; + indentStr = undefined; + } + + if (indentStr === undefined) { + this._ensureindentStr(); + indentStr = this.indentStr || '\t'; + } + + if (indentStr === '') return this; // noop + + options = options || {}; + + // Process exclusion ranges + const isExcluded = {}; + + if (options.exclude) { + const exclusions = + typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude; + exclusions.forEach((exclusion) => { + for (let i = exclusion[0]; i < exclusion[1]; i += 1) { + isExcluded[i] = true; + } + }); + } + + let shouldIndentNextCharacter = options.indentStart !== false; + const replacer = (match) => { + if (shouldIndentNextCharacter) return `${indentStr}${match}`; + shouldIndentNextCharacter = true; + return match; + }; + + this.intro = this.intro.replace(pattern, replacer); + + let charIndex = 0; + let chunk = this.firstChunk; + + while (chunk) { + const end = chunk.end; + + if (chunk.edited) { + if (!isExcluded[charIndex]) { + chunk.content = chunk.content.replace(pattern, replacer); + + if (chunk.content.length) { + shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n'; + } + } + } else { + charIndex = chunk.start; + + while (charIndex < end) { + if (!isExcluded[charIndex]) { + const char = this.original[charIndex]; + + if (char === '\n') { + shouldIndentNextCharacter = true; + } else if (char !== '\r' && shouldIndentNextCharacter) { + shouldIndentNextCharacter = false; + + if (charIndex === chunk.start) { + chunk.prependRight(indentStr); + } else { + this._splitChunk(chunk, charIndex); + chunk = chunk.next; + chunk.prependRight(indentStr); + } + } + } + + charIndex += 1; + } + } + + charIndex = chunk.end; + chunk = chunk.next; + } + + this.outro = this.outro.replace(pattern, replacer); + + return this; + } + + insert() { + throw new Error( + 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)', + ); + } + + insertLeft(index, content) { + if (!warned.insertLeft) { + console.warn( + 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead', + ); // eslint-disable-line no-console + warned.insertLeft = true; + } + + return this.appendLeft(index, content); + } + + insertRight(index, content) { + if (!warned.insertRight) { + console.warn( + 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead', + ); // eslint-disable-line no-console + warned.insertRight = true; + } + + return this.prependRight(index, content); + } + + move(start, end, index) { + if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself'); + + this._split(start); + this._split(end); + this._split(index); + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + const oldLeft = first.previous; + const oldRight = last.next; + + const newRight = this.byStart[index]; + if (!newRight && last === this.lastChunk) return this; + const newLeft = newRight ? newRight.previous : this.lastChunk; + + if (oldLeft) oldLeft.next = oldRight; + if (oldRight) oldRight.previous = oldLeft; + + if (newLeft) newLeft.next = first; + if (newRight) newRight.previous = last; + + if (!first.previous) this.firstChunk = last.next; + if (!last.next) { + this.lastChunk = first.previous; + this.lastChunk.next = null; + } + + first.previous = newLeft; + last.next = newRight || null; + + if (!newLeft) this.firstChunk = first; + if (!newRight) this.lastChunk = last; + return this; + } + + overwrite(start, end, content, options) { + options = options || {}; + return this.update(start, end, content, { ...options, overwrite: !options.contentOnly }); + } + + update(start, end, content, options) { + if (typeof content !== 'string') throw new TypeError('replacement content must be a string'); + + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (end > this.original.length) throw new Error('end is out of bounds'); + if (start === end) + throw new Error( + 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead', + ); + + this._split(start); + this._split(end); + + if (options === true) { + if (!warned.storeName) { + console.warn( + 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string', + ); // eslint-disable-line no-console + warned.storeName = true; + } + + options = { storeName: true }; + } + const storeName = options !== undefined ? options.storeName : false; + const overwrite = options !== undefined ? options.overwrite : false; + + if (storeName) { + const original = this.original.slice(start, end); + Object.defineProperty(this.storedNames, original, { + writable: true, + value: true, + enumerable: true, + }); + } + + const first = this.byStart[start]; + const last = this.byEnd[end]; + + if (first) { + let chunk = first; + while (chunk !== last) { + if (chunk.next !== this.byStart[chunk.end]) { + throw new Error('Cannot overwrite across a split point'); + } + chunk = chunk.next; + chunk.edit('', false); + } + + first.edit(content, storeName, !overwrite); + } else { + // must be inserting at the end + const newChunk = new Chunk(start, end, '').edit(content, storeName); + + // TODO last chunk in the array may not be the last chunk, if it's moved... + last.next = newChunk; + newChunk.previous = last; + } + return this; + } + + prepend(content) { + if (typeof content !== 'string') throw new TypeError('outro content must be a string'); + + this.intro = content + this.intro; + return this; + } + + prependLeft(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byEnd[index]; + + if (chunk) { + chunk.prependLeft(content); + } else { + this.intro = content + this.intro; + } + return this; + } + + prependRight(index, content) { + if (typeof content !== 'string') throw new TypeError('inserted content must be a string'); + + this._split(index); + + const chunk = this.byStart[index]; + + if (chunk) { + chunk.prependRight(content); + } else { + this.outro = content + this.outro; + } + return this; + } + + remove(start, end) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + if (start === end) return this; + + if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds'); + if (start > end) throw new Error('end must be greater than start'); + + this._split(start); + this._split(end); + + let chunk = this.byStart[start]; + + while (chunk) { + chunk.intro = ''; + chunk.outro = ''; + chunk.edit(''); + + chunk = end > chunk.end ? this.byStart[chunk.end] : null; + } + return this; + } + + lastChar() { + if (this.outro.length) return this.outro[this.outro.length - 1]; + let chunk = this.lastChunk; + do { + if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1]; + if (chunk.content.length) return chunk.content[chunk.content.length - 1]; + if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1]; + } while ((chunk = chunk.previous)); + if (this.intro.length) return this.intro[this.intro.length - 1]; + return ''; + } + + lastLine() { + let lineIndex = this.outro.lastIndexOf(n$1); + if (lineIndex !== -1) return this.outro.substr(lineIndex + 1); + let lineStr = this.outro; + let chunk = this.lastChunk; + do { + if (chunk.outro.length > 0) { + lineIndex = chunk.outro.lastIndexOf(n$1); + if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.outro + lineStr; + } + + if (chunk.content.length > 0) { + lineIndex = chunk.content.lastIndexOf(n$1); + if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr; + lineStr = chunk.content + lineStr; + } + + if (chunk.intro.length > 0) { + lineIndex = chunk.intro.lastIndexOf(n$1); + if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr; + lineStr = chunk.intro + lineStr; + } + } while ((chunk = chunk.previous)); + lineIndex = this.intro.lastIndexOf(n$1); + if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr; + return this.intro + lineStr; + } + + slice(start = 0, end = this.original.length) { + while (start < 0) start += this.original.length; + while (end < 0) end += this.original.length; + + let result = ''; + + // find start chunk + let chunk = this.firstChunk; + while (chunk && (chunk.start > start || chunk.end <= start)) { + // found end chunk before start + if (chunk.start < end && chunk.end >= end) { + return result; + } + + chunk = chunk.next; + } + + if (chunk && chunk.edited && chunk.start !== start) + throw new Error(`Cannot use replaced character ${start} as slice start anchor.`); + + const startChunk = chunk; + while (chunk) { + if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { + result += chunk.intro; + } + + const containsEnd = chunk.start < end && chunk.end >= end; + if (containsEnd && chunk.edited && chunk.end !== end) + throw new Error(`Cannot use replaced character ${end} as slice end anchor.`); + + const sliceStart = startChunk === chunk ? start - chunk.start : 0; + const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; + + result += chunk.content.slice(sliceStart, sliceEnd); + + if (chunk.outro && (!containsEnd || chunk.end === end)) { + result += chunk.outro; + } + + if (containsEnd) { + break; + } + + chunk = chunk.next; + } + + return result; + } + + // TODO deprecate this? not really very useful + snip(start, end) { + const clone = this.clone(); + clone.remove(0, start); + clone.remove(end, clone.original.length); + + return clone; + } + + _split(index) { + if (this.byStart[index] || this.byEnd[index]) return; + + let chunk = this.lastSearchedChunk; + const searchForward = index > chunk.end; + + while (chunk) { + if (chunk.contains(index)) return this._splitChunk(chunk, index); + + chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start]; + } + } + + _splitChunk(chunk, index) { + if (chunk.edited && chunk.content.length) { + // zero-length edited chunks are a special case (overlapping replacements) + const loc = getLocator(this.original)(index); + throw new Error( + `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`, + ); + } + + const newChunk = chunk.split(index); + + this.byEnd[index] = chunk; + this.byStart[index] = newChunk; + this.byEnd[newChunk.end] = newChunk; + + if (chunk === this.lastChunk) this.lastChunk = newChunk; + + this.lastSearchedChunk = chunk; + return true; + } + + toString() { + let str = this.intro; + + let chunk = this.firstChunk; + while (chunk) { + str += chunk.toString(); + chunk = chunk.next; + } + + return str + this.outro; + } + + isEmpty() { + let chunk = this.firstChunk; + do { + if ( + (chunk.intro.length && chunk.intro.trim()) || + (chunk.content.length && chunk.content.trim()) || + (chunk.outro.length && chunk.outro.trim()) + ) + return false; + } while ((chunk = chunk.next)); + return true; + } + + length() { + let chunk = this.firstChunk; + let length = 0; + do { + length += chunk.intro.length + chunk.content.length + chunk.outro.length; + } while ((chunk = chunk.next)); + return length; + } + + trimLines() { + return this.trim('[\\r\\n]'); + } + + trim(charType) { + return this.trimStart(charType).trimEnd(charType); + } + + trimEndAborted(charType) { + const rx = new RegExp((charType || '\\s') + '+$'); + + this.outro = this.outro.replace(rx, ''); + if (this.outro.length) return true; + + let chunk = this.lastChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimEnd(rx); + + // if chunk was trimmed, we have a new lastChunk + if (chunk.end !== end) { + if (this.lastChunk === chunk) { + this.lastChunk = chunk.next; + } + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.previous; + } while (chunk); + + return false; + } + + trimEnd(charType) { + this.trimEndAborted(charType); + return this; + } + trimStartAborted(charType) { + const rx = new RegExp('^' + (charType || '\\s') + '+'); + + this.intro = this.intro.replace(rx, ''); + if (this.intro.length) return true; + + let chunk = this.firstChunk; + + do { + const end = chunk.end; + const aborted = chunk.trimStart(rx); + + if (chunk.end !== end) { + // special case... + if (chunk === this.lastChunk) this.lastChunk = chunk.next; + + this.byEnd[chunk.end] = chunk; + this.byStart[chunk.next.start] = chunk.next; + this.byEnd[chunk.next.end] = chunk.next; + } + + if (aborted) return true; + chunk = chunk.next; + } while (chunk); + + return false; + } + + trimStart(charType) { + this.trimStartAborted(charType); + return this; + } + + hasChanged() { + return this.original !== this.toString(); + } + + _replaceRegexp(searchValue, replacement) { + function getReplacement(match, str) { + if (typeof replacement === 'string') { + return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => { + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter + if (i === '$') return '$'; + if (i === '&') return match[0]; + const num = +i; + if (num < match.length) return match[+i]; + return `$${i}`; + }); + } else { + return replacement(...match, match.index, str, match.groups); + } + } + function matchAll(re, str) { + let match; + const matches = []; + while ((match = re.exec(str))) { + matches.push(match); + } + return matches; + } + if (searchValue.global) { + const matches = matchAll(searchValue, this.original); + matches.forEach((match) => { + if (match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + }); + } else { + const match = this.original.match(searchValue); + if (match && match.index != null) + this.overwrite( + match.index, + match.index + match[0].length, + getReplacement(match, this.original), + ); + } + return this; + } + + _replaceString(string, replacement) { + const { original } = this; + const index = original.indexOf(string); + + if (index !== -1) { + this.overwrite(index, index + string.length, replacement); + } + + return this; + } + + replace(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceString(searchValue, replacement); + } + + return this._replaceRegexp(searchValue, replacement); + } + + _replaceAllString(string, replacement) { + const { original } = this; + const stringLength = string.length; + for ( + let index = original.indexOf(string); + index !== -1; + index = original.indexOf(string, index + stringLength) + ) { + this.overwrite(index, index + stringLength, replacement); + } + + return this; + } + + replaceAll(searchValue, replacement) { + if (typeof searchValue === 'string') { + return this._replaceAllString(searchValue, replacement); + } + + if (!searchValue.global) { + throw new TypeError( + 'MagicString.prototype.replaceAll called with a non-global RegExp argument', + ); + } + + return this._replaceRegexp(searchValue, replacement); + } +} + +function isReference(node, parent) { + if (node.type === 'MemberExpression') { + return !node.computed && isReference(node.object, node); + } + if (node.type === 'Identifier') { + if (!parent) + return true; + switch (parent.type) { + // disregard `bar` in `foo.bar` + case 'MemberExpression': return parent.computed || node === parent.object; + // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}` + case 'MethodDefinition': return parent.computed; + // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}` + case 'FieldDefinition': return parent.computed || node === parent.value; + // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }` + case 'Property': return parent.computed || node === parent.value; + // disregard the `bar` in `export { foo as bar }` or + // the foo in `import { foo as bar }` + case 'ExportSpecifier': + case 'ImportSpecifier': return node === parent.local; + // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}` + case 'LabeledStatement': + case 'BreakStatement': + case 'ContinueStatement': return false; + default: return true; + } + } + return false; +} + +var version$3 = "25.0.7"; +var peerDependencies = { + rollup: "^2.68.0||^3.0.0||^4.0.0" +}; + +function tryParse(parse, code, id) { + try { + return parse(code, { allowReturnOutsideFunction: true }); + } catch (err) { + err.message += ` in ${id}`; + throw err; + } +} + +const firstpassGlobal = /\b(?:require|module|exports|global)\b/; + +const firstpassNoGlobal = /\b(?:require|module|exports)\b/; + +function hasCjsKeywords(code, ignoreGlobal) { + const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal; + return firstpass.test(code); +} + +/* eslint-disable no-underscore-dangle */ + + +function analyzeTopLevelStatements(parse, code, id) { + const ast = tryParse(parse, code, id); + + let isEsModule = false; + let hasDefaultExport = false; + let hasNamedExports = false; + + for (const node of ast.body) { + switch (node.type) { + case 'ExportDefaultDeclaration': + isEsModule = true; + hasDefaultExport = true; + break; + case 'ExportNamedDeclaration': + isEsModule = true; + if (node.declaration) { + hasNamedExports = true; + } else { + for (const specifier of node.specifiers) { + if (specifier.exported.name === 'default') { + hasDefaultExport = true; + } else { + hasNamedExports = true; + } + } + } + break; + case 'ExportAllDeclaration': + isEsModule = true; + if (node.exported && node.exported.name === 'default') { + hasDefaultExport = true; + } else { + hasNamedExports = true; + } + break; + case 'ImportDeclaration': + isEsModule = true; + break; + } + } + + return { isEsModule, hasDefaultExport, hasNamedExports, ast }; +} + +/* eslint-disable import/prefer-default-export */ + + +function deconflict(scopes, globals, identifier) { + let i = 1; + let deconflicted = makeLegalIdentifier(identifier); + const hasConflicts = () => + scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted); + + while (hasConflicts()) { + deconflicted = makeLegalIdentifier(`${identifier}_${i}`); + i += 1; + } + + for (const scope of scopes) { + scope.declarations[deconflicted] = true; + } + + return deconflicted; +} + +function getName(id) { + const name = makeLegalIdentifier(basename$1(id, extname(id))); + if (name !== 'index') { + return name; + } + return makeLegalIdentifier(basename$1(dirname$1(id))); +} + +function normalizePathSlashes(path) { + return path.replace(/\\/g, '/'); +} + +const getVirtualPathForDynamicRequirePath = (path, commonDir) => + `/${normalizePathSlashes(relative$1(commonDir, path))}`; + +function capitalize(name) { + return name[0].toUpperCase() + name.slice(1); +} + +function getStrictRequiresFilter({ strictRequires }) { + switch (strictRequires) { + case true: + return { strictRequiresFilter: () => true, detectCyclesAndConditional: false }; + // eslint-disable-next-line no-undefined + case undefined: + case 'auto': + case 'debug': + case null: + return { strictRequiresFilter: () => false, detectCyclesAndConditional: true }; + case false: + return { strictRequiresFilter: () => false, detectCyclesAndConditional: false }; + default: + if (typeof strictRequires === 'string' || Array.isArray(strictRequires)) { + return { + strictRequiresFilter: createFilter$1(strictRequires), + detectCyclesAndConditional: false + }; + } + throw new Error('Unexpected value for "strictRequires" option.'); + } +} + +function getPackageEntryPoint(dirPath) { + let entryPoint = 'index.js'; + + try { + if (existsSync(join$1(dirPath, 'package.json'))) { + entryPoint = + JSON.parse(readFileSync(join$1(dirPath, 'package.json'), { encoding: 'utf8' })).main || + entryPoint; + } + } catch (ignored) { + // ignored + } + + return entryPoint; +} + +function isDirectory$1(path) { + try { + if (statSync$1(path).isDirectory()) return true; + } catch (ignored) { + // Nothing to do here + } + return false; +} + +function getDynamicRequireModules(patterns, dynamicRequireRoot) { + const dynamicRequireModules = new Map(); + const dirNames = new Set(); + for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) { + const isNegated = pattern.startsWith('!'); + const modifyMap = (targetPath, resolvedPath) => + isNegated + ? dynamicRequireModules.delete(targetPath) + : dynamicRequireModules.set(targetPath, resolvedPath); + for (const path of glob$1.sync(isNegated ? pattern.substr(1) : pattern)) { + const resolvedPath = resolve$3(path); + const requirePath = normalizePathSlashes(resolvedPath); + if (isDirectory$1(resolvedPath)) { + dirNames.add(resolvedPath); + const modulePath = resolve$3(join$1(resolvedPath, getPackageEntryPoint(path))); + modifyMap(requirePath, modulePath); + modifyMap(normalizePathSlashes(modulePath), modulePath); + } else { + dirNames.add(dirname$1(resolvedPath)); + modifyMap(requirePath, resolvedPath); + } + } + } + return { + commonDir: dirNames.size ? getCommonDir([...dirNames, dynamicRequireRoot]) : null, + dynamicRequireModules + }; +} + +const FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`; + +const COMMONJS_REQUIRE_EXPORT = 'commonjsRequire'; +const CREATE_COMMONJS_REQUIRE_EXPORT = 'createCommonjsRequire'; + +function getDynamicModuleRegistry( + isDynamicRequireModulesEnabled, + dynamicRequireModules, + commonDir, + ignoreDynamicRequires +) { + if (!isDynamicRequireModulesEnabled) { + return `export function ${COMMONJS_REQUIRE_EXPORT}(path) { + ${FAILED_REQUIRE_ERROR} +}`; + } + const dynamicModuleImports = [...dynamicRequireModules.values()] + .map( + (id, index) => + `import ${ + id.endsWith('.json') ? `json${index}` : `{ __require as require${index} }` + } from ${JSON.stringify(id)};` + ) + .join('\n'); + const dynamicModuleProps = [...dynamicRequireModules.keys()] + .map( + (id, index) => + `\t\t${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${ + id.endsWith('.json') ? `function () { return json${index}; }` : `require${index}` + }` + ) + .join(',\n'); + return `${dynamicModuleImports} + +var dynamicModules; + +function getDynamicModules() { + return dynamicModules || (dynamicModules = { +${dynamicModuleProps} + }); +} + +export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) { + function handleRequire(path) { + var resolvedPath = commonjsResolve(path, originalModuleDir); + if (resolvedPath !== null) { + return getDynamicModules()[resolvedPath](); + } + ${ignoreDynamicRequires ? 'return require(path);' : FAILED_REQUIRE_ERROR} + } + handleRequire.resolve = function (path) { + var resolvedPath = commonjsResolve(path, originalModuleDir); + if (resolvedPath !== null) { + return resolvedPath; + } + return require.resolve(path); + } + return handleRequire; +} + +function commonjsResolve (path, originalModuleDir) { + var shouldTryNodeModules = isPossibleNodeModulesPath(path); + path = normalize(path); + var relPath; + if (path[0] === '/') { + originalModuleDir = ''; + } + var modules = getDynamicModules(); + var checkedExtensions = ['', '.js', '.json']; + while (true) { + if (!shouldTryNodeModules) { + relPath = normalize(originalModuleDir + '/' + path); + } else { + relPath = normalize(originalModuleDir + '/node_modules/' + path); + } + + if (relPath.endsWith('/..')) { + break; // Travelled too far up, avoid infinite loop + } + + for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) { + var resolvedPath = relPath + checkedExtensions[extensionIndex]; + if (modules[resolvedPath]) { + return resolvedPath; + } + } + if (!shouldTryNodeModules) break; + var nextDir = normalize(originalModuleDir + '/..'); + if (nextDir === originalModuleDir) break; + originalModuleDir = nextDir; + } + return null; +} + +function isPossibleNodeModulesPath (modulePath) { + var c0 = modulePath[0]; + if (c0 === '/' || c0 === '\\\\') return false; + var c1 = modulePath[1], c2 = modulePath[2]; + if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) || + (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false; + if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false; + return true; +} + +function normalize (path) { + path = path.replace(/\\\\/g, '/'); + var parts = path.split('/'); + var slashed = parts[0] === ''; + for (var i = 1; i < parts.length; i++) { + if (parts[i] === '.' || parts[i] === '') { + parts.splice(i--, 1); + } + } + for (var i = 1; i < parts.length; i++) { + if (parts[i] !== '..') continue; + if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') { + parts.splice(--i, 2); + i--; + } + } + path = parts.join('/'); + if (slashed && path[0] !== '/') path = '/' + path; + else if (path.length === 0) path = '.'; + return path; +}`; +} + +const isWrappedId = (id, suffix) => id.endsWith(suffix); +const wrapId$1 = (id, suffix) => `\0${id}${suffix}`; +const unwrapId$1 = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length); + +const PROXY_SUFFIX = '?commonjs-proxy'; +const WRAPPED_SUFFIX = '?commonjs-wrapped'; +const EXTERNAL_SUFFIX = '?commonjs-external'; +const EXPORTS_SUFFIX = '?commonjs-exports'; +const MODULE_SUFFIX = '?commonjs-module'; +const ENTRY_SUFFIX = '?commonjs-entry'; +const ES_IMPORT_SUFFIX = '?commonjs-es-import'; + +const DYNAMIC_MODULES_ID = '\0commonjs-dynamic-modules'; +const HELPERS_ID = '\0commonjsHelpers.js'; + +const IS_WRAPPED_COMMONJS = 'withRequireFunction'; + +// `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers. +// Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled. +// This could be improved by inspecting Rollup's "generatedCode" option + +const HELPERS = ` +export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +export function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +export function getDefaultExportFromNamespaceIfPresent (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; +} + +export function getDefaultExportFromNamespaceIfNotNamed (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; +} + +export function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a () { + if (this instanceof a) { + return Reflect.construct(f, arguments, this.constructor); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} +`; + +function getHelpersModule() { + return HELPERS; +} + +function getUnknownRequireProxy(id, requireReturnsDefault) { + if (requireReturnsDefault === true || id.endsWith('.json')) { + return `export { default } from ${JSON.stringify(id)};`; + } + const name = getName(id); + const exported = + requireReturnsDefault === 'auto' + ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});` + : requireReturnsDefault === 'preferred' + ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});` + : !requireReturnsDefault + ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});` + : `export default ${name};`; + return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`; +} + +async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) { + const name = getName(id); + const { + meta: { commonjs: commonjsMeta } + } = await loadModule({ id }); + if (!commonjsMeta) { + return getUnknownRequireProxy(id, requireReturnsDefault); + } + if (commonjsMeta.isCommonJS) { + return `export { __moduleExports as default } from ${JSON.stringify(id)};`; + } + if (!requireReturnsDefault) { + return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify( + id + )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`; + } + if ( + requireReturnsDefault !== true && + (requireReturnsDefault === 'namespace' || + !commonjsMeta.hasDefaultExport || + (requireReturnsDefault === 'auto' && commonjsMeta.hasNamedExports)) + ) { + return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`; + } + return `export { default } from ${JSON.stringify(id)};`; +} + +function getEntryProxy(id, defaultIsModuleExports, getModuleInfo, shebang) { + const { + meta: { commonjs: commonjsMeta }, + hasDefaultExport + } = getModuleInfo(id); + if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) { + const stringifiedId = JSON.stringify(id); + let code = `export * from ${stringifiedId};`; + if (hasDefaultExport) { + code += `export { default } from ${stringifiedId};`; + } + return shebang + code; + } + const result = getEsImportProxy(id, defaultIsModuleExports); + return { + ...result, + code: shebang + result.code + }; +} + +function getEsImportProxy(id, defaultIsModuleExports) { + const name = getName(id); + const exportsName = `${name}Exports`; + const requireModule = `require${capitalize(name)}`; + let code = + `import { getDefaultExportFromCjs } from "${HELPERS_ID}";\n` + + `import { __require as ${requireModule} } from ${JSON.stringify(id)};\n` + + `var ${exportsName} = ${requireModule}();\n` + + `export { ${exportsName} as __moduleExports };`; + if (defaultIsModuleExports === true) { + code += `\nexport { ${exportsName} as default };`; + } else { + code += `export default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`; + } + return { + code, + syntheticNamedExports: '__moduleExports' + }; +} + +/* eslint-disable no-param-reassign, no-undefined */ + + +function getCandidatesForExtension(resolved, extension) { + return [resolved + extension, `${resolved}${sep}index${extension}`]; +} + +function getCandidates(resolved, extensions) { + return extensions.reduce( + (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)), + [resolved] + ); +} + +function resolveExtensions(importee, importer, extensions) { + // not our problem + if (importee[0] !== '.' || !importer) return undefined; + + const resolved = resolve$3(dirname$1(importer), importee); + const candidates = getCandidates(resolved, extensions); + + for (let i = 0; i < candidates.length; i += 1) { + try { + const stats = statSync$1(candidates[i]); + if (stats.isFile()) return { id: candidates[i] }; + } catch (err) { + /* noop */ + } + } + + return undefined; +} + +function getResolveId(extensions, isPossibleCjsId) { + const currentlyResolving = new Map(); + + return { + /** + * This is a Maps of importers to Sets of require sources being resolved at + * the moment by resolveRequireSourcesAndUpdateMeta + */ + currentlyResolving, + async resolveId(importee, importer, resolveOptions) { + const customOptions = resolveOptions.custom; + // All logic below is specific to ES imports. + // Also, if we do not skip this logic for requires that are resolved while + // transforming a commonjs file, it can easily lead to deadlocks. + if ( + customOptions && + customOptions['node-resolve'] && + customOptions['node-resolve'].isRequire + ) { + return null; + } + const currentlyResolvingForParent = currentlyResolving.get(importer); + if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) { + this.warn({ + code: 'THIS_RESOLVE_WITHOUT_OPTIONS', + message: + 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.', + url: 'https://rollupjs.org/guide/en/#resolveid' + }); + return null; + } + + if (isWrappedId(importee, WRAPPED_SUFFIX)) { + return unwrapId$1(importee, WRAPPED_SUFFIX); + } + + if ( + importee.endsWith(ENTRY_SUFFIX) || + isWrappedId(importee, MODULE_SUFFIX) || + isWrappedId(importee, EXPORTS_SUFFIX) || + isWrappedId(importee, PROXY_SUFFIX) || + isWrappedId(importee, ES_IMPORT_SUFFIX) || + isWrappedId(importee, EXTERNAL_SUFFIX) || + importee.startsWith(HELPERS_ID) || + importee === DYNAMIC_MODULES_ID + ) { + return importee; + } + + if (importer) { + if ( + importer === DYNAMIC_MODULES_ID || + // Proxies are only importing resolved ids, no need to resolve again + isWrappedId(importer, PROXY_SUFFIX) || + isWrappedId(importer, ES_IMPORT_SUFFIX) || + importer.endsWith(ENTRY_SUFFIX) + ) { + return importee; + } + if (isWrappedId(importer, EXTERNAL_SUFFIX)) { + // We need to return null for unresolved imports so that the proper warning is shown + if ( + !(await this.resolve( + importee, + importer, + Object.assign({ skipSelf: true }, resolveOptions) + )) + ) { + return null; + } + // For other external imports, we need to make sure they are handled as external + return { id: importee, external: true }; + } + } + + if (importee.startsWith('\0')) { + return null; + } + + // If this is an entry point or ESM import, we need to figure out if the importee is wrapped and + // if that is the case, we need to add a proxy. + const resolved = + (await this.resolve( + importee, + importer, + Object.assign({ skipSelf: true }, resolveOptions) + )) || resolveExtensions(importee, importer, extensions); + // Make sure that even if other plugins resolve again, we ignore our own proxies + if ( + !resolved || + resolved.external || + resolved.id.endsWith(ENTRY_SUFFIX) || + isWrappedId(resolved.id, ES_IMPORT_SUFFIX) || + !isPossibleCjsId(resolved.id) + ) { + return resolved; + } + const moduleInfo = await this.load(resolved); + const { + meta: { commonjs: commonjsMeta } + } = moduleInfo; + if (commonjsMeta) { + const { isCommonJS } = commonjsMeta; + if (isCommonJS) { + if (resolveOptions.isEntry) { + moduleInfo.moduleSideEffects = true; + // We must not precede entry proxies with a `\0` as that will mess up relative external resolution + return resolved.id + ENTRY_SUFFIX; + } + if (isCommonJS === IS_WRAPPED_COMMONJS) { + return { id: wrapId$1(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } }; + } + } + } + return resolved; + } + }; +} + +function getRequireResolver(extensions, detectCyclesAndConditional, currentlyResolving) { + const knownCjsModuleTypes = Object.create(null); + const requiredIds = Object.create(null); + const unconditionallyRequiredIds = Object.create(null); + const dependencies = Object.create(null); + const getDependencies = (id) => dependencies[id] || (dependencies[id] = new Set()); + + const isCyclic = (id) => { + const dependenciesToCheck = new Set(getDependencies(id)); + for (const dependency of dependenciesToCheck) { + if (dependency === id) { + return true; + } + for (const childDependency of getDependencies(dependency)) { + dependenciesToCheck.add(childDependency); + } + } + return false; + }; + + // Once a module is listed here, its type (wrapped or not) is fixed and may + // not change for the rest of the current build, to not break already + // transformed modules. + const fullyAnalyzedModules = Object.create(null); + + const getTypeForFullyAnalyzedModule = (id) => { + const knownType = knownCjsModuleTypes[id]; + if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) { + return knownType; + } + if (isCyclic(id)) { + return (knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS); + } + return knownType; + }; + + const setInitialParentType = (id, initialCommonJSType) => { + // Fully analyzed modules may never change type + if (fullyAnalyzedModules[id]) { + return; + } + knownCjsModuleTypes[id] = initialCommonJSType; + if ( + detectCyclesAndConditional && + knownCjsModuleTypes[id] === true && + requiredIds[id] && + !unconditionallyRequiredIds[id] + ) { + knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS; + } + }; + + const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => { + const childId = resolved.id; + requiredIds[childId] = true; + if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) { + unconditionallyRequiredIds[childId] = true; + } + + getDependencies(parentId).add(childId); + if (!isCyclic(childId)) { + // This makes sure the current transform handler waits for all direct + // dependencies to be loaded and transformed and therefore for all + // transitive CommonJS dependencies to be loaded as well so that all + // cycles have been found and knownCjsModuleTypes is reliable. + await loadModule(resolved); + } + }; + + const getTypeForImportedModule = async (resolved, loadModule) => { + if (resolved.id in knownCjsModuleTypes) { + // This handles cyclic ES dependencies + return knownCjsModuleTypes[resolved.id]; + } + const { + meta: { commonjs } + } = await loadModule(resolved); + return (commonjs && commonjs.isCommonJS) || false; + }; + + return { + getWrappedIds: () => + Object.keys(knownCjsModuleTypes).filter( + (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS + ), + isRequiredId: (id) => requiredIds[id], + async shouldTransformCachedModule({ + id: parentId, + resolvedSources, + meta: { commonjs: parentMeta } + }) { + // We explicitly track ES modules to handle circular imports + if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false; + if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false; + const parentRequires = parentMeta && parentMeta.requires; + if (parentRequires) { + setInitialParentType(parentId, parentMeta.initialCommonJSType); + await Promise.all( + parentRequires.map(({ resolved, isConditional }) => + analyzeRequiredModule(parentId, resolved, isConditional, this.load) + ) + ); + if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) { + return true; + } + for (const { + resolved: { id } + } of parentRequires) { + if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) { + return true; + } + } + // Now that we decided to go with the cached copy, neither the parent + // module nor any of its children may change types anymore + fullyAnalyzedModules[parentId] = true; + for (const { + resolved: { id } + } of parentRequires) { + fullyAnalyzedModules[id] = true; + } + } + const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id)); + return ( + await Promise.all( + Object.keys(resolvedSources) + .map((source) => resolvedSources[source]) + .filter(({ id, external }) => !(external || parentRequireSet.has(id))) + .map(async (resolved) => { + if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) { + return ( + (await getTypeForImportedModule( + ( + await this.load({ id: resolved.id }) + ).meta.commonjs.resolved, + this.load + )) !== IS_WRAPPED_COMMONJS + ); + } + return (await getTypeForImportedModule(resolved, this.load)) === IS_WRAPPED_COMMONJS; + }) + ) + ).some((shouldTransform) => shouldTransform); + }, + /* eslint-disable no-param-reassign */ + resolveRequireSourcesAndUpdateMeta: + (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => { + parentMeta.initialCommonJSType = isParentCommonJS; + parentMeta.requires = []; + parentMeta.isRequiredCommonJS = Object.create(null); + setInitialParentType(parentId, isParentCommonJS); + const currentlyResolvingForParent = currentlyResolving.get(parentId) || new Set(); + currentlyResolving.set(parentId, currentlyResolvingForParent); + const requireTargets = await Promise.all( + sources.map(async ({ source, isConditional }) => { + // Never analyze or proxy internal modules + if (source.startsWith('\0')) { + return { id: source, allowProxy: false }; + } + currentlyResolvingForParent.add(source); + const resolved = + (await rollupContext.resolve(source, parentId, { + skipSelf: false, + custom: { 'node-resolve': { isRequire: true } } + })) || resolveExtensions(source, parentId, extensions); + currentlyResolvingForParent.delete(source); + if (!resolved) { + return { id: wrapId$1(source, EXTERNAL_SUFFIX), allowProxy: false }; + } + const childId = resolved.id; + if (resolved.external) { + return { id: wrapId$1(childId, EXTERNAL_SUFFIX), allowProxy: false }; + } + parentMeta.requires.push({ resolved, isConditional }); + await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load); + return { id: childId, allowProxy: true }; + }) + ); + parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId); + fullyAnalyzedModules[parentId] = true; + return requireTargets.map(({ id: dependencyId, allowProxy }, index) => { + // eslint-disable-next-line no-multi-assign + const isCommonJS = (parentMeta.isRequiredCommonJS[dependencyId] = + getTypeForFullyAnalyzedModule(dependencyId)); + fullyAnalyzedModules[dependencyId] = true; + return { + source: sources[index].source, + id: allowProxy + ? isCommonJS === IS_WRAPPED_COMMONJS + ? wrapId$1(dependencyId, WRAPPED_SUFFIX) + : wrapId$1(dependencyId, PROXY_SUFFIX) + : dependencyId, + isCommonJS + }; + }); + }, + isCurrentlyResolving(source, parentId) { + const currentlyResolvingForParent = currentlyResolving.get(parentId); + return currentlyResolvingForParent && currentlyResolvingForParent.has(source); + } + }; +} + +function validateVersion(actualVersion, peerDependencyVersion, name) { + const versionRegexp = /\^(\d+\.\d+\.\d+)/g; + let minMajor = Infinity; + let minMinor = Infinity; + let minPatch = Infinity; + let foundVersion; + // eslint-disable-next-line no-cond-assign + while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) { + const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number); + if (foundMajor < minMajor) { + minMajor = foundMajor; + minMinor = foundMinor; + minPatch = foundPatch; + } + } + if (!actualVersion) { + throw new Error( + `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch}.` + ); + } + const [major, minor, patch] = actualVersion.split('.').map(Number); + if ( + major < minMajor || + (major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch))) + ) { + throw new Error( + `Insufficient ${name} version: "@rollup/plugin-commonjs" requires at least ${name}@${minMajor}.${minMinor}.${minPatch} but found ${name}@${actualVersion}.` + ); + } +} + +const operators = { + '==': (x) => equals(x.left, x.right, false), + + '!=': (x) => not(operators['=='](x)), + + '===': (x) => equals(x.left, x.right, true), + + '!==': (x) => not(operators['==='](x)), + + '!': (x) => isFalsy(x.argument), + + '&&': (x) => isTruthy(x.left) && isTruthy(x.right), + + '||': (x) => isTruthy(x.left) || isTruthy(x.right) +}; + +function not(value) { + return value === null ? value : !value; +} + +function equals(a, b, strict) { + if (a.type !== b.type) return null; + // eslint-disable-next-line eqeqeq + if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value; + return null; +} + +function isTruthy(node) { + if (!node) return false; + if (node.type === 'Literal') return !!node.value; + if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression); + if (node.operator in operators) return operators[node.operator](node); + return null; +} + +function isFalsy(node) { + return not(isTruthy(node)); +} + +function getKeypath(node) { + const parts = []; + + while (node.type === 'MemberExpression') { + if (node.computed) return null; + + parts.unshift(node.property.name); + // eslint-disable-next-line no-param-reassign + node = node.object; + } + + if (node.type !== 'Identifier') return null; + + const { name } = node; + parts.unshift(name); + + return { name, keypath: parts.join('.') }; +} + +const KEY_COMPILED_ESM = '__esModule'; + +function getDefineCompiledEsmType(node) { + const definedPropertyWithExports = getDefinePropertyCallName(node, 'exports'); + const definedProperty = + definedPropertyWithExports || getDefinePropertyCallName(node, 'module.exports'); + if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) { + return isTruthy(definedProperty.value) + ? definedPropertyWithExports + ? 'exports' + : 'module' + : false; + } + return false; +} + +function getDefinePropertyCallName(node, targetName) { + const { + callee: { object, property } + } = node; + if (!object || object.type !== 'Identifier' || object.name !== 'Object') return; + if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return; + if (node.arguments.length !== 3) return; + + const targetNames = targetName.split('.'); + const [target, key, value] = node.arguments; + if (targetNames.length === 1) { + if (target.type !== 'Identifier' || target.name !== targetNames[0]) { + return; + } + } + + if (targetNames.length === 2) { + if ( + target.type !== 'MemberExpression' || + target.object.name !== targetNames[0] || + target.property.name !== targetNames[1] + ) { + return; + } + } + + if (value.type !== 'ObjectExpression' || !value.properties) return; + + const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value'); + if (!valueProperty || !valueProperty.value) return; + + // eslint-disable-next-line consistent-return + return { key: key.value, value: valueProperty.value }; +} + +function isShorthandProperty(parent) { + return parent && parent.type === 'Property' && parent.shorthand; +} + +function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) { + const args = []; + const passedArgs = []; + if (uses.module) { + args.push('module'); + passedArgs.push(moduleName); + } + if (uses.exports) { + args.push('exports'); + passedArgs.push(uses.module ? `${moduleName}.exports` : exportsName); + } + magicString + .trim() + .indent('\t', { exclude: indentExclusionRanges }) + .prepend(`(function (${args.join(', ')}) {\n`) + // For some reason, this line is only indented correctly when using a + // require-wrapper if we have this leading space + .append(` \n} (${passedArgs.join(', ')}));`); +} + +function rewriteExportsAndGetExportsBlock( + magicString, + moduleName, + exportsName, + exportedExportsName, + wrapped, + moduleExportsAssignments, + firstTopLevelModuleExportsAssignment, + exportsAssignmentsByName, + topLevelAssignments, + defineCompiledEsmExpressions, + deconflictedExportNames, + code, + HELPERS_NAME, + exportMode, + defaultIsModuleExports, + usesRequireWrapper, + requireName +) { + const exports = []; + const exportDeclarations = []; + + if (usesRequireWrapper) { + getExportsWhenUsingRequireWrapper( + magicString, + wrapped, + exportMode, + exports, + moduleExportsAssignments, + exportsAssignmentsByName, + moduleName, + exportsName, + requireName, + defineCompiledEsmExpressions + ); + } else if (exportMode === 'replace') { + getExportsForReplacedModuleExports( + magicString, + exports, + exportDeclarations, + moduleExportsAssignments, + firstTopLevelModuleExportsAssignment, + exportsName, + defaultIsModuleExports, + HELPERS_NAME + ); + } else { + if (exportMode === 'module') { + exportDeclarations.push(`var ${exportedExportsName} = ${moduleName}.exports`); + exports.push(`${exportedExportsName} as __moduleExports`); + } else { + exports.push(`${exportsName} as __moduleExports`); + } + if (wrapped) { + exportDeclarations.push( + getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) + ); + } else { + getExports( + magicString, + exports, + exportDeclarations, + moduleExportsAssignments, + exportsAssignmentsByName, + deconflictedExportNames, + topLevelAssignments, + moduleName, + exportsName, + exportedExportsName, + defineCompiledEsmExpressions, + HELPERS_NAME, + defaultIsModuleExports, + exportMode + ); + } + } + if (exports.length) { + exportDeclarations.push(`export { ${exports.join(', ')} }`); + } + + return `\n\n${exportDeclarations.join(';\n')};`; +} + +function getExportsWhenUsingRequireWrapper( + magicString, + wrapped, + exportMode, + exports, + moduleExportsAssignments, + exportsAssignmentsByName, + moduleName, + exportsName, + requireName, + defineCompiledEsmExpressions +) { + exports.push(`${requireName} as __require`); + if (wrapped) return; + if (exportMode === 'replace') { + rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName); + } else { + rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, `${moduleName}.exports`); + // Collect and rewrite named exports + for (const [exportName, { nodes }] of exportsAssignmentsByName) { + for (const { node, type } of nodes) { + magicString.overwrite( + node.start, + node.left.end, + `${ + exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName + }.${exportName}` + ); + } + } + replaceDefineCompiledEsmExpressionsAndGetIfRestorable( + defineCompiledEsmExpressions, + magicString, + exportMode, + moduleName, + exportsName + ); + } +} + +function getExportsForReplacedModuleExports( + magicString, + exports, + exportDeclarations, + moduleExportsAssignments, + firstTopLevelModuleExportsAssignment, + exportsName, + defaultIsModuleExports, + HELPERS_NAME +) { + for (const { left } of moduleExportsAssignments) { + magicString.overwrite(left.start, left.end, exportsName); + } + magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, 'var '); + exports.push(`${exportsName} as __moduleExports`); + exportDeclarations.push( + getDefaultExportDeclaration(exportsName, defaultIsModuleExports, HELPERS_NAME) + ); +} + +function getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) { + return `export default ${ + defaultIsModuleExports === true + ? exportedExportsName + : defaultIsModuleExports === false + ? `${exportedExportsName}.default` + : `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportedExportsName})` + }`; +} + +function getExports( + magicString, + exports, + exportDeclarations, + moduleExportsAssignments, + exportsAssignmentsByName, + deconflictedExportNames, + topLevelAssignments, + moduleName, + exportsName, + exportedExportsName, + defineCompiledEsmExpressions, + HELPERS_NAME, + defaultIsModuleExports, + exportMode +) { + let deconflictedDefaultExportName; + // Collect and rewrite module.exports assignments + for (const { left } of moduleExportsAssignments) { + magicString.overwrite(left.start, left.end, `${moduleName}.exports`); + } + + // Collect and rewrite named exports + for (const [exportName, { nodes }] of exportsAssignmentsByName) { + const deconflicted = deconflictedExportNames[exportName]; + let needsDeclaration = true; + for (const { node, type } of nodes) { + let replacement = `${deconflicted} = ${ + exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName + }.${exportName}`; + if (needsDeclaration && topLevelAssignments.has(node)) { + replacement = `var ${replacement}`; + needsDeclaration = false; + } + magicString.overwrite(node.start, node.left.end, replacement); + } + if (needsDeclaration) { + magicString.prepend(`var ${deconflicted};\n`); + } + + if (exportName === 'default') { + deconflictedDefaultExportName = deconflicted; + } else { + exports.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`); + } + } + + const isRestorableCompiledEsm = replaceDefineCompiledEsmExpressionsAndGetIfRestorable( + defineCompiledEsmExpressions, + magicString, + exportMode, + moduleName, + exportsName + ); + + if ( + defaultIsModuleExports === false || + (defaultIsModuleExports === 'auto' && + isRestorableCompiledEsm && + moduleExportsAssignments.length === 0) + ) { + // If there is no deconflictedDefaultExportName, then we use the namespace as + // fallback because there can be no "default" property on the namespace + exports.push(`${deconflictedDefaultExportName || exportedExportsName} as default`); + } else if ( + defaultIsModuleExports === true || + (!isRestorableCompiledEsm && moduleExportsAssignments.length === 0) + ) { + exports.push(`${exportedExportsName} as default`); + } else { + exportDeclarations.push( + getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) + ); + } +} + +function rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName) { + for (const { left } of moduleExportsAssignments) { + magicString.overwrite(left.start, left.end, exportsName); + } +} + +function replaceDefineCompiledEsmExpressionsAndGetIfRestorable( + defineCompiledEsmExpressions, + magicString, + exportMode, + moduleName, + exportsName +) { + let isRestorableCompiledEsm = false; + for (const { node, type } of defineCompiledEsmExpressions) { + isRestorableCompiledEsm = true; + const moduleExportsExpression = + node.type === 'CallExpression' ? node.arguments[0] : node.left.object; + magicString.overwrite( + moduleExportsExpression.start, + moduleExportsExpression.end, + exportMode === 'module' && type === 'module' ? `${moduleName}.exports` : exportsName + ); + } + return isRestorableCompiledEsm; +} + +function isRequireExpression(node, scope) { + if (!node) return false; + if (node.type !== 'CallExpression') return false; + + // Weird case of `require()` or `module.require()` without arguments + if (node.arguments.length === 0) return false; + + return isRequire(node.callee, scope); +} + +function isRequire(node, scope) { + return ( + (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) || + (node.type === 'MemberExpression' && isModuleRequire(node, scope)) + ); +} + +function isModuleRequire({ object, property }, scope) { + return ( + object.type === 'Identifier' && + object.name === 'module' && + property.type === 'Identifier' && + property.name === 'require' && + !scope.contains('module') + ); +} + +function hasDynamicArguments(node) { + return ( + node.arguments.length > 1 || + (node.arguments[0].type !== 'Literal' && + (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0)) + ); +} + +const reservedMethod = { resolve: true, cache: true, main: true }; + +function isNodeRequirePropertyAccess(parent) { + return parent && parent.property && reservedMethod[parent.property.name]; +} + +function getRequireStringArg(node) { + return node.arguments[0].type === 'Literal' + ? node.arguments[0].value + : node.arguments[0].quasis[0].value.cooked; +} + +function getRequireHandlers() { + const requireExpressions = []; + + function addRequireExpression( + sourceId, + node, + scope, + usesReturnValue, + isInsideTryBlock, + isInsideConditional, + toBeRemoved + ) { + requireExpressions.push({ + sourceId, + node, + scope, + usesReturnValue, + isInsideTryBlock, + isInsideConditional, + toBeRemoved + }); + } + + async function rewriteRequireExpressionsAndGetImportBlock( + magicString, + topLevelDeclarations, + reassignedNames, + helpersName, + dynamicRequireName, + moduleName, + exportsName, + id, + exportMode, + resolveRequireSourcesAndUpdateMeta, + needsRequireWrapper, + isEsModule, + isDynamicRequireModulesEnabled, + getIgnoreTryCatchRequireStatementMode, + commonjsMeta + ) { + const imports = []; + imports.push(`import * as ${helpersName} from "${HELPERS_ID}"`); + if (dynamicRequireName) { + imports.push( + `import { ${ + isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT + } as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}"` + ); + } + if (exportMode === 'module') { + imports.push( + `import { __module as ${moduleName} } from ${JSON.stringify(wrapId$1(id, MODULE_SUFFIX))}`, + `var ${exportsName} = ${moduleName}.exports` + ); + } else if (exportMode === 'exports') { + imports.push( + `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId$1(id, EXPORTS_SUFFIX))}` + ); + } + const requiresBySource = collectSources(requireExpressions); + const requireTargets = await resolveRequireSourcesAndUpdateMeta( + id, + needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule, + commonjsMeta, + Object.keys(requiresBySource).map((source) => { + return { + source, + isConditional: requiresBySource[source].every((require) => require.isInsideConditional) + }; + }) + ); + processRequireExpressions( + imports, + requireTargets, + requiresBySource, + getIgnoreTryCatchRequireStatementMode, + magicString + ); + return imports.length ? `${imports.join(';\n')};\n\n` : ''; + } + + return { + addRequireExpression, + rewriteRequireExpressionsAndGetImportBlock + }; +} + +function collectSources(requireExpressions) { + const requiresBySource = Object.create(null); + for (const requireExpression of requireExpressions) { + const { sourceId } = requireExpression; + if (!requiresBySource[sourceId]) { + requiresBySource[sourceId] = []; + } + const requires = requiresBySource[sourceId]; + requires.push(requireExpression); + } + return requiresBySource; +} + +function processRequireExpressions( + imports, + requireTargets, + requiresBySource, + getIgnoreTryCatchRequireStatementMode, + magicString +) { + const generateRequireName = getGenerateRequireName(); + for (const { source, id: resolvedId, isCommonJS } of requireTargets) { + const requires = requiresBySource[source]; + const name = generateRequireName(requires); + let usesRequired = false; + let needsImport = false; + for (const { node, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) { + const { canConvertRequire, shouldRemoveRequire } = + isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX) + ? getIgnoreTryCatchRequireStatementMode(source) + : { canConvertRequire: true, shouldRemoveRequire: false }; + if (shouldRemoveRequire) { + if (usesReturnValue) { + magicString.overwrite(node.start, node.end, 'undefined'); + } else { + magicString.remove(toBeRemoved.start, toBeRemoved.end); + } + } else if (canConvertRequire) { + needsImport = true; + if (isCommonJS === IS_WRAPPED_COMMONJS) { + magicString.overwrite(node.start, node.end, `${name}()`); + } else if (usesReturnValue) { + usesRequired = true; + magicString.overwrite(node.start, node.end, name); + } else { + magicString.remove(toBeRemoved.start, toBeRemoved.end); + } + } + } + if (needsImport) { + if (isCommonJS === IS_WRAPPED_COMMONJS) { + imports.push(`import { __require as ${name} } from ${JSON.stringify(resolvedId)}`); + } else { + imports.push(`import ${usesRequired ? `${name} from ` : ''}${JSON.stringify(resolvedId)}`); + } + } + } +} + +function getGenerateRequireName() { + let uid = 0; + return (requires) => { + let name; + const hasNameConflict = ({ scope }) => scope.contains(name); + do { + name = `require$$${uid}`; + uid += 1; + } while (requires.some(hasNameConflict)); + return name; + }; +} + +/* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */ + + +const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/; + +const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/; + +// There are three different types of CommonJS modules, described by their +// "exportMode": +// - exports: Only assignments to (module.)exports properties +// - replace: A single assignment to module.exports itself +// - module: Anything else +// Special cases: +// - usesRequireWrapper +// - isWrapped +async function transformCommonjs( + parse, + code, + id, + isEsModule, + ignoreGlobal, + ignoreRequire, + ignoreDynamicRequires, + getIgnoreTryCatchRequireStatementMode, + sourceMap, + isDynamicRequireModulesEnabled, + dynamicRequireModules, + commonDir, + astCache, + defaultIsModuleExports, + needsRequireWrapper, + resolveRequireSourcesAndUpdateMeta, + isRequired, + checkDynamicRequire, + commonjsMeta +) { + const ast = astCache || tryParse(parse, code, id); + const magicString = new MagicString(code); + const uses = { + module: false, + exports: false, + global: false, + require: false + }; + const virtualDynamicRequirePath = + isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(dirname$1(id), commonDir); + let scope = attachScopes(ast, 'scope'); + let lexicalDepth = 0; + let programDepth = 0; + let classBodyDepth = 0; + let currentTryBlockEnd = null; + let shouldWrap = false; + + const globals = new Set(); + // A conditionalNode is a node for which execution is not guaranteed. If such a node is a require + // or contains nested requires, those should be handled as function calls unless there is an + // unconditional require elsewhere. + let currentConditionalNodeEnd = null; + const conditionalNodes = new Set(); + const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers(); + + // See which names are assigned to. This is necessary to prevent + // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`, + // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh) + const reassignedNames = new Set(); + const topLevelDeclarations = []; + const skippedNodes = new Set(); + const moduleAccessScopes = new Set([scope]); + const exportsAccessScopes = new Set([scope]); + const moduleExportsAssignments = []; + let firstTopLevelModuleExportsAssignment = null; + const exportsAssignmentsByName = new Map(); + const topLevelAssignments = new Set(); + const topLevelDefineCompiledEsmExpressions = []; + const replacedGlobal = []; + const replacedDynamicRequires = []; + const importedVariables = new Set(); + const indentExclusionRanges = []; + + walk$3(ast, { + enter(node, parent) { + if (skippedNodes.has(node)) { + this.skip(); + return; + } + + if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) { + currentTryBlockEnd = null; + } + if (currentConditionalNodeEnd !== null && node.start > currentConditionalNodeEnd) { + currentConditionalNodeEnd = null; + } + if (currentConditionalNodeEnd === null && conditionalNodes.has(node)) { + currentConditionalNodeEnd = node.end; + } + + programDepth += 1; + if (node.scope) ({ scope } = node); + if (functionType.test(node.type)) lexicalDepth += 1; + if (sourceMap) { + magicString.addSourcemapLocation(node.start); + magicString.addSourcemapLocation(node.end); + } + + // eslint-disable-next-line default-case + switch (node.type) { + case 'AssignmentExpression': + if (node.left.type === 'MemberExpression') { + const flattened = getKeypath(node.left); + if (!flattened || scope.contains(flattened.name)) return; + + const exportsPatternMatch = exportsPattern.exec(flattened.keypath); + if (!exportsPatternMatch || flattened.keypath === 'exports') return; + + const [, exportName] = exportsPatternMatch; + uses[flattened.name] = true; + + // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` – + if (flattened.keypath === 'module.exports') { + moduleExportsAssignments.push(node); + if (programDepth > 3) { + moduleAccessScopes.add(scope); + } else if (!firstTopLevelModuleExportsAssignment) { + firstTopLevelModuleExportsAssignment = node; + } + } else if (exportName === KEY_COMPILED_ESM) { + if (programDepth > 3) { + shouldWrap = true; + } else { + // The "type" is either "module" or "exports" to discern + // assignments to module.exports vs exports if needed + topLevelDefineCompiledEsmExpressions.push({ node, type: flattened.name }); + } + } else { + const exportsAssignments = exportsAssignmentsByName.get(exportName) || { + nodes: [], + scopes: new Set() + }; + exportsAssignments.nodes.push({ node, type: flattened.name }); + exportsAssignments.scopes.add(scope); + exportsAccessScopes.add(scope); + exportsAssignmentsByName.set(exportName, exportsAssignments); + if (programDepth <= 3) { + topLevelAssignments.add(node); + } + } + + skippedNodes.add(node.left); + } else { + for (const name of extractAssignedNames(node.left)) { + reassignedNames.add(name); + } + } + return; + case 'CallExpression': { + const defineCompiledEsmType = getDefineCompiledEsmType(node); + if (defineCompiledEsmType) { + if (programDepth === 3 && parent.type === 'ExpressionStatement') { + // skip special handling for [module.]exports until we know we render this + skippedNodes.add(node.arguments[0]); + topLevelDefineCompiledEsmExpressions.push({ node, type: defineCompiledEsmType }); + } else { + shouldWrap = true; + } + return; + } + + // Transform require.resolve + if ( + isDynamicRequireModulesEnabled && + node.callee.object && + isRequire(node.callee.object, scope) && + node.callee.property.name === 'resolve' + ) { + checkDynamicRequire(node.start); + uses.require = true; + const requireNode = node.callee.object; + replacedDynamicRequires.push(requireNode); + skippedNodes.add(node.callee); + return; + } + + if (!isRequireExpression(node, scope)) { + const keypath = getKeypath(node.callee); + if (keypath && importedVariables.has(keypath.name)) { + // Heuristic to deoptimize requires after a required function has been called + currentConditionalNodeEnd = Infinity; + } + return; + } + + skippedNodes.add(node.callee); + uses.require = true; + + if (hasDynamicArguments(node)) { + if (isDynamicRequireModulesEnabled) { + checkDynamicRequire(node.start); + } + if (!ignoreDynamicRequires) { + replacedDynamicRequires.push(node.callee); + } + return; + } + + const requireStringArg = getRequireStringArg(node); + if (!ignoreRequire(requireStringArg)) { + const usesReturnValue = parent.type !== 'ExpressionStatement'; + const toBeRemoved = + parent.type === 'ExpressionStatement' && + (!currentConditionalNodeEnd || + // We should completely remove requires directly in a try-catch + // so that Rollup can remove up the try-catch + (currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd)) + ? parent + : node; + addRequireExpression( + requireStringArg, + node, + scope, + usesReturnValue, + currentTryBlockEnd !== null, + currentConditionalNodeEnd !== null, + toBeRemoved + ); + if (parent.type === 'VariableDeclarator' && parent.id.type === 'Identifier') { + for (const name of extractAssignedNames(parent.id)) { + importedVariables.add(name); + } + } + } + return; + } + case 'ClassBody': + classBodyDepth += 1; + return; + case 'ConditionalExpression': + case 'IfStatement': + // skip dead branches + if (isFalsy(node.test)) { + skippedNodes.add(node.consequent); + } else if (isTruthy(node.test)) { + if (node.alternate) { + skippedNodes.add(node.alternate); + } + } else { + conditionalNodes.add(node.consequent); + if (node.alternate) { + conditionalNodes.add(node.alternate); + } + } + return; + case 'ArrowFunctionExpression': + case 'FunctionDeclaration': + case 'FunctionExpression': + // requires in functions should be conditional unless it is an IIFE + if ( + currentConditionalNodeEnd === null && + !(parent.type === 'CallExpression' && parent.callee === node) + ) { + currentConditionalNodeEnd = node.end; + } + return; + case 'Identifier': { + const { name } = node; + if (!isReference(node, parent) || scope.contains(name)) return; + switch (name) { + case 'require': + uses.require = true; + if (isNodeRequirePropertyAccess(parent)) { + return; + } + if (!ignoreDynamicRequires) { + if (isShorthandProperty(parent)) { + // as key and value are the same object, isReference regards + // both as references, so we need to skip now + skippedNodes.add(parent.value); + magicString.prependRight(node.start, 'require: '); + } + replacedDynamicRequires.push(node); + } + return; + case 'module': + case 'exports': + shouldWrap = true; + uses[name] = true; + return; + case 'global': + uses.global = true; + if (!ignoreGlobal) { + replacedGlobal.push(node); + } + return; + case 'define': + magicString.overwrite(node.start, node.end, 'undefined', { + storeName: true + }); + return; + default: + globals.add(name); + return; + } + } + case 'LogicalExpression': + // skip dead branches + if (node.operator === '&&') { + if (isFalsy(node.left)) { + skippedNodes.add(node.right); + } else if (!isTruthy(node.left)) { + conditionalNodes.add(node.right); + } + } else if (node.operator === '||') { + if (isTruthy(node.left)) { + skippedNodes.add(node.right); + } else if (!isFalsy(node.left)) { + conditionalNodes.add(node.right); + } + } + return; + case 'MemberExpression': + if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) { + uses.require = true; + replacedDynamicRequires.push(node); + skippedNodes.add(node.object); + skippedNodes.add(node.property); + } + return; + case 'ReturnStatement': + // if top-level return, we need to wrap it + if (lexicalDepth === 0) { + shouldWrap = true; + } + return; + case 'ThisExpression': + // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal` + if (lexicalDepth === 0 && !classBodyDepth) { + uses.global = true; + if (!ignoreGlobal) { + replacedGlobal.push(node); + } + } + return; + case 'TryStatement': + if (currentTryBlockEnd === null) { + currentTryBlockEnd = node.block.end; + } + if (currentConditionalNodeEnd === null) { + currentConditionalNodeEnd = node.end; + } + return; + case 'UnaryExpression': + // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151) + if (node.operator === 'typeof') { + const flattened = getKeypath(node.argument); + if (!flattened) return; + + if (scope.contains(flattened.name)) return; + + if ( + !isEsModule && + (flattened.keypath === 'module.exports' || + flattened.keypath === 'module' || + flattened.keypath === 'exports') + ) { + magicString.overwrite(node.start, node.end, `'object'`, { + storeName: false + }); + } + } + return; + case 'VariableDeclaration': + if (!scope.parent) { + topLevelDeclarations.push(node); + } + return; + case 'TemplateElement': + if (node.value.raw.includes('\n')) { + indentExclusionRanges.push([node.start, node.end]); + } + } + }, + + leave(node) { + programDepth -= 1; + if (node.scope) scope = scope.parent; + if (functionType.test(node.type)) lexicalDepth -= 1; + if (node.type === 'ClassBody') classBodyDepth -= 1; + } + }); + + const nameBase = getName(id); + const exportsName = deconflict([...exportsAccessScopes], globals, nameBase); + const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`); + const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`); + const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`); + const helpersName = deconflict([scope], globals, 'commonjsHelpers'); + const dynamicRequireName = + replacedDynamicRequires.length > 0 && + deconflict( + [scope], + globals, + isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT + ); + const deconflictedExportNames = Object.create(null); + for (const [exportName, { scopes }] of exportsAssignmentsByName) { + deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName); + } + + for (const node of replacedGlobal) { + magicString.overwrite(node.start, node.end, `${helpersName}.commonjsGlobal`, { + storeName: true + }); + } + for (const node of replacedDynamicRequires) { + magicString.overwrite( + node.start, + node.end, + isDynamicRequireModulesEnabled + ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})` + : dynamicRequireName, + { + contentOnly: true, + storeName: true + } + ); + } + + // We cannot wrap ES/mixed modules + shouldWrap = !isEsModule && (shouldWrap || (uses.exports && moduleExportsAssignments.length > 0)); + + if ( + !( + shouldWrap || + isRequired || + needsRequireWrapper || + uses.module || + uses.exports || + uses.require || + topLevelDefineCompiledEsmExpressions.length > 0 + ) && + (ignoreGlobal || !uses.global) + ) { + return { meta: { commonjs: { isCommonJS: false } } }; + } + + let leadingComment = ''; + if (code.startsWith('/*')) { + const commentEnd = code.indexOf('*/', 2) + 2; + leadingComment = `${code.slice(0, commentEnd)}\n`; + magicString.remove(0, commentEnd).trim(); + } + + let shebang = ''; + if (code.startsWith('#!')) { + const shebangEndPosition = code.indexOf('\n') + 1; + shebang = code.slice(0, shebangEndPosition); + magicString.remove(0, shebangEndPosition).trim(); + } + + const exportMode = isEsModule + ? 'none' + : shouldWrap + ? uses.module + ? 'module' + : 'exports' + : firstTopLevelModuleExportsAssignment + ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0 + ? 'replace' + : 'module' + : moduleExportsAssignments.length === 0 + ? 'exports' + : 'module'; + + const exportedExportsName = + exportMode === 'module' ? deconflict([], globals, `${nameBase}Exports`) : exportsName; + + const importBlock = await rewriteRequireExpressionsAndGetImportBlock( + magicString, + topLevelDeclarations, + reassignedNames, + helpersName, + dynamicRequireName, + moduleName, + exportsName, + id, + exportMode, + resolveRequireSourcesAndUpdateMeta, + needsRequireWrapper, + isEsModule, + isDynamicRequireModulesEnabled, + getIgnoreTryCatchRequireStatementMode, + commonjsMeta + ); + const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS; + const exportBlock = isEsModule + ? '' + : rewriteExportsAndGetExportsBlock( + magicString, + moduleName, + exportsName, + exportedExportsName, + shouldWrap, + moduleExportsAssignments, + firstTopLevelModuleExportsAssignment, + exportsAssignmentsByName, + topLevelAssignments, + topLevelDefineCompiledEsmExpressions, + deconflictedExportNames, + code, + helpersName, + exportMode, + defaultIsModuleExports, + usesRequireWrapper, + requireName + ); + + if (shouldWrap) { + wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges); + } + + if (usesRequireWrapper) { + magicString.trim().indent('\t', { + exclude: indentExclusionRanges + }); + const exported = exportMode === 'module' ? `${moduleName}.exports` : exportsName; + magicString.prepend( + `var ${isRequiredName}; + +function ${requireName} () { +\tif (${isRequiredName}) return ${exported}; +\t${isRequiredName} = 1; +` + ).append(` +\treturn ${exported}; +}`); + if (exportMode === 'replace') { + magicString.prepend(`var ${exportsName};\n`); + } + } + + magicString + .trim() + .prepend(shebang + leadingComment + importBlock) + .append(exportBlock); + + return { + code: magicString.toString(), + map: sourceMap ? magicString.generateMap() : null, + syntheticNamedExports: isEsModule || usesRequireWrapper ? false : '__moduleExports', + meta: { commonjs: { ...commonjsMeta, shebang } } + }; +} + +const PLUGIN_NAME = 'commonjs'; + +function commonjs(options = {}) { + const { + ignoreGlobal, + ignoreDynamicRequires, + requireReturnsDefault: requireReturnsDefaultOption, + defaultIsModuleExports: defaultIsModuleExportsOption, + esmExternals + } = options; + const extensions = options.extensions || ['.js']; + const filter = createFilter$1(options.include, options.exclude); + const isPossibleCjsId = (id) => { + const extName = extname(id); + return extName === '.cjs' || (extensions.includes(extName) && filter(id)); + }; + + const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options); + + const getRequireReturnsDefault = + typeof requireReturnsDefaultOption === 'function' + ? requireReturnsDefaultOption + : () => requireReturnsDefaultOption; + + let esmExternalIds; + const isEsmExternal = + typeof esmExternals === 'function' + ? esmExternals + : Array.isArray(esmExternals) + ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id)) + : () => esmExternals; + + const getDefaultIsModuleExports = + typeof defaultIsModuleExportsOption === 'function' + ? defaultIsModuleExportsOption + : () => + typeof defaultIsModuleExportsOption === 'boolean' ? defaultIsModuleExportsOption : 'auto'; + + const dynamicRequireRoot = + typeof options.dynamicRequireRoot === 'string' + ? resolve$3(options.dynamicRequireRoot) + : process.cwd(); + const { commonDir, dynamicRequireModules } = getDynamicRequireModules( + options.dynamicRequireTargets, + dynamicRequireRoot + ); + const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0; + + const ignoreRequire = + typeof options.ignore === 'function' + ? options.ignore + : Array.isArray(options.ignore) + ? (id) => options.ignore.includes(id) + : () => false; + + const getIgnoreTryCatchRequireStatementMode = (id) => { + const mode = + typeof options.ignoreTryCatch === 'function' + ? options.ignoreTryCatch(id) + : Array.isArray(options.ignoreTryCatch) + ? options.ignoreTryCatch.includes(id) + : typeof options.ignoreTryCatch !== 'undefined' + ? options.ignoreTryCatch + : true; + + return { + canConvertRequire: mode !== 'remove' && mode !== true, + shouldRemoveRequire: mode === 'remove' + }; + }; + + const { currentlyResolving, resolveId } = getResolveId(extensions, isPossibleCjsId); + + const sourceMap = options.sourceMap !== false; + + // Initialized in buildStart + let requireResolver; + + function transformAndCheckExports(code, id) { + const normalizedId = normalizePathSlashes(id); + const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements( + this.parse, + code, + id + ); + + const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {}; + if (hasDefaultExport) { + commonjsMeta.hasDefaultExport = true; + } + if (hasNamedExports) { + commonjsMeta.hasNamedExports = true; + } + + if ( + !dynamicRequireModules.has(normalizedId) && + (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) || + (isEsModule && !options.transformMixedEsModules)) + ) { + commonjsMeta.isCommonJS = false; + return { meta: { commonjs: commonjsMeta } }; + } + + const needsRequireWrapper = + !isEsModule && (dynamicRequireModules.has(normalizedId) || strictRequiresFilter(id)); + + const checkDynamicRequire = (position) => { + const normalizedDynamicRequireRoot = normalizePathSlashes(dynamicRequireRoot); + + if (normalizedId.indexOf(normalizedDynamicRequireRoot) !== 0) { + this.error( + { + code: 'DYNAMIC_REQUIRE_OUTSIDE_ROOT', + normalizedId, + normalizedDynamicRequireRoot, + message: `"${normalizedId}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${normalizedDynamicRequireRoot}". You should set dynamicRequireRoot to "${dirname$1( + normalizedId + )}" or one of its parent directories.` + }, + position + ); + } + }; + + return transformCommonjs( + this.parse, + code, + id, + isEsModule, + ignoreGlobal || isEsModule, + ignoreRequire, + ignoreDynamicRequires && !isDynamicRequireModulesEnabled, + getIgnoreTryCatchRequireStatementMode, + sourceMap, + isDynamicRequireModulesEnabled, + dynamicRequireModules, + commonDir, + ast, + getDefaultIsModuleExports(id), + needsRequireWrapper, + requireResolver.resolveRequireSourcesAndUpdateMeta(this), + requireResolver.isRequiredId(id), + checkDynamicRequire, + commonjsMeta + ); + } + + return { + name: PLUGIN_NAME, + + version: version$3, + + options(rawOptions) { + // We inject the resolver in the beginning so that "catch-all-resolver" like node-resolver + // do not prevent our plugin from resolving entry points ot proxies. + const plugins = Array.isArray(rawOptions.plugins) + ? [...rawOptions.plugins] + : rawOptions.plugins + ? [rawOptions.plugins] + : []; + plugins.unshift({ + name: 'commonjs--resolver', + resolveId + }); + return { ...rawOptions, plugins }; + }, + + buildStart({ plugins }) { + validateVersion(this.meta.rollupVersion, peerDependencies.rollup, 'rollup'); + const nodeResolve = plugins.find(({ name }) => name === 'node-resolve'); + if (nodeResolve) { + validateVersion(nodeResolve.version, '^13.0.6', '@rollup/plugin-node-resolve'); + } + if (options.namedExports != null) { + this.warn( + 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.' + ); + } + requireResolver = getRequireResolver( + extensions, + detectCyclesAndConditional, + currentlyResolving + ); + }, + + buildEnd() { + if (options.strictRequires === 'debug') { + const wrappedIds = requireResolver.getWrappedIds(); + if (wrappedIds.length) { + this.warn({ + code: 'WRAPPED_IDS', + ids: wrappedIds, + message: `The commonjs plugin automatically wrapped the following files:\n[\n${wrappedIds + .map((id) => `\t${JSON.stringify(relative$1(process.cwd(), id))}`) + .join(',\n')}\n]` + }); + } else { + this.warn({ + code: 'WRAPPED_IDS', + ids: wrappedIds, + message: 'The commonjs plugin did not wrap any files.' + }); + } + } + }, + + load(id) { + if (id === HELPERS_ID) { + return getHelpersModule(); + } + + if (isWrappedId(id, MODULE_SUFFIX)) { + const name = getName(unwrapId$1(id, MODULE_SUFFIX)); + return { + code: `var ${name} = {exports: {}}; export {${name} as __module}`, + meta: { commonjs: { isCommonJS: false } } + }; + } + + if (isWrappedId(id, EXPORTS_SUFFIX)) { + const name = getName(unwrapId$1(id, EXPORTS_SUFFIX)); + return { + code: `var ${name} = {}; export {${name} as __exports}`, + meta: { commonjs: { isCommonJS: false } } + }; + } + + if (isWrappedId(id, EXTERNAL_SUFFIX)) { + const actualId = unwrapId$1(id, EXTERNAL_SUFFIX); + return getUnknownRequireProxy( + actualId, + isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true + ); + } + + // entry suffix is just appended to not mess up relative external resolution + if (id.endsWith(ENTRY_SUFFIX)) { + const acutalId = id.slice(0, -ENTRY_SUFFIX.length); + const { + meta: { commonjs: commonjsMeta } + } = this.getModuleInfo(acutalId); + const shebang = commonjsMeta?.shebang ?? ''; + return getEntryProxy( + acutalId, + getDefaultIsModuleExports(acutalId), + this.getModuleInfo, + shebang + ); + } + + if (isWrappedId(id, ES_IMPORT_SUFFIX)) { + const actualId = unwrapId$1(id, ES_IMPORT_SUFFIX); + return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId)); + } + + if (id === DYNAMIC_MODULES_ID) { + return getDynamicModuleRegistry( + isDynamicRequireModulesEnabled, + dynamicRequireModules, + commonDir, + ignoreDynamicRequires + ); + } + + if (isWrappedId(id, PROXY_SUFFIX)) { + const actualId = unwrapId$1(id, PROXY_SUFFIX); + return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load); + } + + return null; + }, + + shouldTransformCachedModule(...args) { + return requireResolver.shouldTransformCachedModule.call(this, ...args); + }, + + transform(code, id) { + if (!isPossibleCjsId(id)) return null; + + try { + return transformAndCheckExports.call(this, code, id); + } catch (err) { + return this.error(err, err.pos); + } + } + }; +} + +// Matches the scheme of a URL, eg "http://" +const schemeRegex = /^[\w+.-]+:\/\//; +/** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ +const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; +/** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ +const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; +var UrlType; +(function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; +})(UrlType || (UrlType = {})); +function isAbsoluteUrl(input) { + return schemeRegex.test(input); +} +function isSchemeRelativeUrl(input) { + return input.startsWith('//'); +} +function isAbsolutePath(input) { + return input.startsWith('/'); +} +function isFileUrl(input) { + return input.startsWith('file:'); +} +function isRelative(input) { + return /^[.?#]/.test(input); +} +function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); +} +function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); +} +function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: UrlType.Absolute, + }; +} +function parseUrl$2(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = UrlType.SchemeRelative; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = UrlType.AbsolutePath; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? UrlType.Query + : input.startsWith('#') + ? UrlType.Hash + : UrlType.RelativePath + : UrlType.Empty; + return url; +} +function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} +function mergePaths(url, base) { + normalizePath$4(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } +} +/** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ +function normalizePath$4(url, type) { + const rel = type <= UrlType.RelativePath; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; +} +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +function resolve$2(input, base) { + if (!input && !base) + return ''; + const url = parseUrl$2(input); + let inputType = url.type; + if (base && inputType !== UrlType.Absolute) { + const baseUrl = parseUrl$2(base); + const baseType = baseUrl.type; + switch (inputType) { + case UrlType.Empty: + url.hash = baseUrl.hash; + // fall through + case UrlType.Hash: + url.query = baseUrl.query; + // fall through + case UrlType.Query: + case UrlType.RelativePath: + mergePaths(url, baseUrl); + // fall through + case UrlType.AbsolutePath: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case UrlType.SchemeRelative: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath$4(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case UrlType.Hash: + case UrlType.Query: + return queryHash; + case UrlType.RelativePath: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case UrlType.AbsolutePath: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +function resolve$1(input, base) { + // The base is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + if (base && !base.endsWith('/')) + base += '/'; + return resolve$2(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN$1 = 0; +const SOURCES_INDEX$1 = 1; +const SOURCE_LINE$1 = 2; +const SOURCE_COLUMN$1 = 3; +const NAMES_INDEX$1 = 4; + +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN$1] - b[COLUMN$1]; +} + +let found = false; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN$1] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN$1] !== needle) + break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN$1] !== needle) + break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; +} +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); +} + +const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; +const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +let decodedMappings; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +let traceSegment; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +let originalPositionFor$1; +class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + const from = resolve$1(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve$1(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} +(() => { + decodedMappings = (map) => { + return (map._decoded || (map._decoded = decode(map._encoded))); + }; + traceSegment = (map, line, column) => { + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + return index === -1 ? null : segments[index]; + }; + originalPositionFor$1 = (map, { line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (index === -1) + return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) + return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping(resolvedSources[segment[SOURCES_INDEX$1]], segment[SOURCE_LINE$1] + 1, segment[SOURCE_COLUMN$1], segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null); + }; +})(); +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; +} + +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +let get; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +let put; +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +class SetArray { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } +} +(() => { + get = (strarr, key) => strarr._indexes[key]; + put = (strarr, key) => { + // The key may or may not be present. If it is present, it's a number. + const index = get(strarr, key); + if (index !== undefined) + return index; + const { array, _indexes: indexes } = strarr; + return (indexes[key] = array.push(key) - 1); + }; +})(); + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; + +const NO_NAME = -1; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +let maybeAddSegment; +/** + * Adds/removes the content of the source file to the source map. + */ +let setSourceContent; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let toDecodedMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let toEncodedMap; +// This split declaration is only so that terser can elminiate the static initialization block. +let addSegmentInternal; +/** + * Provides the state to generate a sourcemap. + */ +class GenMapping { + constructor({ file, sourceRoot } = {}) { + this._names = new SetArray(); + this._sources = new SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + } +} +(() => { + maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal(true, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content); + }; + setSourceContent = (map, source, content) => { + const { _sources: sources, _sourcesContent: sourcesContent } = map; + sourcesContent[put(sources, source)] = content; + }; + toDecodedMap = (map) => { + const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + removeEmptyFinalLines(mappings); + return { + version: 3, + file: file || undefined, + names: names.array, + sourceRoot: sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + }; + }; + toEncodedMap = (map) => { + const decoded = toDecodedMap(map); + return Object.assign(Object.assign({}, decoded), { mappings: encode$1(decoded.mappings) }); + }; + // Internal helpers + addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + const line = getLine(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) + return; + return insert(line, index, [genColumn]); + } + const sourcesIndex = put(sources, source); + const namesIndex = name ? put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) + sourcesContent[sourcesIndex] = content !== null && content !== void 0 ? content : null; + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + return insert(line, index, name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] + : [genColumn, sourcesIndex, sourceLine, sourceColumn]); + }; +})(); +function getLine(mappings, index) { + for (let i = mappings.length; i <= index; i++) { + mappings[i] = []; + } + return mappings[index]; +} +function getColumnIndex(line, genColumn) { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) + break; + } + return index; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +function removeEmptyFinalLines(mappings) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) + break; + } + if (len < length) + mappings.length = len; +} +function skipSourceless(line, index) { + // The start of a line is already sourceless, so adding a sourceless segment to the beginning + // doesn't generate any useful information. + if (index === 0) + return true; + const prev = line[index - 1]; + // If the previous segment is also sourceless, then adding another sourceless segment doesn't + // genrate any new information. Else, this segment will end the source/named segment and point to + // a sourceless position, which is useful. + return prev.length === 1; +} +function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + // A source/named segment at the start of a line gives position at that genColumn + if (index === 0) + return false; + const prev = line[index - 1]; + // If the previous segment is sourceless, then we're transitioning to a source. + if (prev.length === 1) + return false; + // If the previous segment maps to the exact same source position, then this segment doesn't + // provide any new position information. + return (sourcesIndex === prev[SOURCES_INDEX] && + sourceLine === prev[SOURCE_LINE] && + sourceColumn === prev[SOURCE_COLUMN] && + namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)); +} + +const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null); +const EMPTY_SOURCES = []; +function SegmentObject(source, line, column, name, content) { + return { source, line, column, name, content }; +} +function Source(map, sources, source, content) { + return { + map, + sources, + source, + content, + }; +} +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +function MapSource(map, sources) { + return Source(map, sources, '', null); +} +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +function OriginalSource(source, content) { + return Source(null, EMPTY_SOURCES, source, content); +} +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +function traceMappings(tree) { + // TODO: Eventually support sourceRoot, which has to be removed because the sources are already + // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. + const gen = new GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + continue; + } + const { column, line, name, content, source } = traced; + maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) + setSourceContent(gen, source, content); + } + } + return gen; +} +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content); + } + const segment = traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); +} + +function asArray(value) { + if (Array.isArray(value)) + return value; + return [value]; +} +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new TraceMap(m, '')); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error(`Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?'); + } + } + let tree = build$2(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; +} +function build$2(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build$2(new TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + return OriginalSource(source, sourceContent); + }); + return MapSource(map, children); +} + +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } +} + +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +function remapping(input, loader, options) { + const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); +} + +var src$3 = {exports: {}}; + +var node$1 = {exports: {}}; + +/** + * Helpers. + */ + +var ms$1; +var hasRequiredMs$1; + +function requireMs$1 () { + if (hasRequiredMs$1) return ms$1; + hasRequiredMs$1 = 1; + var s = 1000; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + + /** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + + ms$1 = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); + }; + + /** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + + function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } + } + + /** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; + } + + /** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; + } + + /** + * Pluralization helper. + */ + + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); + } + return ms$1; +} + +var common$b; +var hasRequiredCommon; + +function requireCommon () { + if (hasRequiredCommon) return common$b; + hasRequiredCommon = 1; + /** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = requireMs$1(); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; + } + + common$b = setup; + return common$b; +} + +/** + * Module dependencies. + */ + +var hasRequiredNode$1; + +function requireNode$1 () { + if (hasRequiredNode$1) return node$1.exports; + hasRequiredNode$1 = 1; + (function (module, exports) { + const tty = require$$0$3; + const util = require$$0$6; + + /** + * This is the Node.js implementation of `debug()`. + */ + + exports.init = init; + exports.log = log; + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' + ); + + /** + * Colors. + */ + + exports.colors = [6, 2, 3, 4, 5, 1]; + + try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = require('supports-color'); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. + } + + /** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + + exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; + }, {}); + + /** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + + function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); + } + + /** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + + function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } + } + + function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; + } + + /** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + + function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); + } + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + + function load() { + return process.env.DEBUG; + } + + /** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + + function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } + } + + module.exports = requireCommon()(exports); + + const {formatters} = module.exports; + + /** + * Map %o to `util.inspect()`, all on a single line. + */ + + formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); + }; + + /** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + + formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); + }; + } (node$1, node$1.exports)); + return node$1.exports; +} + +var browser$3 = {exports: {}}; + +/* eslint-env browser */ + +var hasRequiredBrowser$1; + +function requireBrowser$1 () { + if (hasRequiredBrowser$1) return browser$3.exports; + hasRequiredBrowser$1 = 1; + (function (module, exports) { + /** + * This is the web browser implementation of `debug()`. + */ + + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; + })(); + + /** + * Colors. + */ + + exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' + ]; + + /** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + + // eslint-disable-next-line complexity + function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); + } + + /** + * Colorize log arguments if enabled. + * + * @api public + */ + + function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); + } + + /** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ + exports.log = console.debug || console.log || (() => {}); + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; + } + + /** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + + function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + module.exports = requireCommon()(exports); + + const {formatters} = module.exports; + + /** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + + formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } + }; + } (browser$3, browser$3.exports)); + return browser$3.exports; +} + +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + src$3.exports = requireBrowser$1(); +} else { + src$3.exports = requireNode$1(); +} + +var srcExports$1 = src$3.exports; +var debug$i = /*@__PURE__*/getDefaultExportFromCjs(srcExports$1); + +let pnp; +if (process.versions.pnp) { + try { + pnp = createRequire$1(import.meta.url)('pnpapi'); + } + catch { } +} +function invalidatePackageData(packageCache, pkgPath) { + const pkgDir = path$o.dirname(pkgPath); + packageCache.forEach((pkg, cacheKey) => { + if (pkg.dir === pkgDir) { + packageCache.delete(cacheKey); + } + }); +} +function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) { + if (pnp) { + const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks); + if (packageCache?.has(cacheKey)) + return packageCache.get(cacheKey); + try { + const pkg = pnp.resolveToUnqualified(pkgName, basedir, { + considerBuiltins: false, + }); + if (!pkg) + return null; + const pkgData = loadPackageData(path$o.join(pkg, 'package.json')); + packageCache?.set(cacheKey, pkgData); + return pkgData; + } + catch { + return null; + } + } + const originalBasedir = basedir; + while (basedir) { + if (packageCache) { + const cached = getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks); + if (cached) + return cached; + } + const pkg = path$o.join(basedir, 'node_modules', pkgName, 'package.json'); + try { + if (fs$l.existsSync(pkg)) { + const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg); + const pkgData = loadPackageData(pkgPath); + if (packageCache) { + setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks); + } + return pkgData; + } + } + catch { } + const nextBasedir = path$o.dirname(basedir); + if (nextBasedir === basedir) + break; + basedir = nextBasedir; + } + return null; +} +function findNearestPackageData(basedir, packageCache) { + const originalBasedir = basedir; + while (basedir) { + if (packageCache) { + const cached = getFnpdCache(packageCache, basedir, originalBasedir); + if (cached) + return cached; + } + const pkgPath = path$o.join(basedir, 'package.json'); + if (tryStatSync(pkgPath)?.isFile()) { + try { + const pkgData = loadPackageData(pkgPath); + if (packageCache) { + setFnpdCache(packageCache, pkgData, basedir, originalBasedir); + } + return pkgData; + } + catch { } + } + const nextBasedir = path$o.dirname(basedir); + if (nextBasedir === basedir) + break; + basedir = nextBasedir; + } + return null; +} +// Finds the nearest package.json with a `name` field +function findNearestMainPackageData(basedir, packageCache) { + const nearestPackage = findNearestPackageData(basedir, packageCache); + return (nearestPackage && + (nearestPackage.data.name + ? nearestPackage + : findNearestMainPackageData(path$o.dirname(nearestPackage.dir), packageCache))); +} +function loadPackageData(pkgPath) { + const data = JSON.parse(fs$l.readFileSync(pkgPath, 'utf-8')); + const pkgDir = path$o.dirname(pkgPath); + const { sideEffects } = data; + let hasSideEffects; + if (typeof sideEffects === 'boolean') { + hasSideEffects = () => sideEffects; + } + else if (Array.isArray(sideEffects)) { + const finalPackageSideEffects = sideEffects.map((sideEffect) => { + /* + * The array accepts simple glob patterns to the relevant files... Patterns like *.css, which do not include a /, will be treated like **\/*.css. + * https://webpack.js.org/guides/tree-shaking/ + * https://github.com/vitejs/vite/pull/11807 + */ + if (sideEffect.includes('/')) { + return sideEffect; + } + return `**/${sideEffect}`; + }); + hasSideEffects = createFilter(finalPackageSideEffects, null, { + resolve: pkgDir, + }); + } + else { + hasSideEffects = () => true; + } + const pkg = { + dir: pkgDir, + data, + hasSideEffects, + webResolvedImports: {}, + nodeResolvedImports: {}, + setResolvedCache(key, entry, targetWeb) { + if (targetWeb) { + pkg.webResolvedImports[key] = entry; + } + else { + pkg.nodeResolvedImports[key] = entry; + } + }, + getResolvedCache(key, targetWeb) { + if (targetWeb) { + return pkg.webResolvedImports[key]; + } + else { + return pkg.nodeResolvedImports[key]; + } + }, + }; + return pkg; +} +function watchPackageDataPlugin(packageCache) { + // a list of files to watch before the plugin is ready + const watchQueue = new Set(); + const watchedDirs = new Set(); + const watchFileStub = (id) => { + watchQueue.add(id); + }; + let watchFile = watchFileStub; + const setPackageData = packageCache.set.bind(packageCache); + packageCache.set = (id, pkg) => { + if (!isInNodeModules$1(pkg.dir) && !watchedDirs.has(pkg.dir)) { + watchedDirs.add(pkg.dir); + watchFile(path$o.join(pkg.dir, 'package.json')); + } + return setPackageData(id, pkg); + }; + return { + name: 'vite:watch-package-data', + buildStart() { + watchFile = this.addWatchFile.bind(this); + watchQueue.forEach(watchFile); + watchQueue.clear(); + }, + buildEnd() { + watchFile = watchFileStub; + }, + watchChange(id) { + if (id.endsWith('/package.json')) { + invalidatePackageData(packageCache, path$o.normalize(id)); + } + }, + handleHotUpdate({ file }) { + if (file.endsWith('/package.json')) { + invalidatePackageData(packageCache, path$o.normalize(file)); + } + }, + }; +} +/** + * Get cached `resolvePackageData` value based on `basedir`. When one is found, + * and we've already traversed some directories between `basedir` and `originalBasedir`, + * we cache the value for those in-between directories as well. + * + * This makes it so the fs is only read once for a shared `basedir`. + */ +function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) { + const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks); + const pkgData = packageCache.get(cacheKey); + if (pkgData) { + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData); + }); + return pkgData; + } +} +function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) { + packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData); + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData); + }); +} +// package cache key for `resolvePackageData` +function getRpdCacheKey(pkgName, basedir, preserveSymlinks) { + return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`; +} +/** + * Get cached `findNearestPackageData` value based on `basedir`. When one is found, + * and we've already traversed some directories between `basedir` and `originalBasedir`, + * we cache the value for those in-between directories as well. + * + * This makes it so the fs is only read once for a shared `basedir`. + */ +function getFnpdCache(packageCache, basedir, originalBasedir) { + const cacheKey = getFnpdCacheKey(basedir); + const pkgData = packageCache.get(cacheKey); + if (pkgData) { + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + packageCache.set(getFnpdCacheKey(dir), pkgData); + }); + return pkgData; + } +} +function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) { + packageCache.set(getFnpdCacheKey(basedir), pkgData); + traverseBetweenDirs(originalBasedir, basedir, (dir) => { + packageCache.set(getFnpdCacheKey(dir), pkgData); + }); +} +// package cache key for `findNearestPackageData` +function getFnpdCacheKey(basedir) { + return `fnpd_${basedir}`; +} +/** + * Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir. + * @param longerDir Longer dir path, e.g. `/User/foo/bar/baz` + * @param shorterDir Shorter dir path, e.g. `/User/foo` + */ +function traverseBetweenDirs(longerDir, shorterDir, cb) { + while (longerDir !== shorterDir) { + cb(longerDir); + longerDir = path$o.dirname(longerDir); + } +} + +const createFilter = createFilter$1; +const windowsSlashRE = /\\/g; +function slash$1(p) { + return p.replace(windowsSlashRE, '/'); +} +/** + * Prepend `/@id/` and replace null byte so the id is URL-safe. + * This is prepended to resolved ids that are not valid browser + * import specifiers by the importAnalysis plugin. + */ +function wrapId(id) { + return id.startsWith(VALID_ID_PREFIX) + ? id + : VALID_ID_PREFIX + id.replace('\0', NULL_BYTE_PLACEHOLDER); +} +/** + * Undo {@link wrapId}'s `/@id/` and null byte replacements. + */ +function unwrapId(id) { + return id.startsWith(VALID_ID_PREFIX) + ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, '\0') + : id; +} +const replaceSlashOrColonRE = /[/:]/g; +const replaceDotRE = /\./g; +const replaceNestedIdRE = /(\s*>\s*)/g; +const replaceHashRE = /#/g; +const flattenId = (id) => { + const flatId = limitFlattenIdLength(id + .replace(replaceSlashOrColonRE, '_') + .replace(replaceDotRE, '__') + .replace(replaceNestedIdRE, '___') + .replace(replaceHashRE, '____')); + return flatId; +}; +const FLATTEN_ID_HASH_LENGTH = 8; +const FLATTEN_ID_MAX_FILE_LENGTH = 170; +const limitFlattenIdLength = (id, limit = FLATTEN_ID_MAX_FILE_LENGTH) => { + if (id.length <= limit) { + return id; + } + return id.slice(0, limit - (FLATTEN_ID_HASH_LENGTH + 1)) + '_' + getHash(id); +}; +const normalizeId = (id) => id.replace(replaceNestedIdRE, ' > '); +// Supported by Node, Deno, Bun +const NODE_BUILTIN_NAMESPACE = 'node:'; +// Supported by Deno +const NPM_BUILTIN_NAMESPACE = 'npm:'; +// Supported by Bun +const BUN_BUILTIN_NAMESPACE = 'bun:'; +// Some runtimes like Bun injects namespaced modules here, which is not a node builtin +const nodeBuiltins = builtinModules.filter((id) => !id.includes(':')); +// TODO: Use `isBuiltin` from `node:module`, but Deno doesn't support it +function isBuiltin(id) { + if (process.versions.deno && id.startsWith(NPM_BUILTIN_NAMESPACE)) + return true; + if (process.versions.bun && id.startsWith(BUN_BUILTIN_NAMESPACE)) + return true; + return isNodeBuiltin(id); +} +function isNodeBuiltin(id) { + if (id.startsWith(NODE_BUILTIN_NAMESPACE)) + return true; + return nodeBuiltins.includes(id); +} +function isInNodeModules$1(id) { + return id.includes('node_modules'); +} +function moduleListContains(moduleList, id) { + return moduleList?.some((m) => m === id || id.startsWith(withTrailingSlash(m))); +} +function isOptimizable(id, optimizeDeps) { + const { extensions } = optimizeDeps; + return (OPTIMIZABLE_ENTRY_RE.test(id) || + (extensions?.some((ext) => id.endsWith(ext)) ?? false)); +} +const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/; +const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//; +// TODO: use import() +const _require$2 = createRequire$1(import.meta.url); +// set in bin/vite.js +const filter = process.env.VITE_DEBUG_FILTER; +const DEBUG = process.env.DEBUG; +function createDebugger(namespace, options = {}) { + const log = debug$i(namespace); + const { onlyWhenFocused } = options; + let enabled = log.enabled; + if (enabled && onlyWhenFocused) { + const ns = typeof onlyWhenFocused === 'string' ? onlyWhenFocused : namespace; + enabled = !!DEBUG?.includes(ns); + } + if (enabled) { + return (...args) => { + if (!filter || args.some((a) => a?.includes?.(filter))) { + log(...args); + } + }; + } +} +function testCaseInsensitiveFS() { + if (!CLIENT_ENTRY.endsWith('client.mjs')) { + throw new Error(`cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`); + } + if (!fs$l.existsSync(CLIENT_ENTRY)) { + throw new Error('cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: ' + + CLIENT_ENTRY); + } + return fs$l.existsSync(CLIENT_ENTRY.replace('client.mjs', 'cLiEnT.mjs')); +} +const urlCanParse = URL$3.canParse ?? + // URL.canParse is supported from Node.js 18.17.0+, 20.0.0+ + ((path, base) => { + try { + new URL$3(path, base); + return true; + } + catch { + return false; + } + }); +const isCaseInsensitiveFS = testCaseInsensitiveFS(); +const isWindows$4 = os$4.platform() === 'win32'; +const VOLUME_RE = /^[A-Z]:/i; +function normalizePath$3(id) { + return path$o.posix.normalize(isWindows$4 ? slash$1(id) : id); +} +function fsPathFromId(id) { + const fsPath = normalizePath$3(id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id); + return fsPath[0] === '/' || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`; +} +function fsPathFromUrl(url) { + return fsPathFromId(cleanUrl(url)); +} +function withTrailingSlash(path) { + if (path[path.length - 1] !== '/') { + return `${path}/`; + } + return path; +} +/** + * Check if dir is a parent of file + * + * Warning: parameters are not validated, only works with normalized absolute paths + * + * @param dir - normalized absolute path + * @param file - normalized absolute path + * @returns true if dir is a parent of file + */ +function isParentDirectory(dir, file) { + dir = withTrailingSlash(dir); + return (file.startsWith(dir) || + (isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase()))); +} +/** + * Check if 2 file name are identical + * + * Warning: parameters are not validated, only works with normalized absolute paths + * + * @param file1 - normalized absolute path + * @param file2 - normalized absolute path + * @returns true if both files url are identical + */ +function isSameFileUri(file1, file2) { + return (file1 === file2 || + (isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase())); +} +const postfixRE = /[?#].*$/s; +function cleanUrl(url) { + return url.replace(postfixRE, ''); +} +const externalRE = /^(https?:)?\/\//; +const isExternalUrl = (url) => externalRE.test(url); +const dataUrlRE = /^\s*data:/i; +const isDataUrl = (url) => dataUrlRE.test(url); +const virtualModuleRE = /^virtual-module:.*/; +const virtualModulePrefix = 'virtual-module:'; +const knownJsSrcRE = /\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba|mdx)(?:$|\?)/; +const isJSRequest = (url) => { + url = cleanUrl(url); + if (knownJsSrcRE.test(url)) { + return true; + } + if (!path$o.extname(url) && url[url.length - 1] !== '/') { + return true; + } + return false; +}; +const knownTsRE = /\.(?:ts|mts|cts|tsx)(?:$|\?)/; +const isTsRequest = (url) => knownTsRE.test(url); +const importQueryRE = /(\?|&)import=?(?:&|$)/; +const directRequestRE$1 = /(\?|&)direct=?(?:&|$)/; +const internalPrefixes = [ + FS_PREFIX, + VALID_ID_PREFIX, + CLIENT_PUBLIC_PATH, + ENV_PUBLIC_PATH, +]; +const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`); +const trailingSeparatorRE = /[?&]$/; +const isImportRequest = (url) => importQueryRE.test(url); +const isInternalRequest = (url) => InternalPrefixRE.test(url); +function removeImportQuery(url) { + return url.replace(importQueryRE, '$1').replace(trailingSeparatorRE, ''); +} +function removeDirectQuery(url) { + return url.replace(directRequestRE$1, '$1').replace(trailingSeparatorRE, ''); +} +const replacePercentageRE = /%/g; +function injectQuery(url, queryToInject) { + // encode percents for consistent behavior with pathToFileURL + // see #2614 for details + const resolvedUrl = new URL$3(url.replace(replacePercentageRE, '%25'), 'relative:///'); + const { search, hash } = resolvedUrl; + let pathname = cleanUrl(url); + pathname = isWindows$4 ? slash$1(pathname) : pathname; + return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${hash ?? ''}`; +} +const timestampRE = /\bt=\d{13}&?\b/; +function removeTimestampQuery(url) { + return url.replace(timestampRE, '').replace(trailingSeparatorRE, ''); +} +async function asyncReplace(input, re, replacer) { + let match; + let remaining = input; + let rewritten = ''; + while ((match = re.exec(remaining))) { + rewritten += remaining.slice(0, match.index); + rewritten += await replacer(match); + remaining = remaining.slice(match.index + match[0].length); + } + rewritten += remaining; + return rewritten; +} +function timeFrom(start, subtract = 0) { + const time = performance.now() - start - subtract; + const timeString = (time.toFixed(2) + `ms`).padEnd(5, ' '); + if (time < 10) { + return colors$1.green(timeString); + } + else if (time < 50) { + return colors$1.yellow(timeString); + } + else { + return colors$1.red(timeString); + } +} +/** + * pretty url for logging. + */ +function prettifyUrl(url, root) { + url = removeTimestampQuery(url); + const isAbsoluteFile = url.startsWith(root); + if (isAbsoluteFile || url.startsWith(FS_PREFIX)) { + const file = path$o.relative(root, isAbsoluteFile ? url : fsPathFromId(url)); + return colors$1.dim(file); + } + else { + return colors$1.dim(url); + } +} +function isObject$1(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} +function isDefined(value) { + return value != null; +} +function tryStatSync(file) { + try { + // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist + return fs$l.statSync(file, { throwIfNoEntry: false }); + } + catch { + // Ignore errors + } +} +function lookupFile(dir, fileNames) { + while (dir) { + for (const fileName of fileNames) { + const fullPath = path$o.join(dir, fileName); + if (tryStatSync(fullPath)?.isFile()) + return fullPath; + } + const parentDir = path$o.dirname(dir); + if (parentDir === dir) + return; + dir = parentDir; + } +} +function isFilePathESM(filePath, packageCache) { + if (/\.m[jt]s$/.test(filePath)) { + return true; + } + else if (/\.c[jt]s$/.test(filePath)) { + return false; + } + else { + // check package.json for type: "module" + try { + const pkg = findNearestPackageData(path$o.dirname(filePath), packageCache); + return pkg?.data.type === 'module'; + } + catch { + return false; + } + } +} +const splitRE = /\r?\n/; +const range = 2; +function pad$1(source, n = 2) { + const lines = source.split(splitRE); + return lines.map((l) => ` `.repeat(n) + l).join(`\n`); +} +function posToNumber(source, pos) { + if (typeof pos === 'number') + return pos; + const lines = source.split(splitRE); + const { line, column } = pos; + let start = 0; + for (let i = 0; i < line - 1 && i < lines.length; i++) { + start += lines[i].length + 1; + } + return start + column; +} +function numberToPos(source, offset) { + if (typeof offset !== 'number') + return offset; + if (offset > source.length) { + throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`); + } + const lines = source.split(splitRE); + let counted = 0; + let line = 0; + let column = 0; + for (; line < lines.length; line++) { + const lineLength = lines[line].length + 1; + if (counted + lineLength >= offset) { + column = offset - counted + 1; + break; + } + counted += lineLength; + } + return { line: line + 1, column }; +} +function generateCodeFrame(source, start = 0, end) { + start = Math.max(posToNumber(source, start), 0); + end = Math.min(end !== undefined ? posToNumber(source, end) : start, source.length); + const lines = source.split(splitRE); + let count = 0; + const res = []; + for (let i = 0; i < lines.length; i++) { + count += lines[i].length; + if (count >= start) { + for (let j = i - range; j <= i + range || end > count; j++) { + if (j < 0 || j >= lines.length) + continue; + const line = j + 1; + res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`); + const lineLength = lines[j].length; + if (j === i) { + // push underline + const pad = Math.max(start - (count - lineLength), 0); + const length = Math.max(1, end > count ? lineLength - pad : end - start); + res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)); + } + else if (j > i) { + if (end > count) { + const length = Math.max(Math.min(end - count, lineLength), 1); + res.push(` | ` + '^'.repeat(length)); + } + count += lineLength + 1; + } + } + break; + } + count++; + } + return res.join('\n'); +} +function isFileReadable(filename) { + if (!tryStatSync(filename)) { + return false; + } + try { + // Check if current process has read permission to the file + fs$l.accessSync(filename, fs$l.constants.R_OK); + return true; + } + catch { + return false; + } +} +const splitFirstDirRE = /(.+?)[\\/](.+)/; +/** + * Delete every file and subdirectory. **The given directory must exist.** + * Pass an optional `skip` array to preserve files under the root directory. + */ +function emptyDir(dir, skip) { + const skipInDir = []; + let nested = null; + if (skip?.length) { + for (const file of skip) { + if (path$o.dirname(file) !== '.') { + const matched = file.match(splitFirstDirRE); + if (matched) { + nested ??= new Map(); + const [, nestedDir, skipPath] = matched; + let nestedSkip = nested.get(nestedDir); + if (!nestedSkip) { + nestedSkip = []; + nested.set(nestedDir, nestedSkip); + } + if (!nestedSkip.includes(skipPath)) { + nestedSkip.push(skipPath); + } + } + } + else { + skipInDir.push(file); + } + } + } + for (const file of fs$l.readdirSync(dir)) { + if (skipInDir.includes(file)) { + continue; + } + if (nested?.has(file)) { + emptyDir(path$o.resolve(dir, file), nested.get(file)); + } + else { + fs$l.rmSync(path$o.resolve(dir, file), { recursive: true, force: true }); + } + } +} +function copyDir(srcDir, destDir) { + fs$l.mkdirSync(destDir, { recursive: true }); + for (const file of fs$l.readdirSync(srcDir)) { + const srcFile = path$o.resolve(srcDir, file); + if (srcFile === destDir) { + continue; + } + const destFile = path$o.resolve(destDir, file); + const stat = fs$l.statSync(srcFile); + if (stat.isDirectory()) { + copyDir(srcFile, destFile); + } + else { + fs$l.copyFileSync(srcFile, destFile); + } + } +} +const ERR_SYMLINK_IN_RECURSIVE_READDIR = 'ERR_SYMLINK_IN_RECURSIVE_READDIR'; +async function recursiveReaddir(dir) { + if (!fs$l.existsSync(dir)) { + return []; + } + let dirents; + try { + dirents = await fsp.readdir(dir, { withFileTypes: true }); + } + catch (e) { + if (e.code === 'EACCES') { + // Ignore permission errors + return []; + } + throw e; + } + if (dirents.some((dirent) => dirent.isSymbolicLink())) { + const err = new Error('Symbolic links are not supported in recursiveReaddir'); + err.code = ERR_SYMLINK_IN_RECURSIVE_READDIR; + throw err; + } + const files = await Promise.all(dirents.map((dirent) => { + const res = path$o.resolve(dir, dirent.name); + return dirent.isDirectory() ? recursiveReaddir(res) : normalizePath$3(res); + })); + return files.flat(1); +} +// `fs.realpathSync.native` resolves differently in Windows network drive, +// causing file read errors. skip for now. +// https://github.com/nodejs/node/issues/37737 +let safeRealpathSync = isWindows$4 + ? windowsSafeRealPathSync + : fs$l.realpathSync.native; +// Based on https://github.com/larrybahr/windows-network-drive +// MIT License, Copyright (c) 2017 Larry Bahr +const windowsNetworkMap = new Map(); +function windowsMappedRealpathSync(path) { + const realPath = fs$l.realpathSync.native(path); + if (realPath.startsWith('\\\\')) { + for (const [network, volume] of windowsNetworkMap) { + if (realPath.startsWith(network)) + return realPath.replace(network, volume); + } + } + return realPath; +} +const parseNetUseRE = /^(\w+)? +(\w:) +([^ ]+)\s/; +let firstSafeRealPathSyncRun = false; +function windowsSafeRealPathSync(path) { + if (!firstSafeRealPathSyncRun) { + optimizeSafeRealPathSync(); + firstSafeRealPathSyncRun = true; + } + return fs$l.realpathSync(path); +} +function optimizeSafeRealPathSync() { + // Skip if using Node <18.10 due to MAX_PATH issue: https://github.com/vitejs/vite/issues/12931 + const nodeVersion = process.versions.node.split('.').map(Number); + if (nodeVersion[0] < 18 || (nodeVersion[0] === 18 && nodeVersion[1] < 10)) { + safeRealpathSync = fs$l.realpathSync; + return; + } + // Check the availability `fs.realpathSync.native` + // in Windows virtual and RAM disks that bypass the Volume Mount Manager, in programs such as imDisk + // get the error EISDIR: illegal operation on a directory + try { + fs$l.realpathSync.native(path$o.resolve('./')); + } + catch (error) { + if (error.message.includes('EISDIR: illegal operation on a directory')) { + safeRealpathSync = fs$l.realpathSync; + return; + } + } + exec('net use', (error, stdout) => { + if (error) + return; + const lines = stdout.split('\n'); + // OK Y: \\NETWORKA\Foo Microsoft Windows Network + // OK Z: \\NETWORKA\Bar Microsoft Windows Network + for (const line of lines) { + const m = line.match(parseNetUseRE); + if (m) + windowsNetworkMap.set(m[3], m[2]); + } + if (windowsNetworkMap.size === 0) { + safeRealpathSync = fs$l.realpathSync.native; + } + else { + safeRealpathSync = windowsMappedRealpathSync; + } + }); +} +function ensureWatchedFile(watcher, file, root) { + if (file && + // only need to watch if out of root + !file.startsWith(withTrailingSlash(root)) && + // some rollup plugins use null bytes for private resolved Ids + !file.includes('\0') && + fs$l.existsSync(file)) { + // resolve file to normalized system path + watcher.add(path$o.resolve(file)); + } +} +const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g; +const imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/; +function joinSrcset(ret) { + return ret.map(({ url, descriptor }) => `${url} ${descriptor}`).join(', '); +} +function splitSrcSetDescriptor(srcs) { + return splitSrcSet(srcs) + .map((s) => { + const src = s.replace(escapedSpaceCharacters, ' ').trim(); + const url = imageSetUrlRE.exec(src)?.[0] ?? ''; + return { + url, + descriptor: src.slice(url.length).trim(), + }; + }) + .filter(({ url }) => !!url); +} +function processSrcSet(srcs, replacer) { + return Promise.all(splitSrcSetDescriptor(srcs).map(async ({ url, descriptor }) => ({ + url: await replacer({ url, descriptor }), + descriptor, + }))).then(joinSrcset); +} +function processSrcSetSync(srcs, replacer) { + return joinSrcset(splitSrcSetDescriptor(srcs).map(({ url, descriptor }) => ({ + url: replacer({ url, descriptor }), + descriptor, + }))); +} +const cleanSrcSetRE = /(?:url|image|gradient|cross-fade)\([^)]*\)|"([^"]|(?<=\\)")*"|'([^']|(?<=\\)')*'|data:\w+\/[\w.+\-]+;base64,[\w+/=]+/g; +function splitSrcSet(srcs) { + const parts = []; + // There could be a ',' inside of url(data:...), linear-gradient(...), "data:..." or data:... + const cleanedSrcs = srcs.replace(cleanSrcSetRE, blankReplacer); + let startIndex = 0; + let splitIndex; + do { + splitIndex = cleanedSrcs.indexOf(',', startIndex); + parts.push(srcs.slice(startIndex, splitIndex !== -1 ? splitIndex : undefined)); + startIndex = splitIndex + 1; + } while (splitIndex !== -1); + return parts; +} +const windowsDriveRE = /^[A-Z]:/; +const replaceWindowsDriveRE = /^([A-Z]):\//; +const linuxAbsolutePathRE = /^\/[^/]/; +function escapeToLinuxLikePath(path) { + if (windowsDriveRE.test(path)) { + return path.replace(replaceWindowsDriveRE, '/windows/$1/'); + } + if (linuxAbsolutePathRE.test(path)) { + return `/linux${path}`; + } + return path; +} +const revertWindowsDriveRE = /^\/windows\/([A-Z])\//; +function unescapeToLinuxLikePath(path) { + if (path.startsWith('/linux/')) { + return path.slice('/linux'.length); + } + if (path.startsWith('/windows/')) { + return path.replace(revertWindowsDriveRE, '$1:/'); + } + return path; +} +// based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221 +const nullSourceMap = { + names: [], + sources: [], + mappings: '', + version: 3, +}; +function combineSourcemaps(filename, sourcemapList) { + if (sourcemapList.length === 0 || + sourcemapList.every((m) => m.sources.length === 0)) { + return { ...nullSourceMap }; + } + // hack for parse broken with normalized absolute paths on windows (C:/path/to/something). + // escape them to linux like paths + // also avoid mutation here to prevent breaking plugin's using cache to generate sourcemaps like vue (see #7442) + sourcemapList = sourcemapList.map((sourcemap) => { + const newSourcemaps = { ...sourcemap }; + newSourcemaps.sources = sourcemap.sources.map((source) => source ? escapeToLinuxLikePath(source) : null); + if (sourcemap.sourceRoot) { + newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot); + } + return newSourcemaps; + }); + const escapedFilename = escapeToLinuxLikePath(filename); + // We don't declare type here so we can convert/fake/map as RawSourceMap + let map; //: SourceMap + let mapIndex = 1; + const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined; + if (useArrayInterface) { + map = remapping(sourcemapList, () => null); + } + else { + map = remapping(sourcemapList[0], function loader(sourcefile) { + if (sourcefile === escapedFilename && sourcemapList[mapIndex]) { + return sourcemapList[mapIndex++]; + } + else { + return null; + } + }); + } + if (!map.file) { + delete map.file; + } + // unescape the previous hack + map.sources = map.sources.map((source) => source ? unescapeToLinuxLikePath(source) : source); + map.file = filename; + return map; +} +function unique(arr) { + return Array.from(new Set(arr)); +} +/** + * Returns resolved localhost address when `dns.lookup` result differs from DNS + * + * `dns.lookup` result is same when defaultResultOrder is `verbatim`. + * Even if defaultResultOrder is `ipv4first`, `dns.lookup` result maybe same. + * For example, when IPv6 is not supported on that machine/network. + */ +async function getLocalhostAddressIfDiffersFromDNS() { + const [nodeResult, dnsResult] = await Promise.all([ + promises.lookup('localhost'), + promises.lookup('localhost', { verbatim: true }), + ]); + const isSame = nodeResult.family === dnsResult.family && + nodeResult.address === dnsResult.address; + return isSame ? undefined : nodeResult.address; +} +function diffDnsOrderChange(oldUrls, newUrls) { + return !(oldUrls === newUrls || + (oldUrls && + newUrls && + arrayEqual(oldUrls.local, newUrls.local) && + arrayEqual(oldUrls.network, newUrls.network))); +} +async function resolveHostname(optionsHost) { + let host; + if (optionsHost === undefined || optionsHost === false) { + // Use a secure default + host = 'localhost'; + } + else if (optionsHost === true) { + // If passed --host in the CLI without arguments + host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs) + } + else { + host = optionsHost; + } + // Set host name to localhost when possible + let name = host === undefined || wildcardHosts.has(host) ? 'localhost' : host; + if (host === 'localhost') { + // See #8647 for more details. + const localhostAddr = await getLocalhostAddressIfDiffersFromDNS(); + if (localhostAddr) { + name = localhostAddr; + } + } + return { host, name }; +} +async function resolveServerUrls(server, options, config) { + const address = server.address(); + const isAddressInfo = (x) => x?.address; + if (!isAddressInfo(address)) { + return { local: [], network: [] }; + } + const local = []; + const network = []; + const hostname = await resolveHostname(options.host); + const protocol = options.https ? 'https' : 'http'; + const port = address.port; + const base = config.rawBase === './' || config.rawBase === '' ? '/' : config.rawBase; + if (hostname.host !== undefined && !wildcardHosts.has(hostname.host)) { + let hostnameName = hostname.name; + // ipv6 host + if (hostnameName.includes(':')) { + hostnameName = `[${hostnameName}]`; + } + const address = `${protocol}://${hostnameName}:${port}${base}`; + if (loopbackHosts.has(hostname.host)) { + local.push(address); + } + else { + network.push(address); + } + } + else { + Object.values(os$4.networkInterfaces()) + .flatMap((nInterface) => nInterface ?? []) + .filter((detail) => detail && + detail.address && + (detail.family === 'IPv4' || + // @ts-expect-error Node 18.0 - 18.3 returns number + detail.family === 4)) + .forEach((detail) => { + let host = detail.address.replace('127.0.0.1', hostname.name); + // ipv6 host + if (host.includes(':')) { + host = `[${host}]`; + } + const url = `${protocol}://${host}:${port}${base}`; + if (detail.address.includes('127.0.0.1')) { + local.push(url); + } + else { + network.push(url); + } + }); + } + return { local, network }; +} +function arraify(target) { + return Array.isArray(target) ? target : [target]; +} +// Taken from https://stackoverflow.com/a/36328890 +const multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g; +const singlelineCommentsRE = /\/\/.*/g; +const requestQuerySplitRE = /\?(?!.*[/|}])/; +const requestQueryMaybeEscapedSplitRE = /\\?\?(?!.*[/|}])/; +function parseRequest(id) { + const [_, search] = id.split(requestQuerySplitRE, 2); + if (!search) { + return null; + } + return Object.fromEntries(new URLSearchParams(search)); +} +const blankReplacer = (match) => ' '.repeat(match.length); +function getHash(text, length = 8) { + const h = createHash$2('sha256').update(text).digest('hex').substring(0, length); + if (length <= 64) + return h; + return h.padEnd(length, '_'); +} +const _dirname = path$o.dirname(fileURLToPath(import.meta.url)); +const requireResolveFromRootWithFallback = (root, id) => { + // check existence first, so if the package is not found, + // it won't be cached by nodejs, since there isn't a way to invalidate them: + // https://github.com/nodejs/node/issues/44663 + const found = resolvePackageData(id, root) || resolvePackageData(id, _dirname); + if (!found) { + const error = new Error(`${JSON.stringify(id)} not found.`); + error.code = 'MODULE_NOT_FOUND'; + throw error; + } + // actually resolve + // Search in the root directory first, and fallback to the default require paths. + return _require$2.resolve(id, { paths: [root, _dirname] }); +}; +function emptyCssComments(raw) { + return raw.replace(multilineCommentsRE, (s) => ' '.repeat(s.length)); +} +function backwardCompatibleWorkerPlugins(plugins) { + if (Array.isArray(plugins)) { + return plugins; + } + if (typeof plugins === 'function') { + return plugins(); + } + return []; +} +function mergeConfigRecursively(defaults, overrides, rootPath) { + const merged = { ...defaults }; + for (const key in overrides) { + const value = overrides[key]; + if (value == null) { + continue; + } + const existing = merged[key]; + if (existing == null) { + merged[key] = value; + continue; + } + // fields that require special handling + if (key === 'alias' && (rootPath === 'resolve' || rootPath === '')) { + merged[key] = mergeAlias(existing, value); + continue; + } + else if (key === 'assetsInclude' && rootPath === '') { + merged[key] = [].concat(existing, value); + continue; + } + else if (key === 'noExternal' && + rootPath === 'ssr' && + (existing === true || value === true)) { + merged[key] = true; + continue; + } + else if (key === 'plugins' && rootPath === 'worker') { + merged[key] = () => [ + ...backwardCompatibleWorkerPlugins(existing), + ...backwardCompatibleWorkerPlugins(value), + ]; + continue; + } + if (Array.isArray(existing) || Array.isArray(value)) { + merged[key] = [...arraify(existing ?? []), ...arraify(value ?? [])]; + continue; + } + if (isObject$1(existing) && isObject$1(value)) { + merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key); + continue; + } + merged[key] = value; + } + return merged; +} +function mergeConfig(defaults, overrides, isRoot = true) { + if (typeof defaults === 'function' || typeof overrides === 'function') { + throw new Error(`Cannot merge config in form of callback`); + } + return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.'); +} +function mergeAlias(a, b) { + if (!a) + return b; + if (!b) + return a; + if (isObject$1(a) && isObject$1(b)) { + return { ...a, ...b }; + } + // the order is flipped because the alias is resolved from top-down, + // where the later should have higher priority + return [...normalizeAlias(b), ...normalizeAlias(a)]; +} +function normalizeAlias(o = []) { + return Array.isArray(o) + ? o.map(normalizeSingleAlias) + : Object.keys(o).map((find) => normalizeSingleAlias({ + find, + replacement: o[find], + })); +} +// https://github.com/vitejs/vite/issues/1363 +// work around https://github.com/rollup/plugins/issues/759 +function normalizeSingleAlias({ find, replacement, customResolver, }) { + if (typeof find === 'string' && + find[find.length - 1] === '/' && + replacement[replacement.length - 1] === '/') { + find = find.slice(0, find.length - 1); + replacement = replacement.slice(0, replacement.length - 1); + } + const alias = { + find, + replacement, + }; + if (customResolver) { + alias.customResolver = customResolver; + } + return alias; +} +/** + * Transforms transpiled code result where line numbers aren't altered, + * so we can skip sourcemap generation during dev + */ +function transformStableResult(s, id, config) { + return { + code: s.toString(), + map: config.command === 'build' && config.build.sourcemap + ? s.generateMap({ hires: 'boundary', source: id }) + : null, + }; +} +async function asyncFlatten(arr) { + do { + arr = (await Promise.all(arr)).flat(Infinity); + } while (arr.some((v) => v?.then)); + return arr; +} +// strip UTF-8 BOM +function stripBomTag(content) { + if (content.charCodeAt(0) === 0xfeff) { + return content.slice(1); + } + return content; +} +const windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/; +/** + * path.isAbsolute also returns true for drive relative paths on windows (e.g. /something) + * this function returns false for them but true for absolute paths (e.g. C:/something) + */ +const isNonDriveRelativeAbsolutePath = (p) => { + if (!isWindows$4) + return p[0] === '/'; + return windowsDrivePathPrefixRE.test(p); +}; +/** + * Determine if a file is being requested with the correct case, to ensure + * consistent behavior between dev and prod and across operating systems. + */ +function shouldServeFile(filePath, root) { + // can skip case check on Linux + if (!isCaseInsensitiveFS) + return true; + return hasCorrectCase(filePath, root); +} +/** + * Note that we can't use realpath here, because we don't want to follow + * symlinks. + */ +function hasCorrectCase(file, assets) { + if (file === assets) + return true; + const parent = path$o.dirname(file); + if (fs$l.readdirSync(parent).includes(path$o.basename(file))) { + return hasCorrectCase(parent, assets); + } + return false; +} +function joinUrlSegments(a, b) { + if (!a || !b) { + return a || b || ''; + } + if (a[a.length - 1] === '/') { + a = a.substring(0, a.length - 1); + } + if (b[0] !== '/') { + b = '/' + b; + } + return a + b; +} +function removeLeadingSlash(str) { + return str[0] === '/' ? str.slice(1) : str; +} +function stripBase(path, base) { + if (path === base) { + return '/'; + } + const devBase = withTrailingSlash(base); + return path.startsWith(devBase) ? path.slice(devBase.length - 1) : path; +} +function arrayEqual(a, b) { + if (a === b) + return true; + if (a.length !== b.length) + return false; + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) + return false; + } + return true; +} +function evalValue(rawValue) { + const fn = new Function(` + var console, exports, global, module, process, require + return (\n${rawValue}\n) + `); + return fn(); +} +function getNpmPackageName(importPath) { + const parts = importPath.split('/'); + if (parts[0][0] === '@') { + if (!parts[1]) + return null; + return `${parts[0]}/${parts[1]}`; + } + else { + return parts[0]; + } +} +const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g; +function escapeRegex(str) { + return str.replace(escapeRegexRE, '\\$&'); +} +function getPackageManagerCommand(type = 'install') { + const packageManager = process.env.npm_config_user_agent?.split(' ')[0].split('/')[0] || 'npm'; + switch (type) { + case 'install': + return packageManager === 'npm' ? 'npm install' : `${packageManager} add`; + case 'uninstall': + return packageManager === 'npm' + ? 'npm uninstall' + : `${packageManager} remove`; + case 'update': + return packageManager === 'yarn' + ? 'yarn upgrade' + : `${packageManager} update`; + default: + throw new TypeError(`Unknown command type: ${type}`); + } +} +function isDevServer(server) { + return 'pluginContainer' in server; +} +function promiseWithResolvers() { + let resolve; + let reject; + const promise = new Promise((_resolve, _reject) => { + resolve = _resolve; + reject = _reject; + }); + return { promise, resolve, reject }; +} + +/* eslint no-console: 0 */ +const LogLevels = { + silent: 0, + error: 1, + warn: 2, + info: 3, +}; +let lastType; +let lastMsg; +let sameCount = 0; +function clearScreen() { + const repeatCount = process.stdout.rows - 2; + const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : ''; + console.log(blank); + readline.cursorTo(process.stdout, 0, 0); + readline.clearScreenDown(process.stdout); +} +function createLogger(level = 'info', options = {}) { + if (options.customLogger) { + return options.customLogger; + } + const timeFormatter = new Intl.DateTimeFormat(undefined, { + hour: 'numeric', + minute: 'numeric', + second: 'numeric', + }); + const loggedErrors = new WeakSet(); + const { prefix = '[vite]', allowClearScreen = true } = options; + const thresh = LogLevels[level]; + const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI; + const clear = canClearScreen ? clearScreen : () => { }; + function output(type, msg, options = {}) { + if (thresh >= LogLevels[type]) { + const method = type === 'info' ? 'log' : type; + const format = () => { + if (options.timestamp) { + const tag = type === 'info' + ? colors$1.cyan(colors$1.bold(prefix)) + : type === 'warn' + ? colors$1.yellow(colors$1.bold(prefix)) + : colors$1.red(colors$1.bold(prefix)); + return `${colors$1.dim(timeFormatter.format(new Date()))} ${tag} ${msg}`; + } + else { + return msg; + } + }; + if (options.error) { + loggedErrors.add(options.error); + } + if (canClearScreen) { + if (type === lastType && msg === lastMsg) { + sameCount++; + clear(); + console[method](format(), colors$1.yellow(`(x${sameCount + 1})`)); + } + else { + sameCount = 0; + lastMsg = msg; + lastType = type; + if (options.clear) { + clear(); + } + console[method](format()); + } + } + else { + console[method](format()); + } + } + } + const warnedMessages = new Set(); + const logger = { + hasWarned: false, + info(msg, opts) { + output('info', msg, opts); + }, + warn(msg, opts) { + logger.hasWarned = true; + output('warn', msg, opts); + }, + warnOnce(msg, opts) { + if (warnedMessages.has(msg)) + return; + logger.hasWarned = true; + output('warn', msg, opts); + warnedMessages.add(msg); + }, + error(msg, opts) { + logger.hasWarned = true; + output('error', msg, opts); + }, + clearScreen(type) { + if (thresh >= LogLevels[type]) { + clear(); + } + }, + hasErrorLogged(error) { + return loggedErrors.has(error); + }, + }; + return logger; +} +function printServerUrls(urls, optionsHost, info) { + const colorUrl = (url) => colors$1.cyan(url.replace(/:(\d+)\//, (_, port) => `:${colors$1.bold(port)}/`)); + for (const url of urls.local) { + info(` ${colors$1.green('➜')} ${colors$1.bold('Local')}: ${colorUrl(url)}`); + } + for (const url of urls.network) { + info(` ${colors$1.green('➜')} ${colors$1.bold('Network')}: ${colorUrl(url)}`); + } + if (urls.network.length === 0 && optionsHost === undefined) { + info(colors$1.dim(` ${colors$1.green('➜')} ${colors$1.bold('Network')}: use `) + + colors$1.bold('--host') + + colors$1.dim(' to expose')); + } +} + +const groups = [ + { name: 'Assets', color: colors$1.green }, + { name: 'CSS', color: colors$1.magenta }, + { name: 'JS', color: colors$1.cyan }, +]; +const COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml)$/; +function buildReporterPlugin(config) { + const compress = promisify$4(gzip); + const chunkLimit = config.build.chunkSizeWarningLimit; + const numberFormatter = new Intl.NumberFormat('en', { + maximumFractionDigits: 2, + minimumFractionDigits: 2, + }); + const displaySize = (bytes) => { + return `${numberFormatter.format(bytes / 1000)} kB`; + }; + const tty = process.stdout.isTTY && !process.env.CI; + const shouldLogInfo = LogLevels[config.logLevel || 'info'] >= LogLevels.info; + let hasTransformed = false; + let hasRenderedChunk = false; + let hasCompressChunk = false; + let transformedCount = 0; + let chunkCount = 0; + let compressedCount = 0; + let startTime = Date.now(); + let buildFailed = false; + async function getCompressedSize(code) { + if (config.build.ssr || !config.build.reportCompressedSize) { + return null; + } + if (shouldLogInfo && !hasCompressChunk) { + if (!tty) { + config.logger.info('computing gzip size...'); + } + else { + writeLine('computing gzip size (0)...'); + } + hasCompressChunk = true; + } + const compressed = await compress(typeof code === 'string' ? code : Buffer.from(code)); + compressedCount++; + if (shouldLogInfo && tty) { + writeLine(`computing gzip size (${compressedCount})...`); + } + return compressed.length; + } + const logTransform = throttle((id) => { + writeLine(`transforming (${transformedCount}) ${colors$1.dim(path$o.relative(config.root, id))}`); + }); + return { + name: 'vite:reporter', + transform(_, id) { + transformedCount++; + if (shouldLogInfo) { + if (!tty) { + if (!hasTransformed) { + config.logger.info(`transforming...`); + } + } + else { + if (id.includes(`?`)) + return; + logTransform(id); + } + hasTransformed = true; + } + return null; + }, + options() { + startTime = Date.now(); + }, + buildStart() { + transformedCount = 0; + }, + buildEnd(error) { + buildFailed = !!error; + if (shouldLogInfo) { + if (tty) { + clearLine$1(); + } + config.logger.info(`${colors$1.green(`✓`)} ${transformedCount} modules transformed.`); + } + }, + renderStart() { + chunkCount = 0; + compressedCount = 0; + }, + renderChunk(code, chunk, options) { + if (!options.inlineDynamicImports) { + for (const id of chunk.moduleIds) { + const module = this.getModuleInfo(id); + if (!module) + continue; + // When a dynamic importer shares a chunk with the imported module, + // warn that the dynamic imported module will not be moved to another chunk (#12850). + if (module.importers.length && module.dynamicImporters.length) { + // Filter out the intersection of dynamic importers and sibling modules in + // the same chunk. The intersecting dynamic importers' dynamic import is not + // expected to work. Note we're only detecting the direct ineffective + // dynamic import here. + const detectedIneffectiveDynamicImport = module.dynamicImporters.some((id) => !isInNodeModules$1(id) && chunk.moduleIds.includes(id)); + if (detectedIneffectiveDynamicImport) { + this.warn(`\n(!) ${module.id} is dynamically imported by ${module.dynamicImporters.join(', ')} but also statically imported by ${module.importers.join(', ')}, dynamic import will not move module into another chunk.\n`); + } + } + } + } + chunkCount++; + if (shouldLogInfo) { + if (!tty) { + if (!hasRenderedChunk) { + config.logger.info('rendering chunks...'); + } + } + else { + writeLine(`rendering chunks (${chunkCount})...`); + } + hasRenderedChunk = true; + } + return null; + }, + generateBundle() { + if (shouldLogInfo && tty) + clearLine$1(); + }, + async writeBundle({ dir: outDir }, output) { + let hasLargeChunks = false; + if (shouldLogInfo) { + const entries = (await Promise.all(Object.values(output).map(async (chunk) => { + if (chunk.type === 'chunk') { + return { + name: chunk.fileName, + group: 'JS', + size: chunk.code.length, + compressedSize: await getCompressedSize(chunk.code), + mapSize: chunk.map ? chunk.map.toString().length : null, + }; + } + else { + if (chunk.fileName.endsWith('.map')) + return null; + const isCSS = chunk.fileName.endsWith('.css'); + const isCompressible = isCSS || COMPRESSIBLE_ASSETS_RE.test(chunk.fileName); + return { + name: chunk.fileName, + group: isCSS ? 'CSS' : 'Assets', + size: chunk.source.length, + mapSize: null, + compressedSize: isCompressible + ? await getCompressedSize(chunk.source) + : null, + }; + } + }))).filter(isDefined); + if (tty) + clearLine$1(); + let longest = 0; + let biggestSize = 0; + let biggestMap = 0; + let biggestCompressSize = 0; + for (const entry of entries) { + if (entry.name.length > longest) + longest = entry.name.length; + if (entry.size > biggestSize) + biggestSize = entry.size; + if (entry.mapSize && entry.mapSize > biggestMap) { + biggestMap = entry.mapSize; + } + if (entry.compressedSize && + entry.compressedSize > biggestCompressSize) { + biggestCompressSize = entry.compressedSize; + } + } + const sizePad = displaySize(biggestSize).length; + const mapPad = displaySize(biggestMap).length; + const compressPad = displaySize(biggestCompressSize).length; + const relativeOutDir = normalizePath$3(path$o.relative(config.root, path$o.resolve(config.root, outDir ?? config.build.outDir))); + const assetsDir = path$o.join(config.build.assetsDir, '/'); + for (const group of groups) { + const filtered = entries.filter((e) => e.group === group.name); + if (!filtered.length) + continue; + for (const entry of filtered.sort((a, z) => a.size - z.size)) { + const isLarge = group.name === 'JS' && entry.size / 1000 > chunkLimit; + if (isLarge) + hasLargeChunks = true; + const sizeColor = isLarge ? colors$1.yellow : colors$1.dim; + let log = colors$1.dim(withTrailingSlash(relativeOutDir)); + log += + !config.build.lib && + entry.name.startsWith(withTrailingSlash(assetsDir)) + ? colors$1.dim(assetsDir) + + group.color(entry.name + .slice(assetsDir.length) + .padEnd(longest + 2 - assetsDir.length)) + : group.color(entry.name.padEnd(longest + 2)); + log += colors$1.bold(sizeColor(displaySize(entry.size).padStart(sizePad))); + if (entry.compressedSize) { + log += colors$1.dim(` │ gzip: ${displaySize(entry.compressedSize).padStart(compressPad)}`); + } + if (entry.mapSize) { + log += colors$1.dim(` │ map: ${displaySize(entry.mapSize).padStart(mapPad)}`); + } + config.logger.info(log); + } + } + } + else { + hasLargeChunks = Object.values(output).some((chunk) => { + return chunk.type === 'chunk' && chunk.code.length / 1000 > chunkLimit; + }); + } + if (hasLargeChunks && + config.build.minify && + !config.build.lib && + !config.build.ssr) { + config.logger.warn(colors$1.yellow(`\n(!) Some chunks are larger than ${chunkLimit} kB after minification. Consider:\n` + + `- Using dynamic import() to code-split the application\n` + + `- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks\n` + + `- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`)); + } + }, + closeBundle() { + if (shouldLogInfo && !config.build.watch && !buildFailed) { + config.logger.info(`${colors$1.green(`✓ built in ${displayTime(Date.now() - startTime)}`)}`); + } + }, + }; +} +function writeLine(output) { + clearLine$1(); + if (output.length < process.stdout.columns) { + process.stdout.write(output); + } + else { + process.stdout.write(output.substring(0, process.stdout.columns - 1)); + } +} +function clearLine$1() { + process.stdout.clearLine(0); + process.stdout.cursorTo(0); +} +function throttle(fn) { + let timerHandle = null; + return (...args) => { + if (timerHandle) + return; + fn(...args); + timerHandle = setTimeout(() => { + timerHandle = null; + }, 100); + }; +} +function displayTime(time) { + // display: {X}ms + if (time < 1000) { + return `${time}ms`; + } + time = time / 1000; + // display: {X}s + if (time < 60) { + return `${time.toFixed(2)}s`; + } + const mins = parseInt((time / 60).toString()); + const seconds = time % 60; + // display: {X}m {Y}s + return `${mins}m${seconds < 1 ? '' : ` ${seconds.toFixed(0)}s`}`; +} + +const POSIX_SEP_RE = new RegExp('\\' + path$o.posix.sep, 'g'); +const NATIVE_SEP_RE = new RegExp('\\' + path$o.sep, 'g'); +/** @type {Map}*/ +const PATTERN_REGEX_CACHE = new Map(); +const GLOB_ALL_PATTERN = `**/*`; +const TS_EXTENSIONS = ['.ts', '.tsx', '.mts', '.cts']; +const JS_EXTENSIONS = ['.js', '.jsx', '.mjs', '.cjs']; +const TSJS_EXTENSIONS = TS_EXTENSIONS.concat(JS_EXTENSIONS); +const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext) => ext.substring(1)).join('|')})`; +const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext) => ext.substring(1)).join( + '|' +)})`; +const IS_POSIX = path$o.posix.sep === path$o.sep; + +/** + * @template T + * @returns {{resolve:(result:T)=>void, reject:(error:any)=>void, promise: Promise}} + */ +function makePromise() { + let resolve, reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +/** + * @param {string} filename + * @param {import('./cache.js').TSConfckCache} [cache] + * @returns {Promise} + */ +async function resolveTSConfigJson(filename, cache) { + if (path$o.extname(filename) !== '.json') { + return; // ignore files that are not json + } + const tsconfig = path$o.resolve(filename); + if (cache && (cache.hasParseResult(tsconfig) || cache.hasParseResult(filename))) { + return tsconfig; + } + return promises$1.stat(tsconfig).then((stat) => { + if (stat.isFile() || stat.isFIFO()) { + return tsconfig; + } else { + throw new Error(`${filename} exists but is not a regular file.`); + } + }); +} + +/** + * + * @param {string} dir an absolute directory path + * @returns {boolean} if dir path includes a node_modules segment + */ +const isInNodeModules = IS_POSIX + ? (dir) => dir.includes('/node_modules/') + : (dir) => dir.match(/[/\\]node_modules[/\\]/); + +/** + * convert posix separator to native separator + * + * eg. + * windows: C:/foo/bar -> c:\foo\bar + * linux: /foo/bar -> /foo/bar + * + * @param {string} filename with posix separators + * @returns {string} filename with native separators + */ +const posix2native = IS_POSIX + ? (filename) => filename + : (filename) => filename.replace(POSIX_SEP_RE, path$o.sep); + +/** + * convert native separator to posix separator + * + * eg. + * windows: C:\foo\bar -> c:/foo/bar + * linux: /foo/bar -> /foo/bar + * + * @param {string} filename - filename with native separators + * @returns {string} filename with posix separators + */ +const native2posix = IS_POSIX + ? (filename) => filename + : (filename) => filename.replace(NATIVE_SEP_RE, path$o.posix.sep); + +/** + * converts params to native separator, resolves path and converts native back to posix + * + * needed on windows to handle posix paths in tsconfig + * + * @param dir {string|null} directory to resolve from + * @param filename {string} filename or pattern to resolve + * @returns string + */ +const resolve2posix = IS_POSIX + ? (dir, filename) => (dir ? path$o.resolve(dir, filename) : path$o.resolve(filename)) + : (dir, filename) => + native2posix( + dir + ? path$o.resolve(posix2native(dir), posix2native(filename)) + : path$o.resolve(posix2native(filename)) + ); + +/** + * + * @param {import('./public.d.ts').TSConfckParseResult} result + * @param {import('./public.d.ts').TSConfckParseOptions} [options] + * @returns {string[]} + */ +function resolveReferencedTSConfigFiles(result, options) { + const dir = path$o.dirname(result.tsconfigFile); + return result.tsconfig.references.map((ref) => { + const refPath = ref.path.endsWith('.json') + ? ref.path + : path$o.join(ref.path, options?.configName ?? 'tsconfig.json'); + return resolve2posix(dir, refPath); + }); +} + +/** + * @param {string} filename + * @param {import('./public.d.ts').TSConfckParseResult} result + * @returns {import('./public.d.ts').TSConfckParseResult} + */ +function resolveSolutionTSConfig(filename, result) { + const allowJs = result.tsconfig.compilerOptions?.allowJs; + const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS; + if ( + result.referenced && + extensions.some((ext) => filename.endsWith(ext)) && + !isIncluded(filename, result) + ) { + const solutionTSConfig = result.referenced.find((referenced) => + isIncluded(filename, referenced) + ); + if (solutionTSConfig) { + return solutionTSConfig; + } + } + return result; +} + +/** + * + * @param {string} filename + * @param {import('./public.d.ts').TSConfckParseResult} result + * @returns {boolean} + */ +function isIncluded(filename, result) { + const dir = native2posix(path$o.dirname(result.tsconfigFile)); + const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file)); + const absoluteFilename = resolve2posix(null, filename); + if (files.includes(filename)) { + return true; + } + const allowJs = result.tsconfig.compilerOptions?.allowJs; + const isIncluded = isGlobMatch( + absoluteFilename, + dir, + result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN]), + allowJs + ); + if (isIncluded) { + const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || [], allowJs); + return !isExcluded; + } + return false; +} + +/** + * test filenames agains glob patterns in tsconfig + * + * @param filename {string} posix style abolute path to filename to test + * @param dir {string} posix style absolute path to directory of tsconfig containing patterns + * @param patterns {string[]} glob patterns to match against + * @param allowJs {boolean} allowJs setting in tsconfig to include js extensions in checks + * @returns {boolean} true when at least one pattern matches filename + */ +function isGlobMatch(filename, dir, patterns, allowJs) { + const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS; + return patterns.some((pattern) => { + // filename must end with part of pattern that comes after last wildcard + let lastWildcardIndex = pattern.length; + let hasWildcard = false; + for (let i = pattern.length - 1; i > -1; i--) { + if (pattern[i] === '*' || pattern[i] === '?') { + lastWildcardIndex = i; + hasWildcard = true; + break; + } + } + + // if pattern does not end with wildcard, filename must end with pattern after last wildcard + if ( + lastWildcardIndex < pattern.length - 1 && + !filename.endsWith(pattern.slice(lastWildcardIndex + 1)) + ) { + return false; + } + + // if pattern ends with *, filename must end with a default extension + if (pattern.endsWith('*') && !extensions.some((ext) => filename.endsWith(ext))) { + return false; + } + + // for **/* , filename must start with the dir + if (pattern === GLOB_ALL_PATTERN) { + return filename.startsWith(`${dir}/`); + } + + const resolvedPattern = resolve2posix(dir, pattern); + + // filename must start with part of pattern that comes before first wildcard + let firstWildcardIndex = -1; + for (let i = 0; i < resolvedPattern.length; i++) { + if (resolvedPattern[i] === '*' || resolvedPattern[i] === '?') { + firstWildcardIndex = i; + hasWildcard = true; + break; + } + } + if ( + firstWildcardIndex > 1 && + !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1)) + ) { + return false; + } + + // if no wildcard in pattern, filename must be equal to resolved pattern + if (!hasWildcard) { + return filename === resolvedPattern; + } + + // complex pattern, use regex to check it + if (PATTERN_REGEX_CACHE.has(resolvedPattern)) { + return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename); + } + const regex = pattern2regex(resolvedPattern, allowJs); + PATTERN_REGEX_CACHE.set(resolvedPattern, regex); + return regex.test(filename); + }); +} + +/** + * @param {string} resolvedPattern + * @param {boolean} allowJs + * @returns {RegExp} + */ +function pattern2regex(resolvedPattern, allowJs) { + let regexStr = '^'; + for (let i = 0; i < resolvedPattern.length; i++) { + const char = resolvedPattern[i]; + if (char === '?') { + regexStr += '[^\\/]'; + continue; + } + if (char === '*') { + if (resolvedPattern[i + 1] === '*' && resolvedPattern[i + 2] === '/') { + i += 2; + regexStr += '(?:[^\\/]*\\/)*'; // zero or more path segments + continue; + } + regexStr += '[^\\/]*'; + continue; + } + if ('/.+^${}()|[]\\'.includes(char)) { + regexStr += `\\`; + } + regexStr += char; + } + + // add known file endings if pattern ends on * + if (resolvedPattern.endsWith('*')) { + regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP; + } + regexStr += '$'; + + return new RegExp(regexStr); +} + +/** + * find the closest tsconfig.json file + * + * @param {string} filename - path to file to find tsconfig for (absolute or relative to cwd) + * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options + * @returns {Promise} absolute path to closest tsconfig.json or null if not found + */ +async function find(filename, options) { + let dir = path$o.dirname(path$o.resolve(filename)); + if (options?.ignoreNodeModules && isInNodeModules(dir)) { + return null; + } + const cache = options?.cache; + const configName = options?.configName ?? 'tsconfig.json'; + if (cache?.hasConfigPath(dir, configName)) { + return cache.getConfigPath(dir, configName); + } + const { /** @type {Promise} */ promise, resolve, reject } = makePromise(); + if (options?.root && !path$o.isAbsolute(options.root)) { + options.root = path$o.resolve(options.root); + } + findUp(dir, { promise, resolve, reject }, options); + return promise; +} + +/** + * + * @param {string} dir + * @param {{promise:Promise,resolve:(result:string|null)=>void,reject:(err:any)=>void}} madePromise + * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options + */ +function findUp(dir, { resolve, reject, promise }, options) { + const { cache, root, configName } = options ?? {}; + if (cache) { + if (cache.hasConfigPath(dir, configName)) { + let cached; + try { + cached = cache.getConfigPath(dir, configName); + } catch (e) { + reject(e); + return; + } + if (cached?.then) { + cached.then(resolve).catch(reject); + } else { + resolve(cached); + } + } else { + cache.setConfigPath(dir, promise, configName); + } + } + const tsconfig = path$o.join(dir, options?.configName ?? 'tsconfig.json'); + fs$l.stat(tsconfig, (err, stats) => { + if (stats && (stats.isFile() || stats.isFIFO())) { + resolve(tsconfig); + } else if (err?.code !== 'ENOENT') { + reject(err); + } else { + let parent; + if (root === dir || (parent = path$o.dirname(dir)) === dir) { + resolve(null); + } else { + findUp(parent, { promise, resolve, reject }, options); + } + } + }); +} + +/* + this file contains code from strip-bom and strip-json-comments by Sindre Sorhus + https://github.com/sindresorhus/strip-json-comments/blob/v4.0.0/index.js + https://github.com/sindresorhus/strip-bom/blob/v5.0.0/index.js + licensed under MIT, see ../LICENSE +*/ + +/** + * convert content of tsconfig.json to regular json + * + * @param {string} tsconfigJson - content of tsconfig.json + * @returns {string} content as regular json, comments and dangling commas have been replaced with whitespace + */ +function toJson(tsconfigJson) { + const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson))); + if (stripped.trim() === '') { + // only whitespace left after stripping, return empty object so that JSON.parse still works + return '{}'; + } else { + return stripped; + } +} + +/** + * replace dangling commas from pseudo-json string with single space + * implementation heavily inspired by strip-json-comments + * + * @param {string} pseudoJson + * @returns {string} + */ +function stripDanglingComma(pseudoJson) { + let insideString = false; + let offset = 0; + let result = ''; + let danglingCommaPos = null; + for (let i = 0; i < pseudoJson.length; i++) { + const currentCharacter = pseudoJson[i]; + if (currentCharacter === '"') { + const escaped = isEscaped(pseudoJson, i); + if (!escaped) { + insideString = !insideString; + } + } + if (insideString) { + danglingCommaPos = null; + continue; + } + if (currentCharacter === ',') { + danglingCommaPos = i; + continue; + } + if (danglingCommaPos) { + if (currentCharacter === '}' || currentCharacter === ']') { + result += pseudoJson.slice(offset, danglingCommaPos) + ' '; + offset = danglingCommaPos + 1; + danglingCommaPos = null; + } else if (!currentCharacter.match(/\s/)) { + danglingCommaPos = null; + } + } + } + return result + pseudoJson.substring(offset); +} + +// start strip-json-comments +/** + * + * @param {string} jsonString + * @param {number} quotePosition + * @returns {boolean} + */ +function isEscaped(jsonString, quotePosition) { + let index = quotePosition - 1; + let backslashCount = 0; + + while (jsonString[index] === '\\') { + index -= 1; + backslashCount += 1; + } + + return Boolean(backslashCount % 2); +} + +/** + * + * @param {string} string + * @param {number?} start + * @param {number?} end + */ +function strip(string, start, end) { + return string.slice(start, end).replace(/\S/g, ' '); +} + +const singleComment = Symbol('singleComment'); +const multiComment = Symbol('multiComment'); + +/** + * @param {string} jsonString + * @returns {string} + */ +function stripJsonComments(jsonString) { + let isInsideString = false; + /** @type {false | symbol} */ + let isInsideComment = false; + let offset = 0; + let result = ''; + + for (let index = 0; index < jsonString.length; index++) { + const currentCharacter = jsonString[index]; + const nextCharacter = jsonString[index + 1]; + + if (!isInsideComment && currentCharacter === '"') { + const escaped = isEscaped(jsonString, index); + if (!escaped) { + isInsideString = !isInsideString; + } + } + + if (isInsideString) { + continue; + } + + if (!isInsideComment && currentCharacter + nextCharacter === '//') { + result += jsonString.slice(offset, index); + offset = index; + isInsideComment = singleComment; + index++; + } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === '\r\n') { + index++; + isInsideComment = false; + result += strip(jsonString, offset, index); + offset = index; + } else if (isInsideComment === singleComment && currentCharacter === '\n') { + isInsideComment = false; + result += strip(jsonString, offset, index); + offset = index; + } else if (!isInsideComment && currentCharacter + nextCharacter === '/*') { + result += jsonString.slice(offset, index); + offset = index; + isInsideComment = multiComment; + index++; + } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === '*/') { + index++; + isInsideComment = false; + result += strip(jsonString, offset, index + 1); + offset = index + 1; + } + } + + return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset)); +} +// end strip-json-comments + +// start strip-bom +/** + * @param {string} string + * @returns {string} + */ +function stripBom(string) { + // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string + // conversion translates it to FEFF (UTF-16 BOM). + if (string.charCodeAt(0) === 0xfeff) { + return string.slice(1); + } + return string; +} +// end strip-bom + +const not_found_result = { + tsconfigFile: null, + tsconfig: {} +}; + +/** + * parse the closest tsconfig.json file + * + * @param {string} filename - path to a tsconfig .json or a source file or directory (absolute or relative to cwd) + * @param {import('./public.d.ts').TSConfckParseOptions} [options] - options + * @returns {Promise} + * @throws {TSConfckParseError} + */ +async function parse$f(filename, options) { + /** @type {import('./cache.js').TSConfckCache} */ + const cache = options?.cache; + if (cache?.hasParseResult(filename)) { + return cache.getParseResult(filename); + } + const { + resolve, + reject, + /** @type {Promise}*/ + promise + } = makePromise(); + cache?.setParseResult(filename, promise); + try { + let tsconfigFile = + (await resolveTSConfigJson(filename, cache)) || (await find(filename, options)); + if (!tsconfigFile) { + resolve(not_found_result); + return promise; + } + let result; + if (filename !== tsconfigFile && cache?.hasParseResult(tsconfigFile)) { + result = await cache.getParseResult(tsconfigFile); + } else { + result = await parseFile$1(tsconfigFile, cache, filename === tsconfigFile); + await Promise.all([parseExtends(result, cache), parseReferences(result, options)]); + } + resolve(resolveSolutionTSConfig(filename, result)); + return promise; + } catch (e) { + reject(e); + return promise; + } +} + +/** + * + * @param {string} tsconfigFile - path to tsconfig file + * @param {import('./cache.js').TSConfckCache} [cache] - cache + * @param {boolean} [skipCache] - skip cache + * @returns {Promise} + */ +async function parseFile$1(tsconfigFile, cache, skipCache) { + if (!skipCache && cache?.hasParseResult(tsconfigFile)) { + return cache.getParseResult(tsconfigFile); + } + const promise = promises$1 + .readFile(tsconfigFile, 'utf-8') + .then(toJson) + .then((json) => { + const parsed = JSON.parse(json); + applyDefaults(parsed, tsconfigFile); + return { + tsconfigFile, + tsconfig: normalizeTSConfig(parsed, path$o.dirname(tsconfigFile)) + }; + }) + .catch((e) => { + throw new TSConfckParseError( + `parsing ${tsconfigFile} failed: ${e}`, + 'PARSE_FILE', + tsconfigFile, + e + ); + }); + if (!skipCache) { + cache?.setParseResult(tsconfigFile, promise); + } + return promise; +} + +/** + * normalize to match the output of ts.parseJsonConfigFileContent + * + * @param {any} tsconfig - typescript tsconfig output + * @param {string} dir - directory + */ +function normalizeTSConfig(tsconfig, dir) { + // set baseUrl to absolute path + if (tsconfig.compilerOptions?.baseUrl && !path$o.isAbsolute(tsconfig.compilerOptions.baseUrl)) { + tsconfig.compilerOptions.baseUrl = resolve2posix(dir, tsconfig.compilerOptions.baseUrl); + } + return tsconfig; +} + +/** + * + * @param {import('./public.d.ts').TSConfckParseResult} result + * @param {import('./public.d.ts').TSConfckParseOptions} [options] + * @returns {Promise} + */ +async function parseReferences(result, options) { + if (!result.tsconfig.references) { + return; + } + const referencedFiles = resolveReferencedTSConfigFiles(result, options); + const referenced = await Promise.all( + referencedFiles.map((file) => parseFile$1(file, options?.cache)) + ); + await Promise.all(referenced.map((ref) => parseExtends(ref, options?.cache))); + referenced.forEach((ref) => { + ref.solution = result; + }); + result.referenced = referenced; +} + +/** + * @param {import('./public.d.ts').TSConfckParseResult} result + * @param {import('./cache.js').TSConfckCache}[cache] + * @returns {Promise} + */ +async function parseExtends(result, cache) { + if (!result.tsconfig.extends) { + return; + } + // use result as first element in extended + // but dereference tsconfig so that mergeExtended can modify the original without affecting extended[0] + /** @type {import('./public.d.ts').TSConfckParseResult[]} */ + const extended = [ + { tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) } + ]; + + // flatten extends graph into extended + let pos = 0; + /** @type {string[]} */ + const extendsPath = []; + let currentBranchDepth = 0; + while (pos < extended.length) { + const extending = extended[pos]; + extendsPath.push(extending.tsconfigFile); + if (extending.tsconfig.extends) { + // keep following this branch + currentBranchDepth += 1; + /** @type {string[]} */ + let resolvedExtends; + if (!Array.isArray(extending.tsconfig.extends)) { + resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)]; + } else { + // reverse because typescript 5.0 treats ['a','b','c'] as c extends b extends a + resolvedExtends = extending.tsconfig.extends + .reverse() + .map((ex) => resolveExtends(ex, extending.tsconfigFile)); + } + + const circularExtends = resolvedExtends.find((tsconfigFile) => + extendsPath.includes(tsconfigFile) + ); + if (circularExtends) { + const circle = extendsPath.concat([circularExtends]).join(' -> '); + throw new TSConfckParseError( + `Circular dependency in "extends": ${circle}`, + 'EXTENDS_CIRCULAR', + result.tsconfigFile + ); + } + // add new extends to the list directly after current + extended.splice( + pos + 1, + 0, + ...(await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache)))) + ); + } else { + // reached a leaf, backtrack to the last branching point and continue + extendsPath.splice(-currentBranchDepth); + currentBranchDepth = 0; + } + pos = pos + 1; + } + result.extended = extended; + // skip first as it is the original config + for (const ext of result.extended.slice(1)) { + extendTSConfig(result, ext); + } +} + +/** + * + * @param {string} extended + * @param {string} from + * @returns {string} + */ +function resolveExtends(extended, from) { + let error; + + try { + return createRequire$2(from).resolve(extended); + } catch (e) { + error = e; + } + + if (!path$o.isAbsolute(extended) && !extended.startsWith('./') && !extended.startsWith('../')) { + try { + const fallbackExtended = path$o.join(extended, 'tsconfig.json'); + return createRequire$2(from).resolve(fallbackExtended); + } catch (e) { + error = e; + } + } + + throw new TSConfckParseError( + `failed to resolve "extends":"${extended}" in ${from}`, + 'EXTENDS_RESOLVE', + from, + error + ); +} + +// references, extends and custom keys are not carried over +const EXTENDABLE_KEYS = [ + 'compilerOptions', + 'files', + 'include', + 'exclude', + 'watchOptions', + 'compileOnSave', + 'typeAcquisition', + 'buildOptions' +]; + +/** + * + * @param {import('./public.d.ts').TSConfckParseResult} extending + * @param {import('./public.d.ts').TSConfckParseResult} extended + * @returns void + */ +function extendTSConfig(extending, extended) { + const extendingConfig = extending.tsconfig; + const extendedConfig = extended.tsconfig; + const relativePath = native2posix( + path$o.relative(path$o.dirname(extending.tsconfigFile), path$o.dirname(extended.tsconfigFile)) + ); + for (const key of Object.keys(extendedConfig).filter((key) => EXTENDABLE_KEYS.includes(key))) { + if (key === 'compilerOptions') { + if (!extendingConfig.compilerOptions) { + extendingConfig.compilerOptions = {}; + } + for (const option of Object.keys(extendedConfig.compilerOptions)) { + if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) { + continue; // already set + } + extendingConfig.compilerOptions[option] = rebaseRelative( + option, + extendedConfig.compilerOptions[option], + relativePath + ); + } + } else if (extendingConfig[key] === undefined) { + if (key === 'watchOptions') { + extendingConfig.watchOptions = {}; + for (const option of Object.keys(extendedConfig.watchOptions)) { + extendingConfig.watchOptions[option] = rebaseRelative( + option, + extendedConfig.watchOptions[option], + relativePath + ); + } + } else { + extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath); + } + } + } +} + +const REBASE_KEYS = [ + // root + 'files', + 'include', + 'exclude', + // compilerOptions + 'baseUrl', + 'rootDir', + 'rootDirs', + 'typeRoots', + 'outDir', + 'outFile', + 'declarationDir', + // watchOptions + 'excludeDirectories', + 'excludeFiles' +]; + +/** @typedef {string | string[]} PathValue */ + +/** + * + * @param {string} key + * @param {PathValue} value + * @param {string} prependPath + * @returns {PathValue} + */ +function rebaseRelative(key, value, prependPath) { + if (!REBASE_KEYS.includes(key)) { + return value; + } + if (Array.isArray(value)) { + return value.map((x) => rebasePath(x, prependPath)); + } else { + return rebasePath(value, prependPath); + } +} + +/** + * + * @param {string} value + * @param {string} prependPath + * @returns {string} + */ +function rebasePath(value, prependPath) { + if (path$o.isAbsolute(value)) { + return value; + } else { + // relative paths use posix syntax in tsconfig + return path$o.posix.normalize(path$o.posix.join(prependPath, value)); + } +} + +class TSConfckParseError extends Error { + /** + * error code + * @type {string} + */ + code; + /** + * error cause + * @type { Error | undefined} + */ + cause; + + /** + * absolute path of tsconfig file where the error happened + * @type {string} + */ + tsconfigFile; + /** + * + * @param {string} message - error message + * @param {string} code - error code + * @param {string} tsconfigFile - path to tsconfig file + * @param {Error?} cause - cause of this error + */ + constructor(message, code, tsconfigFile, cause) { + super(message); + // Set the prototype explicitly. + Object.setPrototypeOf(this, TSConfckParseError.prototype); + this.name = TSConfckParseError.name; + this.code = code; + this.cause = cause; + this.tsconfigFile = tsconfigFile; + } +} + +/** + * + * @param {any} tsconfig + * @param {string} tsconfigFile + */ +function applyDefaults(tsconfig, tsconfigFile) { + if (isJSConfig(tsconfigFile)) { + tsconfig.compilerOptions = { + ...DEFAULT_JSCONFIG_COMPILER_OPTIONS, + ...tsconfig.compilerOptions + }; + } +} + +const DEFAULT_JSCONFIG_COMPILER_OPTIONS = { + allowJs: true, + maxNodeModuleJsDepth: 2, + allowSyntheticDefaultImports: true, + skipLibCheck: true, + noEmit: true +}; + +/** + * @param {string} configFileName + */ +function isJSConfig(configFileName) { + return path$o.basename(configFileName) === 'jsconfig.json'; +} + +/** @template T */ +class TSConfckCache { + /** + * clear cache, use this if you have a long running process and tsconfig files have been added,changed or deleted + */ + clear() { + this.#configPaths.clear(); + this.#parsed.clear(); + } + + /** + * has cached closest config for files in dir + * @param {string} dir + * @param {string} [configName=tsconfig.json] + * @returns {boolean} + */ + hasConfigPath(dir, configName = 'tsconfig.json') { + return this.#configPaths.has(`${dir}/${configName}`); + } + + /** + * get cached closest tsconfig for files in dir + * @param {string} dir + * @param {string} [configName=tsconfig.json] + * @returns {Promise|string|null} + * @throws {unknown} if cached value is an error + */ + getConfigPath(dir, configName = 'tsconfig.json') { + const key = `${dir}/${configName}`; + const value = this.#configPaths.get(key); + if (value == null || value.length || value.then) { + return value; + } else { + throw value; + } + } + + /** + * has parsed tsconfig for file + * @param {string} file + * @returns {boolean} + */ + hasParseResult(file) { + return this.#parsed.has(file); + } + + /** + * get parsed tsconfig for file + * @param {string} file + * @returns {Promise|T} + * @throws {unknown} if cached value is an error + */ + getParseResult(file) { + const value = this.#parsed.get(file); + if (value.then || value.tsconfig) { + return value; + } else { + throw value; // cached error, rethrow + } + } + + /** + * @internal + * @private + * @param file + * @param {Promise} result + */ + setParseResult(file, result) { + this.#parsed.set(file, result); + result + .then((parsed) => { + if (this.#parsed.get(file) === result) { + this.#parsed.set(file, parsed); + } + }) + .catch((e) => { + if (this.#parsed.get(file) === result) { + this.#parsed.set(file, e); + } + }); + } + + /** + * @internal + * @private + * @param {string} dir + * @param {Promise} configPath + * @param {string} [configName=tsconfig.json] + */ + setConfigPath(dir, configPath, configName = 'tsconfig.json') { + const key = `${dir}/${configName}`; + this.#configPaths.set(key, configPath); + configPath + .then((path) => { + if (this.#configPaths.get(key) === configPath) { + this.#configPaths.set(key, path); + } + }) + .catch((e) => { + if (this.#configPaths.get(key) === configPath) { + this.#configPaths.set(key, e); + } + }); + } + + /** + * map directories to their closest tsconfig.json + * @internal + * @private + * @type{Map|string|null)>} + */ + #configPaths = new Map(); + + /** + * map files to their parsed tsconfig result + * @internal + * @private + * @type {Map|T)> } + */ + #parsed = new Map(); +} + +const debug$h = createDebugger('vite:esbuild'); +// IIFE content looks like `var MyLib = function() {`. +// Spaces are removed and parameters are mangled when minified +const IIFE_BEGIN_RE = /(const|var)\s+\S+\s*=\s*function\([^()]*\)\s*\{\s*"use strict";/; +const validExtensionRE = /\.\w+$/; +const jsxExtensionsRE = /\.(?:j|t)sx\b/; +let server; +async function transformWithEsbuild(code, filename, options, inMap) { + let loader = options?.loader; + if (!loader) { + // if the id ends with a valid ext, use it (e.g. vue blocks) + // otherwise, cleanup the query before checking the ext + const ext = path$o + .extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename)) + .slice(1); + if (ext === 'cjs' || ext === 'mjs') { + loader = 'js'; + } + else if (ext === 'cts' || ext === 'mts') { + loader = 'ts'; + } + else { + loader = ext; + } + } + let tsconfigRaw = options?.tsconfigRaw; + // if options provide tsconfigRaw in string, it takes highest precedence + if (typeof tsconfigRaw !== 'string') { + // these fields would affect the compilation result + // https://esbuild.github.io/content-types/#tsconfig-json + const meaningfulFields = [ + 'alwaysStrict', + 'experimentalDecorators', + 'importsNotUsedAsValues', + 'jsx', + 'jsxFactory', + 'jsxFragmentFactory', + 'jsxImportSource', + 'preserveValueImports', + 'target', + 'useDefineForClassFields', + 'verbatimModuleSyntax', + ]; + const compilerOptionsForFile = {}; + if (loader === 'ts' || loader === 'tsx') { + const loadedTsconfig = await loadTsconfigJsonForFile(filename); + const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {}; + for (const field of meaningfulFields) { + if (field in loadedCompilerOptions) { + // @ts-expect-error TypeScript can't tell they are of the same type + compilerOptionsForFile[field] = loadedCompilerOptions[field]; + } + } + } + const compilerOptions = { + ...compilerOptionsForFile, + ...tsconfigRaw?.compilerOptions, + }; + // esbuild uses `useDefineForClassFields: true` when `tsconfig.compilerOptions.target` isn't declared + // but we want `useDefineForClassFields: false` when `tsconfig.compilerOptions.target` isn't declared + // to align with the TypeScript's behavior + if (compilerOptions.useDefineForClassFields === undefined && + compilerOptions.target === undefined) { + compilerOptions.useDefineForClassFields = false; + } + // esbuild uses tsconfig fields when both the normal options and tsconfig was set + // but we want to prioritize the normal options + if (options) { + options.jsx && (compilerOptions.jsx = undefined); + options.jsxFactory && (compilerOptions.jsxFactory = undefined); + options.jsxFragment && (compilerOptions.jsxFragmentFactory = undefined); + options.jsxImportSource && (compilerOptions.jsxImportSource = undefined); + } + tsconfigRaw = { + ...tsconfigRaw, + compilerOptions, + }; + } + const resolvedOptions = { + sourcemap: true, + // ensure source file name contains full query + sourcefile: filename, + ...options, + loader, + tsconfigRaw, + }; + // Some projects in the ecosystem are calling this function with an ESBuildOptions + // object and esbuild throws an error for extra fields + // @ts-expect-error include exists in ESBuildOptions + delete resolvedOptions.include; + // @ts-expect-error exclude exists in ESBuildOptions + delete resolvedOptions.exclude; + // @ts-expect-error jsxInject exists in ESBuildOptions + delete resolvedOptions.jsxInject; + try { + const result = await transform$1(code, resolvedOptions); + let map; + if (inMap && resolvedOptions.sourcemap) { + const nextMap = JSON.parse(result.map); + nextMap.sourcesContent = []; + map = combineSourcemaps(filename, [ + nextMap, + inMap, + ]); + } + else { + map = + resolvedOptions.sourcemap && resolvedOptions.sourcemap !== 'inline' + ? JSON.parse(result.map) + : { mappings: '' }; + } + return { + ...result, + map, + }; + } + catch (e) { + debug$h?.(`esbuild error with options used: `, resolvedOptions); + // patch error information + if (e.errors) { + e.frame = ''; + e.errors.forEach((m) => { + if (m.text === 'Experimental decorators are not currently enabled' || + m.text === + 'Parameter decorators only work when experimental decorators are enabled') { + m.text += + '. Vite 5 now uses esbuild 0.18 and you need to enable them by adding "experimentalDecorators": true in your "tsconfig.json" file.'; + } + e.frame += `\n` + prettifyMessage(m, code); + }); + e.loc = e.errors[0].location; + } + throw e; + } +} +function esbuildPlugin(config) { + const options = config.esbuild; + const { jsxInject, include, exclude, ...esbuildTransformOptions } = options; + const filter = createFilter(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/); + // Remove optimization options for dev as we only need to transpile them, + // and for build as the final optimization is in `buildEsbuildPlugin` + const transformOptions = { + target: 'esnext', + charset: 'utf8', + ...esbuildTransformOptions, + minify: false, + minifyIdentifiers: false, + minifySyntax: false, + minifyWhitespace: false, + treeShaking: false, + // keepNames is not needed when minify is disabled. + // Also transforming multiple times with keepNames enabled breaks + // tree-shaking. (#9164) + keepNames: false, + }; + return { + name: 'vite:esbuild', + configureServer(_server) { + server = _server; + server.watcher + .on('add', reloadOnTsconfigChange) + .on('change', reloadOnTsconfigChange) + .on('unlink', reloadOnTsconfigChange); + }, + buildEnd() { + // recycle serve to avoid preventing Node self-exit (#6815) + server = null; + }, + async transform(code, id) { + if (filter(id) || filter(cleanUrl(id))) { + const result = await transformWithEsbuild(code, id, transformOptions); + if (result.warnings.length) { + result.warnings.forEach((m) => { + this.warn(prettifyMessage(m, code)); + }); + } + if (jsxInject && jsxExtensionsRE.test(id)) { + result.code = jsxInject + ';' + result.code; + } + return { + code: result.code, + map: result.map, + }; + } + }, + }; +} +const rollupToEsbuildFormatMap = { + es: 'esm', + cjs: 'cjs', + // passing `var Lib = (() => {})()` to esbuild with format = "iife" + // will turn it to `(() => { var Lib = (() => {})() })()`, + // so we remove the format config to tell esbuild not doing this + // + // although esbuild doesn't change format, there is still possibility + // that `{ treeShaking: true }` removes a top-level no-side-effect variable + // like: `var Lib = 1`, which becomes `` after esbuild transforming, + // but thankfully rollup does not do this optimization now + iife: undefined, +}; +const buildEsbuildPlugin = (config) => { + return { + name: 'vite:esbuild-transpile', + async renderChunk(code, chunk, opts) { + // @ts-expect-error injected by @vitejs/plugin-legacy + if (opts.__vite_skip_esbuild__) { + return null; + } + const options = resolveEsbuildTranspileOptions(config, opts.format); + if (!options) { + return null; + } + const res = await transformWithEsbuild(code, chunk.fileName, options); + if (config.build.lib) { + // #7188, esbuild adds helpers out of the UMD and IIFE wrappers, and the + // names are minified potentially causing collision with other globals. + // We inject the helpers inside the wrappers. + // e.g. turn: + // (function(){ /*actual content/* })() + // into: + // (function(){ /*actual content/* })() + // Not using regex because it's too hard to rule out performance issues like #8738 #8099 #10900 #14065 + // Instead, using plain string index manipulation (indexOf, slice) which is simple and performant + // We don't need to create a MagicString here because both the helpers and + // the headers don't modify the sourcemap + const esbuildCode = res.code; + const contentIndex = opts.format === 'iife' + ? Math.max(esbuildCode.search(IIFE_BEGIN_RE), 0) + : opts.format === 'umd' + ? esbuildCode.indexOf(`(function(`) // same for minified or not + : 0; + if (contentIndex > 0) { + const esbuildHelpers = esbuildCode.slice(0, contentIndex); + res.code = esbuildCode + .slice(contentIndex) + .replace(`"use strict";`, `"use strict";` + esbuildHelpers); + } + } + return res; + }, + }; +}; +function resolveEsbuildTranspileOptions(config, format) { + const target = config.build.target; + const minify = config.build.minify === 'esbuild'; + if ((!target || target === 'esnext') && !minify) { + return null; + } + // Do not minify whitespace for ES lib output since that would remove + // pure annotations and break tree-shaking + // https://github.com/vuejs/core/issues/2860#issuecomment-926882793 + const isEsLibBuild = config.build.lib && format === 'es'; + const esbuildOptions = config.esbuild || {}; + const options = { + charset: 'utf8', + ...esbuildOptions, + loader: 'js', + target: target || undefined, + format: rollupToEsbuildFormatMap[format], + // the final build should always support dynamic import and import.meta. + // if they need to be polyfilled, plugin-legacy should be used. + // plugin-legacy detects these two features when checking for modern code. + supported: { + 'dynamic-import': true, + 'import-meta': true, + ...esbuildOptions.supported, + }, + }; + // If no minify, disable all minify options + if (!minify) { + return { + ...options, + minify: false, + minifyIdentifiers: false, + minifySyntax: false, + minifyWhitespace: false, + treeShaking: false, + }; + } + // If user enable fine-grain minify options, minify with their options instead + if (options.minifyIdentifiers != null || + options.minifySyntax != null || + options.minifyWhitespace != null) { + if (isEsLibBuild) { + // Disable minify whitespace as it breaks tree-shaking + return { + ...options, + minify: false, + minifyIdentifiers: options.minifyIdentifiers ?? true, + minifySyntax: options.minifySyntax ?? true, + minifyWhitespace: false, + treeShaking: true, + }; + } + else { + return { + ...options, + minify: false, + minifyIdentifiers: options.minifyIdentifiers ?? true, + minifySyntax: options.minifySyntax ?? true, + minifyWhitespace: options.minifyWhitespace ?? true, + treeShaking: true, + }; + } + } + // Else apply default minify options + if (isEsLibBuild) { + // Minify all except whitespace as it breaks tree-shaking + return { + ...options, + minify: false, + minifyIdentifiers: true, + minifySyntax: true, + minifyWhitespace: false, + treeShaking: true, + }; + } + else { + return { + ...options, + minify: true, + treeShaking: true, + }; + } +} +function prettifyMessage(m, code) { + let res = colors$1.yellow(m.text); + if (m.location) { + res += `\n` + generateCodeFrame(code, m.location); + } + return res + `\n`; +} +let tsconfckCache; +async function loadTsconfigJsonForFile(filename) { + try { + if (tsconfckCache) { + // shortcut, the cache stores resolved TSConfckParseResult + // so getting it from the cache directly we bypass async fn call wrapping it in a promise again + if (tsconfckCache.hasParseResult(filename)) { + const result = await tsconfckCache.getParseResult(filename); + return result.tsconfig; + } + } + else { + tsconfckCache = new TSConfckCache(); + } + const result = await parse$f(filename, { + cache: tsconfckCache, + ignoreNodeModules: true, + }); + // tsconfig could be out of root, make sure it is watched on dev + if (server && result.tsconfigFile) { + ensureWatchedFile(server.watcher, result.tsconfigFile, server.config.root); + } + return result.tsconfig; + } + catch (e) { + if (e instanceof TSConfckParseError) { + // tsconfig could be out of root, make sure it is watched on dev + if (server && e.tsconfigFile) { + ensureWatchedFile(server.watcher, e.tsconfigFile, server.config.root); + } + } + throw e; + } +} +async function reloadOnTsconfigChange(changedFile) { + // server could be closed externally after a file change is detected + if (!server) + return; + // any tsconfig.json that's added in the workspace could be closer to a code file than a previously cached one + // any json file in the tsconfig cache could have been used to compile ts + if (path$o.basename(changedFile) === 'tsconfig.json' || + (changedFile.endsWith('.json') && + tsconfckCache?.hasParseResult(changedFile))) { + server.config.logger.info(`changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`, { clear: server.config.clearScreen, timestamp: true }); + // clear module graph to remove code compiled with outdated config + server.moduleGraph.invalidateAll(); + // reset tsconfck so that recompile works with up2date configs + tsconfckCache?.clear(); + // server may not be available if vite config is updated at the same time + if (server) { + // force full reload + server.ws.send({ + type: 'full-reload', + path: '*', + }); + } + } +} + +var dist$1 = {}; + +var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(dist$1, "__esModule", { value: true }); +var Worker_1 = dist$1.Worker = void 0; +const os_1 = __importDefault(require$$2); +const worker_threads_1 = require$$1; +class Worker { + constructor(fn, options = {}) { + this.code = genWorkerCode(fn); + this.max = options.max || Math.max(1, os_1.default.cpus().length - 1); + this.pool = []; + this.idlePool = []; + this.queue = []; + } + async run(...args) { + const worker = await this._getAvailableWorker(); + return new Promise((resolve, reject) => { + worker.currentResolve = resolve; + worker.currentReject = reject; + worker.postMessage(args); + }); + } + stop() { + this.pool.forEach((w) => w.unref()); + this.queue.forEach(([_, reject]) => reject(new Error('Main worker pool stopped before a worker was available.'))); + this.pool = []; + this.idlePool = []; + this.queue = []; + } + async _getAvailableWorker() { + // has idle one? + if (this.idlePool.length) { + return this.idlePool.shift(); + } + // can spawn more? + if (this.pool.length < this.max) { + const worker = new worker_threads_1.Worker(this.code, { eval: true }); + worker.on('message', (res) => { + worker.currentResolve && worker.currentResolve(res); + worker.currentResolve = null; + this._assignDoneWorker(worker); + }); + worker.on('error', (err) => { + worker.currentReject && worker.currentReject(err); + worker.currentReject = null; + }); + worker.on('exit', (code) => { + const i = this.pool.indexOf(worker); + if (i > -1) + this.pool.splice(i, 1); + if (code !== 0 && worker.currentReject) { + worker.currentReject(new Error(`Wroker stopped with non-0 exit code ${code}`)); + worker.currentReject = null; + } + }); + this.pool.push(worker); + return worker; + } + // no one is available, we have to wait + let resolve; + let reject; + const onWorkerAvailablePromise = new Promise((r, rj) => { + resolve = r; + reject = rj; + }); + this.queue.push([resolve, reject]); + return onWorkerAvailablePromise; + } + _assignDoneWorker(worker) { + // someone's waiting already? + if (this.queue.length) { + const [resolve] = this.queue.shift(); + resolve(worker); + return; + } + // take a rest. + this.idlePool.push(worker); + } +} +Worker_1 = dist$1.Worker = Worker; +function genWorkerCode(fn) { + return ` +const doWork = ${fn.toString()} + +const { parentPort } = require('worker_threads') + +parentPort.on('message', async (args) => { + const res = await doWork(...args) + parentPort.postMessage(res) +}) + `; +} + +let terserPath; +const loadTerserPath = (root) => { + if (terserPath) + return terserPath; + try { + terserPath = requireResolveFromRootWithFallback(root, 'terser'); + } + catch (e) { + if (e.code === 'MODULE_NOT_FOUND') { + throw new Error('terser not found. Since Vite v3, terser has become an optional dependency. You need to install it.'); + } + else { + const message = new Error(`terser failed to load:\n${e.message}`); + message.stack = e.stack + '\n' + message.stack; + throw message; + } + } + return terserPath; +}; +function terserPlugin(config) { + const { maxWorkers, ...terserOptions } = config.build.terserOptions; + const makeWorker = () => new Worker_1(async (terserPath, code, options) => { + // test fails when using `import`. maybe related: https://github.com/nodejs/node/issues/43205 + // eslint-disable-next-line no-restricted-globals -- this function runs inside cjs + const terser = require(terserPath); + return terser.minify(code, options); + }, { + max: maxWorkers, + }); + let worker; + return { + name: 'vite:terser', + async renderChunk(code, _chunk, outputOptions) { + // This plugin is included for any non-false value of config.build.minify, + // so that normal chunks can use the preferred minifier, and legacy chunks + // can use terser. + if (config.build.minify !== 'terser' && + // @ts-expect-error injected by @vitejs/plugin-legacy + !outputOptions.__vite_force_terser__) { + return null; + } + // Do not minify ES lib output since that would remove pure annotations + // and break tree-shaking. + if (config.build.lib && outputOptions.format === 'es') { + return null; + } + // Lazy load worker. + worker ||= makeWorker(); + const terserPath = loadTerserPath(config.root); + const res = await worker.run(terserPath, code, { + safari10: true, + ...terserOptions, + sourceMap: !!outputOptions.sourcemap, + module: outputOptions.format.startsWith('es'), + toplevel: outputOptions.format === 'cjs', + }); + return { + code: res.code, + map: res.map, + }; + }, + closeBundle() { + worker?.stop(); + }, + }; +} + +var toString$2 = {}.toString; + +var isarray = Array.isArray || function (arr) { + return toString$2.call(arr) == '[object Array]'; +}; + +var toStr$2 = Object.prototype.toString; + +var isArguments = function isArguments(value) { + var str = toStr$2.call(value); + var isArgs = str === '[object Arguments]'; + if (!isArgs) { + isArgs = str !== '[object Array]' && + value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + toStr$2.call(value.callee) === '[object Function]'; + } + return isArgs; +}; + +var implementation$4; +var hasRequiredImplementation; + +function requireImplementation () { + if (hasRequiredImplementation) return implementation$4; + hasRequiredImplementation = 1; + + var keysShim; + if (!Object.keys) { + // modified from https://github.com/es-shims/es5-shim + var has = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var isArgs = isArguments; // eslint-disable-line global-require + var isEnumerable = Object.prototype.propertyIsEnumerable; + var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); + var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); + var dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ]; + var equalsConstructorPrototype = function (o) { + var ctor = o.constructor; + return ctor && ctor.prototype === o; + }; + var excludedKeys = { + $applicationCache: true, + $console: true, + $external: true, + $frame: true, + $frameElement: true, + $frames: true, + $innerHeight: true, + $innerWidth: true, + $onmozfullscreenchange: true, + $onmozfullscreenerror: true, + $outerHeight: true, + $outerWidth: true, + $pageXOffset: true, + $pageYOffset: true, + $parent: true, + $scrollLeft: true, + $scrollTop: true, + $scrollX: true, + $scrollY: true, + $self: true, + $webkitIndexedDB: true, + $webkitStorageInfo: true, + $window: true + }; + var hasAutomationEqualityBug = (function () { + /* global window */ + if (typeof window === 'undefined') { return false; } + for (var k in window) { + try { + if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { + try { + equalsConstructorPrototype(window[k]); + } catch (e) { + return true; + } + } + } catch (e) { + return true; + } + } + return false; + }()); + var equalsConstructorPrototypeIfNotBuggy = function (o) { + /* global window */ + if (typeof window === 'undefined' || !hasAutomationEqualityBug) { + return equalsConstructorPrototype(o); + } + try { + return equalsConstructorPrototype(o); + } catch (e) { + return false; + } + }; + + keysShim = function keys(object) { + var isObject = object !== null && typeof object === 'object'; + var isFunction = toStr.call(object) === '[object Function]'; + var isArguments = isArgs(object); + var isString = isObject && toStr.call(object) === '[object String]'; + var theKeys = []; + + if (!isObject && !isFunction && !isArguments) { + throw new TypeError('Object.keys called on a non-object'); + } + + var skipProto = hasProtoEnumBug && isFunction; + if (isString && object.length > 0 && !has.call(object, 0)) { + for (var i = 0; i < object.length; ++i) { + theKeys.push(String(i)); + } + } + + if (isArguments && object.length > 0) { + for (var j = 0; j < object.length; ++j) { + theKeys.push(String(j)); + } + } else { + for (var name in object) { + if (!(skipProto && name === 'prototype') && has.call(object, name)) { + theKeys.push(String(name)); + } + } + } + + if (hasDontEnumBug) { + var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); + + for (var k = 0; k < dontEnums.length; ++k) { + if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { + theKeys.push(dontEnums[k]); + } + } + } + return theKeys; + }; + } + implementation$4 = keysShim; + return implementation$4; +} + +var slice$2 = Array.prototype.slice; +var isArgs = isArguments; + +var origKeys = Object.keys; +var keysShim = origKeys ? function keys(o) { return origKeys(o); } : requireImplementation(); + +var originalKeys = Object.keys; + +keysShim.shim = function shimObjectKeys() { + if (Object.keys) { + var keysWorksWithArguments = (function () { + // Safari 5.0 bug + var args = Object.keys(arguments); + return args && args.length === arguments.length; + }(1, 2)); + if (!keysWorksWithArguments) { + Object.keys = function keys(object) { // eslint-disable-line func-name-matching + if (isArgs(object)) { + return originalKeys(slice$2.call(object)); + } + return originalKeys(object); + }; + } + } else { + Object.keys = keysShim; + } + return Object.keys || keysShim; +}; + +var objectKeys$1 = keysShim; + +var callBind$1 = {exports: {}}; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE$1 = 'Function.prototype.bind called on incompatible '; +var toStr$1 = Object.prototype.toString; +var max = Math.max; +var funcType$1 = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +var implementation$3 = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr$1.apply(target) !== funcType$1) { + throw new TypeError(ERROR_MESSAGE$1 + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + +var implementation$2 = implementation$3; + +var functionBind$1 = Function.prototype.bind || implementation$2; + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +var shams = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = shams; + +var hasSymbols$1 = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + +var test = { + foo: {} +}; + +var $Object = Object; + +var hasProto$1 = function hasProto() { + return { __proto__: test }.foo === test.foo && !({ __proto__: null } instanceof $Object); +}; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice$1 = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; + +var implementation$1 = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slice$1.call(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice$1.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply( + that, + args.concat(slice$1.call(arguments)) + ); + } + }; + + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } + + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + +var implementation = implementation$1; + +var functionBind = Function.prototype.bind || implementation; + +var bind$1 = functionBind; + +var src$2 = bind$1.call(Function.call, Object.prototype.hasOwnProperty); + +var undefined$1; + +var $SyntaxError$1 = SyntaxError; +var $Function = Function; +var $TypeError$2 = TypeError; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD$1 = Object.getOwnPropertyDescriptor; + +var throwTypeError = function () { + throw new $TypeError$2(); +}; +var ThrowTypeError = $gOPD$1 + ? (function () { + try { + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD$1(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = hasSymbols$1(); +var hasProto = hasProto$1(); + +var getProto = Object.getPrototypeOf || ( + hasProto + ? function (x) { return x.__proto__; } // eslint-disable-line no-proto + : null +); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined$1 : getProto(Uint8Array); + +var INTRINSICS = { + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined$1 : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined$1, + '%AsyncFromSyncIteratorPrototype%': undefined$1, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined$1 : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined$1 : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined$1 : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined$1 : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined$1, + '%JSON%': typeof JSON === 'object' ? JSON : undefined$1, + '%Map%': typeof Map === 'undefined' ? undefined$1 : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined$1 : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy, + '%RangeError%': RangeError, + '%ReferenceError%': ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined$1 : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined$1 : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined$1, + '%Symbol%': hasSymbols ? Symbol : undefined$1, + '%SyntaxError%': $SyntaxError$1, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError$2, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array, + '%URIError%': URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined$1 : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet +}; + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = functionBind$1; +var hasOwn$1 = src$2; +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError$1('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError$1('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn$1(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn$1(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError$2('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError$1('intrinsic ' + name + ' does not exist!'); +}; + +var getIntrinsic = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError$2('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError$2('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError$1('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError$1('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn$1(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError$2('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined$1; + } + if ($gOPD$1 && (i + 1) >= parts.length) { + var desc = $gOPD$1(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn$1(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + +var GetIntrinsic$3 = getIntrinsic; + +var $defineProperty$1 = GetIntrinsic$3('%Object.defineProperty%', true); + +var hasPropertyDescriptors$1 = function hasPropertyDescriptors() { + if ($defineProperty$1) { + try { + $defineProperty$1({}, 'a', { value: 1 }); + return true; + } catch (e) { + // IE 8 has a broken defineProperty + return false; + } + } + return false; +}; + +hasPropertyDescriptors$1.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!hasPropertyDescriptors$1()) { + return null; + } + try { + return $defineProperty$1([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; + +var hasPropertyDescriptors_1 = hasPropertyDescriptors$1; + +var GetIntrinsic$2 = getIntrinsic; + +var $gOPD = GetIntrinsic$2('%Object.getOwnPropertyDescriptor%', true); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +var gopd$1 = $gOPD; + +var hasPropertyDescriptors = hasPropertyDescriptors_1(); + +var GetIntrinsic$1 = getIntrinsic; + +var $defineProperty = hasPropertyDescriptors && GetIntrinsic$1('%Object.defineProperty%', true); +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +var $SyntaxError = GetIntrinsic$1('%SyntaxError%'); +var $TypeError$1 = GetIntrinsic$1('%TypeError%'); + +var gopd = gopd$1; + +/** @type {(obj: Record, property: PropertyKey, value: unknown, nonEnumerable?: boolean | null, nonWritable?: boolean | null, nonConfigurable?: boolean | null, loose?: boolean) => void} */ +var defineDataProperty = function defineDataProperty( + obj, + property, + value +) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new $TypeError$1('`obj` must be an object or a function`'); + } + if (typeof property !== 'string' && typeof property !== 'symbol') { + throw new $TypeError$1('`property` must be a string or a symbol`'); + } + if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { + throw new $TypeError$1('`nonEnumerable`, if provided, must be a boolean or null'); + } + if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { + throw new $TypeError$1('`nonWritable`, if provided, must be a boolean or null'); + } + if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { + throw new $TypeError$1('`nonConfigurable`, if provided, must be a boolean or null'); + } + if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { + throw new $TypeError$1('`loose`, if provided, must be a boolean'); + } + + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + + /* @type {false | TypedPropertyDescriptor} */ + var desc = !!gopd && gopd(obj, property); + + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value: value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { + // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable + obj[property] = value; // eslint-disable-line no-param-reassign + } else { + throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); + } +}; + +var GetIntrinsic = getIntrinsic; +var define = defineDataProperty; +var hasDescriptors = hasPropertyDescriptors_1(); +var gOPD = gopd$1; + +var $TypeError = GetIntrinsic('%TypeError%'); +var $floor = GetIntrinsic('%Math.floor%'); + +var setFunctionLength = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } + + var loose = arguments.length > 2 && !!arguments[2]; + + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(fn, 'length', length, true, true); + } else { + define(fn, 'length', length); + } + } + return fn; +}; + +(function (module) { + + var bind = functionBind$1; + var GetIntrinsic = getIntrinsic; + var setFunctionLength$1 = setFunctionLength; + + var $TypeError = GetIntrinsic('%TypeError%'); + var $apply = GetIntrinsic('%Function.prototype.apply%'); + var $call = GetIntrinsic('%Function.prototype.call%'); + var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + + var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); + var $max = GetIntrinsic('%Math.max%'); + + if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = null; + } + } + + module.exports = function callBind(originalFunction) { + if (typeof originalFunction !== 'function') { + throw new $TypeError('a function is required'); + } + var func = $reflectApply(bind, $call, arguments); + return setFunctionLength$1( + func, + 1 + $max(0, originalFunction.length - (arguments.length - 1)), + true + ); + }; + + var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); + }; + + if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); + } else { + module.exports.apply = applyBind; + } +} (callBind$1)); + +var callBindExports = callBind$1.exports; + +var jsonStringify = (typeof JSON !== 'undefined' ? JSON : JSON).stringify; + +var isArray$1 = isarray; +var objectKeys = objectKeys$1; +var callBind = callBindExports; + +var strRepeat = function repeat(n, char) { + var str = ''; + for (var i = 0; i < n; i += 1) { + str += char; + } + return str; +}; + +var defaultReplacer = function (parent, key, value) { return value; }; + +var jsonStableStringify = function stableStringify(obj) { + var opts = arguments.length > 1 ? arguments[1] : void undefined; + var space = (opts && opts.space) || ''; + if (typeof space === 'number') { space = strRepeat(space, ' '); } + var cycles = !!opts && typeof opts.cycles === 'boolean' && opts.cycles; + var replacer = opts && opts.replacer ? callBind(opts.replacer) : defaultReplacer; + + var cmpOpt = typeof opts === 'function' ? opts : opts && opts.cmp; + var cmp = cmpOpt && function (node) { + var get = cmpOpt.length > 2 && function get(k) { return node[k]; }; + return function (a, b) { + return cmpOpt( + { key: a, value: node[a] }, + { key: b, value: node[b] }, + get ? { __proto__: null, get: get } : void undefined + ); + }; + }; + + var seen = []; + return (function stringify(parent, key, node, level) { + var indent = space ? '\n' + strRepeat(level, space) : ''; + var colonSeparator = space ? ': ' : ':'; + + if (node && node.toJSON && typeof node.toJSON === 'function') { + node = node.toJSON(); + } + + node = replacer(parent, key, node); + + if (node === undefined) { + return; + } + if (typeof node !== 'object' || node === null) { + return jsonStringify(node); + } + if (isArray$1(node)) { + var out = ''; + for (var i = 0; i < node.length; i++) { + var item = stringify(node, i, node[i], level + 1) || jsonStringify(null); + out += indent + space + item; + if ((i + 1) < node.length) { + out += ','; + } + } + return '[' + out + indent + ']'; + } + + if (seen.indexOf(node) !== -1) { + if (cycles) { return jsonStringify('__cycle__'); } + throw new TypeError('Converting circular structure to JSON'); + } else { seen.push(node); } + + var keys = objectKeys(node).sort(cmp && cmp(node)); + var out = ''; + var needsComma = false; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = stringify(node, key, node[key], level + 1); + + if (!value) { continue; } + + var keyValue = jsonStringify(key) + + colonSeparator + + value; + + out += (needsComma ? ',' : '') + indent + space + keyValue; + needsComma = true; + } + seen.splice(seen.indexOf(node), 1); + return '{' + out + indent + '}'; + + }({ '': obj }, '', obj, 0)); +}; + +var jsonStableStringify$1 = /*@__PURE__*/getDefaultExportFromCjs(jsonStableStringify); + +const mimes$1 = { + "ez": "application/andrew-inset", + "aw": "application/applixware", + "atom": "application/atom+xml", + "atomcat": "application/atomcat+xml", + "atomdeleted": "application/atomdeleted+xml", + "atomsvc": "application/atomsvc+xml", + "dwd": "application/atsc-dwd+xml", + "held": "application/atsc-held+xml", + "rsat": "application/atsc-rsat+xml", + "bdoc": "application/bdoc", + "xcs": "application/calendar+xml", + "ccxml": "application/ccxml+xml", + "cdfx": "application/cdfx+xml", + "cdmia": "application/cdmi-capability", + "cdmic": "application/cdmi-container", + "cdmid": "application/cdmi-domain", + "cdmio": "application/cdmi-object", + "cdmiq": "application/cdmi-queue", + "cu": "application/cu-seeme", + "mpd": "application/dash+xml", + "davmount": "application/davmount+xml", + "dbk": "application/docbook+xml", + "dssc": "application/dssc+der", + "xdssc": "application/dssc+xml", + "es": "application/ecmascript", + "ecma": "application/ecmascript", + "emma": "application/emma+xml", + "emotionml": "application/emotionml+xml", + "epub": "application/epub+zip", + "exi": "application/exi", + "fdt": "application/fdt+xml", + "pfr": "application/font-tdpfr", + "geojson": "application/geo+json", + "gml": "application/gml+xml", + "gpx": "application/gpx+xml", + "gxf": "application/gxf", + "gz": "application/gzip", + "hjson": "application/hjson", + "stk": "application/hyperstudio", + "ink": "application/inkml+xml", + "inkml": "application/inkml+xml", + "ipfix": "application/ipfix", + "its": "application/its+xml", + "jar": "application/java-archive", + "war": "application/java-archive", + "ear": "application/java-archive", + "ser": "application/java-serialized-object", + "class": "application/java-vm", + "js": "application/javascript", + "mjs": "application/javascript", + "json": "application/json", + "map": "application/json", + "json5": "application/json5", + "jsonml": "application/jsonml+json", + "jsonld": "application/ld+json", + "lgr": "application/lgr+xml", + "lostxml": "application/lost+xml", + "hqx": "application/mac-binhex40", + "cpt": "application/mac-compactpro", + "mads": "application/mads+xml", + "webmanifest": "application/manifest+json", + "mrc": "application/marc", + "mrcx": "application/marcxml+xml", + "ma": "application/mathematica", + "nb": "application/mathematica", + "mb": "application/mathematica", + "mathml": "application/mathml+xml", + "mbox": "application/mbox", + "mscml": "application/mediaservercontrol+xml", + "metalink": "application/metalink+xml", + "meta4": "application/metalink4+xml", + "mets": "application/mets+xml", + "maei": "application/mmt-aei+xml", + "musd": "application/mmt-usd+xml", + "mods": "application/mods+xml", + "m21": "application/mp21", + "mp21": "application/mp21", + "mp4s": "application/mp4", + "m4p": "application/mp4", + "doc": "application/msword", + "dot": "application/msword", + "mxf": "application/mxf", + "nq": "application/n-quads", + "nt": "application/n-triples", + "cjs": "application/node", + "bin": "application/octet-stream", + "dms": "application/octet-stream", + "lrf": "application/octet-stream", + "mar": "application/octet-stream", + "so": "application/octet-stream", + "dist": "application/octet-stream", + "distz": "application/octet-stream", + "pkg": "application/octet-stream", + "bpk": "application/octet-stream", + "dump": "application/octet-stream", + "elc": "application/octet-stream", + "deploy": "application/octet-stream", + "exe": "application/octet-stream", + "dll": "application/octet-stream", + "deb": "application/octet-stream", + "dmg": "application/octet-stream", + "iso": "application/octet-stream", + "img": "application/octet-stream", + "msi": "application/octet-stream", + "msp": "application/octet-stream", + "msm": "application/octet-stream", + "buffer": "application/octet-stream", + "oda": "application/oda", + "opf": "application/oebps-package+xml", + "ogx": "application/ogg", + "omdoc": "application/omdoc+xml", + "onetoc": "application/onenote", + "onetoc2": "application/onenote", + "onetmp": "application/onenote", + "onepkg": "application/onenote", + "oxps": "application/oxps", + "relo": "application/p2p-overlay+xml", + "xer": "application/patch-ops-error+xml", + "pdf": "application/pdf", + "pgp": "application/pgp-encrypted", + "asc": "application/pgp-signature", + "sig": "application/pgp-signature", + "prf": "application/pics-rules", + "p10": "application/pkcs10", + "p7m": "application/pkcs7-mime", + "p7c": "application/pkcs7-mime", + "p7s": "application/pkcs7-signature", + "p8": "application/pkcs8", + "ac": "application/pkix-attr-cert", + "cer": "application/pkix-cert", + "crl": "application/pkix-crl", + "pkipath": "application/pkix-pkipath", + "pki": "application/pkixcmp", + "pls": "application/pls+xml", + "ai": "application/postscript", + "eps": "application/postscript", + "ps": "application/postscript", + "provx": "application/provenance+xml", + "cww": "application/prs.cww", + "pskcxml": "application/pskc+xml", + "raml": "application/raml+yaml", + "rdf": "application/rdf+xml", + "owl": "application/rdf+xml", + "rif": "application/reginfo+xml", + "rnc": "application/relax-ng-compact-syntax", + "rl": "application/resource-lists+xml", + "rld": "application/resource-lists-diff+xml", + "rs": "application/rls-services+xml", + "rapd": "application/route-apd+xml", + "sls": "application/route-s-tsid+xml", + "rusd": "application/route-usd+xml", + "gbr": "application/rpki-ghostbusters", + "mft": "application/rpki-manifest", + "roa": "application/rpki-roa", + "rsd": "application/rsd+xml", + "rss": "application/rss+xml", + "rtf": "application/rtf", + "sbml": "application/sbml+xml", + "scq": "application/scvp-cv-request", + "scs": "application/scvp-cv-response", + "spq": "application/scvp-vp-request", + "spp": "application/scvp-vp-response", + "sdp": "application/sdp", + "senmlx": "application/senml+xml", + "sensmlx": "application/sensml+xml", + "setpay": "application/set-payment-initiation", + "setreg": "application/set-registration-initiation", + "shf": "application/shf+xml", + "siv": "application/sieve", + "sieve": "application/sieve", + "smi": "application/smil+xml", + "smil": "application/smil+xml", + "rq": "application/sparql-query", + "srx": "application/sparql-results+xml", + "gram": "application/srgs", + "grxml": "application/srgs+xml", + "sru": "application/sru+xml", + "ssdl": "application/ssdl+xml", + "ssml": "application/ssml+xml", + "swidtag": "application/swid+xml", + "tei": "application/tei+xml", + "teicorpus": "application/tei+xml", + "tfi": "application/thraud+xml", + "tsd": "application/timestamped-data", + "toml": "application/toml", + "trig": "application/trig", + "ttml": "application/ttml+xml", + "ubj": "application/ubjson", + "rsheet": "application/urc-ressheet+xml", + "td": "application/urc-targetdesc+xml", + "vxml": "application/voicexml+xml", + "wasm": "application/wasm", + "wgt": "application/widget", + "hlp": "application/winhlp", + "wsdl": "application/wsdl+xml", + "wspolicy": "application/wspolicy+xml", + "xaml": "application/xaml+xml", + "xav": "application/xcap-att+xml", + "xca": "application/xcap-caps+xml", + "xdf": "application/xcap-diff+xml", + "xel": "application/xcap-el+xml", + "xns": "application/xcap-ns+xml", + "xenc": "application/xenc+xml", + "xhtml": "application/xhtml+xml", + "xht": "application/xhtml+xml", + "xlf": "application/xliff+xml", + "xml": "application/xml", + "xsl": "application/xml", + "xsd": "application/xml", + "rng": "application/xml", + "dtd": "application/xml-dtd", + "xop": "application/xop+xml", + "xpl": "application/xproc+xml", + "xslt": "application/xml", + "xspf": "application/xspf+xml", + "mxml": "application/xv+xml", + "xhvml": "application/xv+xml", + "xvml": "application/xv+xml", + "xvm": "application/xv+xml", + "yang": "application/yang", + "yin": "application/yin+xml", + "zip": "application/zip", + "3gpp": "video/3gpp", + "adp": "audio/adpcm", + "amr": "audio/amr", + "au": "audio/basic", + "snd": "audio/basic", + "mid": "audio/midi", + "midi": "audio/midi", + "kar": "audio/midi", + "rmi": "audio/midi", + "mxmf": "audio/mobile-xmf", + "mp3": "audio/mpeg", + "m4a": "audio/mp4", + "mp4a": "audio/mp4", + "mpga": "audio/mpeg", + "mp2": "audio/mpeg", + "mp2a": "audio/mpeg", + "m2a": "audio/mpeg", + "m3a": "audio/mpeg", + "oga": "audio/ogg", + "ogg": "audio/ogg", + "spx": "audio/ogg", + "opus": "audio/ogg", + "s3m": "audio/s3m", + "sil": "audio/silk", + "wav": "audio/wav", + "weba": "audio/webm", + "xm": "audio/xm", + "ttc": "font/collection", + "otf": "font/otf", + "ttf": "font/ttf", + "woff": "font/woff", + "woff2": "font/woff2", + "exr": "image/aces", + "apng": "image/apng", + "avif": "image/avif", + "bmp": "image/bmp", + "cgm": "image/cgm", + "drle": "image/dicom-rle", + "emf": "image/emf", + "fits": "image/fits", + "g3": "image/g3fax", + "gif": "image/gif", + "heic": "image/heic", + "heics": "image/heic-sequence", + "heif": "image/heif", + "heifs": "image/heif-sequence", + "hej2": "image/hej2k", + "hsj2": "image/hsj2", + "ief": "image/ief", + "jls": "image/jls", + "jp2": "image/jp2", + "jpg2": "image/jp2", + "jpeg": "image/jpeg", + "jpg": "image/jpeg", + "jpe": "image/jpeg", + "jph": "image/jph", + "jhc": "image/jphc", + "jpm": "image/jpm", + "jpx": "image/jpx", + "jpf": "image/jpx", + "jxr": "image/jxr", + "jxra": "image/jxra", + "jxrs": "image/jxrs", + "jxs": "image/jxs", + "jxsc": "image/jxsc", + "jxsi": "image/jxsi", + "jxss": "image/jxss", + "ktx": "image/ktx", + "ktx2": "image/ktx2", + "png": "image/png", + "btif": "image/prs.btif", + "pti": "image/prs.pti", + "sgi": "image/sgi", + "svg": "image/svg+xml", + "svgz": "image/svg+xml", + "t38": "image/t38", + "tif": "image/tiff", + "tiff": "image/tiff", + "tfx": "image/tiff-fx", + "webp": "image/webp", + "wmf": "image/wmf", + "disposition-notification": "message/disposition-notification", + "u8msg": "message/global", + "u8dsn": "message/global-delivery-status", + "u8mdn": "message/global-disposition-notification", + "u8hdr": "message/global-headers", + "eml": "message/rfc822", + "mime": "message/rfc822", + "3mf": "model/3mf", + "gltf": "model/gltf+json", + "glb": "model/gltf-binary", + "igs": "model/iges", + "iges": "model/iges", + "msh": "model/mesh", + "mesh": "model/mesh", + "silo": "model/mesh", + "mtl": "model/mtl", + "obj": "model/obj", + "stpz": "model/step+zip", + "stpxz": "model/step-xml+zip", + "stl": "model/stl", + "wrl": "model/vrml", + "vrml": "model/vrml", + "x3db": "model/x3d+fastinfoset", + "x3dbz": "model/x3d+binary", + "x3dv": "model/x3d-vrml", + "x3dvz": "model/x3d+vrml", + "x3d": "model/x3d+xml", + "x3dz": "model/x3d+xml", + "appcache": "text/cache-manifest", + "manifest": "text/cache-manifest", + "ics": "text/calendar", + "ifb": "text/calendar", + "coffee": "text/coffeescript", + "litcoffee": "text/coffeescript", + "css": "text/css", + "csv": "text/csv", + "html": "text/html", + "htm": "text/html", + "shtml": "text/html", + "jade": "text/jade", + "jsx": "text/jsx", + "less": "text/less", + "markdown": "text/markdown", + "md": "text/markdown", + "mml": "text/mathml", + "mdx": "text/mdx", + "n3": "text/n3", + "txt": "text/plain", + "text": "text/plain", + "conf": "text/plain", + "def": "text/plain", + "list": "text/plain", + "log": "text/plain", + "in": "text/plain", + "ini": "text/plain", + "dsc": "text/prs.lines.tag", + "rtx": "text/richtext", + "sgml": "text/sgml", + "sgm": "text/sgml", + "shex": "text/shex", + "slim": "text/slim", + "slm": "text/slim", + "spdx": "text/spdx", + "stylus": "text/stylus", + "styl": "text/stylus", + "tsv": "text/tab-separated-values", + "t": "text/troff", + "tr": "text/troff", + "roff": "text/troff", + "man": "text/troff", + "me": "text/troff", + "ms": "text/troff", + "ttl": "text/turtle", + "uri": "text/uri-list", + "uris": "text/uri-list", + "urls": "text/uri-list", + "vcard": "text/vcard", + "vtt": "text/vtt", + "yaml": "text/yaml", + "yml": "text/yaml", + "3gp": "video/3gpp", + "3g2": "video/3gpp2", + "h261": "video/h261", + "h263": "video/h263", + "h264": "video/h264", + "m4s": "video/iso.segment", + "jpgv": "video/jpeg", + "jpgm": "image/jpm", + "mj2": "video/mj2", + "mjp2": "video/mj2", + "ts": "video/mp2t", + "mp4": "video/mp4", + "mp4v": "video/mp4", + "mpg4": "video/mp4", + "mpeg": "video/mpeg", + "mpg": "video/mpeg", + "mpe": "video/mpeg", + "m1v": "video/mpeg", + "m2v": "video/mpeg", + "ogv": "video/ogg", + "qt": "video/quicktime", + "mov": "video/quicktime", + "webm": "video/webm" +}; + +function lookup(extn) { + let tmp = ('' + extn).trim().toLowerCase(); + let idx = tmp.lastIndexOf('.'); + return mimes$1[!~idx ? tmp : tmp.substring(++idx)]; +} + +const publicFilesMap = new WeakMap(); +async function initPublicFiles(config) { + let fileNames; + try { + fileNames = await recursiveReaddir(config.publicDir); + } + catch (e) { + if (e.code === ERR_SYMLINK_IN_RECURSIVE_READDIR) { + return; + } + throw e; + } + const publicFiles = new Set(fileNames.map((fileName) => fileName.slice(config.publicDir.length))); + publicFilesMap.set(config, publicFiles); + return publicFiles; +} +function getPublicFiles(config) { + return publicFilesMap.get(config); +} +function checkPublicFile(url, config) { + // note if the file is in /public, the resolver would have returned it + // as-is so it's not going to be a fully resolved path. + const { publicDir } = config; + if (!publicDir || url[0] !== '/') { + return; + } + const fileName = cleanUrl(url); + // short-circuit if we have an in-memory publicFiles cache + const publicFiles = getPublicFiles(config); + if (publicFiles) { + return publicFiles.has(fileName) + ? normalizePath$3(path$o.join(publicDir, fileName)) + : undefined; + } + const publicFile = normalizePath$3(path$o.join(publicDir, fileName)); + if (!publicFile.startsWith(withTrailingSlash(normalizePath$3(publicDir)))) { + // can happen if URL starts with '../' + return; + } + return fs$l.existsSync(publicFile) ? publicFile : undefined; +} + +// referenceId is base64url but replaces - with $ +const assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g; +const rawRE = /(?:\?|&)raw(?:&|$)/; +const urlRE = /(\?|&)url(?:&|$)/; +const jsSourceMapRE = /\.[cm]?js\.map$/; +const unnededFinalQueryCharRE = /[?&]$/; +const assetCache = new WeakMap(); +const generatedAssets = new WeakMap(); +// add own dictionary entry by directly assigning mrmime +function registerCustomMime() { + // https://github.com/lukeed/mrmime/issues/3 + mimes$1['ico'] = 'image/x-icon'; + // https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers#flac + mimes$1['flac'] = 'audio/flac'; + // mrmime and mime-db is not released yet: https://github.com/jshttp/mime-db/commit/c9242a9b7d4bb25d7a0c9244adec74aeef08d8a1 + mimes$1['aac'] = 'audio/aac'; + // https://wiki.xiph.org/MIME_Types_and_File_Extensions#.opus_-_audio/ogg + mimes$1['opus'] = 'audio/ogg'; + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types + mimes$1['eot'] = 'application/vnd.ms-fontobject'; +} +function renderAssetUrlInJS(ctx, config, chunk, opts, code) { + const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(opts.format, config.isWorker); + let match; + let s; + // Urls added with JS using e.g. + // imgElement.src = "__VITE_ASSET__5aA0Ddc0__" are using quotes + // Urls added in CSS that is imported in JS end up like + // var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aA0Ddc0__)}\n"; + // In both cases, the wrapping should already be fine + assetUrlRE.lastIndex = 0; + while ((match = assetUrlRE.exec(code))) { + s ||= new MagicString(code); + const [full, referenceId, postfix = ''] = match; + const file = ctx.getFileName(referenceId); + chunk.viteMetadata.importedAssets.add(cleanUrl(file)); + const filename = file + postfix; + const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime); + const replacementString = typeof replacement === 'string' + ? JSON.stringify(replacement).slice(1, -1) + : `"+${replacement.runtime}+"`; + s.update(match.index, match.index + full.length, replacementString); + } + // Replace __VITE_PUBLIC_ASSET__5aA0Ddc0__ with absolute paths + const publicAssetUrlMap = publicAssetUrlCache.get(config); + publicAssetUrlRE.lastIndex = 0; + while ((match = publicAssetUrlRE.exec(code))) { + s ||= new MagicString(code); + const [full, hash] = match; + const publicUrl = publicAssetUrlMap.get(hash).slice(1); + const replacement = toOutputFilePathInJS(publicUrl, 'public', chunk.fileName, 'js', config, toRelativeRuntime); + const replacementString = typeof replacement === 'string' + ? JSON.stringify(replacement).slice(1, -1) + : `"+${replacement.runtime}+"`; + s.update(match.index, match.index + full.length, replacementString); + } + return s; +} +// During build, if we don't use a virtual file for public assets, rollup will +// watch for these ids resulting in watching the root of the file system in Windows, +const viteBuildPublicIdPrefix = '\0vite:asset:public'; +/** + * Also supports loading plain strings with import text from './foo.txt?raw' + */ +function assetPlugin(config) { + registerCustomMime(); + let moduleGraph; + return { + name: 'vite:asset', + buildStart() { + assetCache.set(config, new Map()); + generatedAssets.set(config, new Map()); + }, + configureServer(server) { + moduleGraph = server.moduleGraph; + }, + resolveId(id) { + if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) { + return; + } + // imports to absolute urls pointing to files in /public + // will fail to resolve in the main resolver. handle them here. + const publicFile = checkPublicFile(id, config); + if (publicFile) { + return config.command === 'build' + ? `${viteBuildPublicIdPrefix}${id}` + : id; + } + }, + async load(id) { + if (id.startsWith(viteBuildPublicIdPrefix)) { + id = id.slice(viteBuildPublicIdPrefix.length); + } + if (id[0] === '\0') { + // Rollup convention, this id should be handled by the + // plugin that marked it with \0 + return; + } + // raw requests, read from disk + if (rawRE.test(id)) { + const file = checkPublicFile(id, config) || cleanUrl(id); + this.addWatchFile(file); + // raw query, read file and return as string + return `export default ${JSON.stringify(await fsp.readFile(file, 'utf-8'))}`; + } + if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) { + return; + } + id = id.replace(urlRE, '$1').replace(unnededFinalQueryCharRE, ''); + let url = await fileToUrl$1(id, config, this); + // Inherit HMR timestamp if this asset was invalidated + if (moduleGraph) { + const mod = moduleGraph.getModuleById(id); + if (mod && mod.lastHMRTimestamp > 0) { + url = injectQuery(url, `t=${mod.lastHMRTimestamp}`); + } + } + return `export default ${JSON.stringify(url)}`; + }, + renderChunk(code, chunk, opts) { + const s = renderAssetUrlInJS(this, config, chunk, opts, code); + if (s) { + return { + code: s.toString(), + map: config.build.sourcemap + ? s.generateMap({ hires: 'boundary' }) + : null, + }; + } + else { + return null; + } + }, + generateBundle(_, bundle) { + // do not emit assets for SSR build + if (config.command === 'build' && + config.build.ssr && + !config.build.ssrEmitAssets) { + for (const file in bundle) { + if (bundle[file].type === 'asset' && + !file.endsWith('ssr-manifest.json') && + !jsSourceMapRE.test(file)) { + delete bundle[file]; + } + } + } + }, + }; +} +async function fileToUrl$1(id, config, ctx) { + if (config.command === 'serve') { + return fileToDevUrl(id, config); + } + else { + return fileToBuiltUrl(id, config, ctx); + } +} +function fileToDevUrl(id, config) { + let rtn; + if (checkPublicFile(id, config)) { + // in public dir during dev, keep the url as-is + rtn = id; + } + else if (id.startsWith(withTrailingSlash(config.root))) { + // in project root, infer short public path + rtn = '/' + path$o.posix.relative(config.root, id); + } + else { + // outside of project root, use absolute fs path + // (this is special handled by the serve static middleware + rtn = path$o.posix.join(FS_PREFIX, id); + } + const base = joinUrlSegments(config.server?.origin ?? '', config.base); + return joinUrlSegments(base, removeLeadingSlash(rtn)); +} +function getPublicAssetFilename(hash, config) { + return publicAssetUrlCache.get(config)?.get(hash); +} +const publicAssetUrlCache = new WeakMap(); +const publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g; +function publicFileToBuiltUrl(url, config) { + if (config.command !== 'build') { + // We don't need relative base or renderBuiltUrl support during dev + return joinUrlSegments(config.base, url); + } + const hash = getHash(url); + let cache = publicAssetUrlCache.get(config); + if (!cache) { + cache = new Map(); + publicAssetUrlCache.set(config, cache); + } + if (!cache.get(hash)) { + cache.set(hash, url); + } + return `__VITE_PUBLIC_ASSET__${hash}__`; +} +const GIT_LFS_PREFIX = Buffer$1.from('version https://git-lfs.github.com'); +function isGitLfsPlaceholder(content) { + if (content.length < GIT_LFS_PREFIX.length) + return false; + // Check whether the content begins with the characteristic string of Git LFS placeholders + return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0; +} +/** + * Register an asset to be emitted as part of the bundle (if necessary) + * and returns the resolved public URL + */ +async function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false, shouldInline) { + if (!skipPublicCheck && checkPublicFile(id, config)) { + return publicFileToBuiltUrl(id, config); + } + const cache = assetCache.get(config); + const cached = cache.get(id); + if (cached) { + return cached; + } + const file = cleanUrl(id); + const content = await fsp.readFile(file); + if (shouldInline == null) { + shouldInline = + !!config.build.lib || + // Don't inline SVG with fragments, as they are meant to be reused + (!(file.endsWith('.svg') && id.includes('#')) && + !file.endsWith('.html') && + content.length < Number(config.build.assetsInlineLimit) && + !isGitLfsPlaceholder(content)); + } + let url; + if (shouldInline) { + if (config.build.lib && isGitLfsPlaceholder(content)) { + config.logger.warn(colors$1.yellow(`Inlined file ${id} was not downloaded via Git LFS`)); + } + if (file.endsWith('.svg')) { + url = svgToDataURL(content); + } + else { + const mimeType = lookup(file) ?? 'application/octet-stream'; + // base64 inlined as a string + url = `data:${mimeType};base64,${content.toString('base64')}`; + } + } + else { + // emit as asset + const { search, hash } = parse$i(id); + const postfix = (search || '') + (hash || ''); + const referenceId = pluginContext.emitFile({ + // Ignore directory structure for asset file names + name: path$o.basename(file), + type: 'asset', + source: content, + }); + const originalName = normalizePath$3(path$o.relative(config.root, file)); + generatedAssets.get(config).set(referenceId, { originalName }); + url = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`; // TODO_BASE + } + cache.set(id, url); + return url; +} +async function urlToBuiltUrl(url, importer, config, pluginContext, shouldInline) { + if (checkPublicFile(url, config)) { + return publicFileToBuiltUrl(url, config); + } + const file = url[0] === '/' + ? path$o.join(config.root, url) + : path$o.join(path$o.dirname(importer), url); + return fileToBuiltUrl(file, config, pluginContext, + // skip public check since we just did it above + true, shouldInline); +} +const nestedQuotesRE = /"[^"']*'[^"]*"|'[^'"]*"[^']*'/; +// Inspired by https://github.com/iconify/iconify/blob/main/packages/utils/src/svg/url.ts +function svgToDataURL(content) { + const stringContent = content.toString(); + // If the SVG contains some text or HTML, any transformation is unsafe, and given that double quotes would then + // need to be escaped, the gain to use a data URI would be ridiculous if not negative + if (stringContent.includes('\s+<') + .replaceAll('"', "'") + .replaceAll('%', '%25') + .replaceAll('#', '%23') + .replaceAll('<', '%3c') + .replaceAll('>', '%3e') + // Spaces are not valid in srcset it has some use cases + // it can make the uncompressed URI slightly higher than base64, but will compress way better + // https://github.com/vitejs/vite/pull/14643#issuecomment-1766288673 + .replaceAll(/\s+/g, '%20')); + } +} + +function manifestPlugin(config) { + const manifest = {}; + let outputCount; + return { + name: 'vite:manifest', + buildStart() { + outputCount = 0; + }, + generateBundle({ format }, bundle) { + function getChunkName(chunk) { + return getChunkOriginalFileName(chunk, config.root, format); + } + function getInternalImports(imports) { + const filteredImports = []; + for (const file of imports) { + if (bundle[file] === undefined) { + continue; + } + filteredImports.push(getChunkName(bundle[file])); + } + return filteredImports; + } + function createChunk(chunk) { + const manifestChunk = { + file: chunk.fileName, + }; + if (chunk.facadeModuleId) { + manifestChunk.src = getChunkName(chunk); + } + if (chunk.isEntry) { + manifestChunk.isEntry = true; + } + if (chunk.isDynamicEntry) { + manifestChunk.isDynamicEntry = true; + } + if (chunk.imports.length) { + const internalImports = getInternalImports(chunk.imports); + if (internalImports.length > 0) { + manifestChunk.imports = internalImports; + } + } + if (chunk.dynamicImports.length) { + const internalImports = getInternalImports(chunk.dynamicImports); + if (internalImports.length > 0) { + manifestChunk.dynamicImports = internalImports; + } + } + if (chunk.viteMetadata?.importedCss.size) { + manifestChunk.css = [...chunk.viteMetadata.importedCss]; + } + if (chunk.viteMetadata?.importedAssets.size) { + manifestChunk.assets = [...chunk.viteMetadata.importedAssets]; + } + return manifestChunk; + } + function createAsset(asset, src, isEntry) { + const manifestChunk = { + file: asset.fileName, + src, + }; + if (isEntry) + manifestChunk.isEntry = true; + return manifestChunk; + } + const fileNameToAssetMeta = new Map(); + const assets = generatedAssets.get(config); + assets.forEach((asset, referenceId) => { + try { + const fileName = this.getFileName(referenceId); + fileNameToAssetMeta.set(fileName, asset); + } + catch (error) { + // The asset was generated as part of a different output option. + // It was already handled during the previous run of this plugin. + assets.delete(referenceId); + } + }); + const fileNameToAsset = new Map(); + for (const file in bundle) { + const chunk = bundle[file]; + if (chunk.type === 'chunk') { + manifest[getChunkName(chunk)] = createChunk(chunk); + } + else if (chunk.type === 'asset' && typeof chunk.name === 'string') { + // Add every unique asset to the manifest, keyed by its original name + const assetMeta = fileNameToAssetMeta.get(chunk.fileName); + const src = assetMeta?.originalName ?? chunk.name; + const asset = createAsset(chunk, src, assetMeta?.isEntry); + // If JS chunk and asset chunk are both generated from the same source file, + // prioritize JS chunk as it contains more information + if (manifest[src]?.file.endsWith('.js')) + continue; + manifest[src] = asset; + fileNameToAsset.set(chunk.fileName, asset); + } + } + // Add deduplicated assets to the manifest + assets.forEach(({ originalName }, referenceId) => { + if (!manifest[originalName]) { + const fileName = this.getFileName(referenceId); + const asset = fileNameToAsset.get(fileName); + if (asset) { + manifest[originalName] = asset; + } + } + }); + outputCount++; + const output = config.build.rollupOptions?.output; + const outputLength = Array.isArray(output) ? output.length : 1; + if (outputCount >= outputLength) { + this.emitFile({ + fileName: typeof config.build.manifest === 'string' + ? config.build.manifest + : '.vite/manifest.json', + type: 'asset', + source: jsonStableStringify$1(manifest, { space: 2 }), + }); + } + }, + }; +} +function getChunkOriginalFileName(chunk, root, format) { + if (chunk.facadeModuleId) { + let name = normalizePath$3(path$o.relative(root, chunk.facadeModuleId)); + if (format === 'system' && !chunk.name.includes('-legacy')) { + const ext = path$o.extname(name); + const endPos = ext.length !== 0 ? -ext.length : undefined; + name = name.slice(0, endPos) + `-legacy` + ext; + } + return name.replace(/\0/g, ''); + } + else { + return `_` + path$o.basename(chunk.fileName); + } +} + +// This is based on @rollup/plugin-data-uri +// MIT Licensed https://github.com/rollup/plugins/blob/master/LICENSE +// ref https://github.com/vitejs/vite/issues/1428#issuecomment-757033808 +const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/; +const base64RE = /base64/i; +const dataUriPrefix = `\0/@data-uri/`; +/** + * Build only, since importing from a data URI works natively. + */ +function dataURIPlugin() { + let resolved; + return { + name: 'vite:data-uri', + buildStart() { + resolved = new Map(); + }, + resolveId(id) { + if (!dataUriRE.test(id)) { + return; + } + const uri = new URL$3(id); + if (uri.protocol !== 'data:') { + return; + } + const match = uri.pathname.match(dataUriRE); + if (!match) { + return; + } + const [, mime, format, data] = match; + if (mime !== 'text/javascript') { + throw new Error(`data URI with non-JavaScript mime type is not supported. If you're using legacy JavaScript MIME types (such as 'application/javascript'), please use 'text/javascript' instead.`); + } + // decode data + const base64 = format && base64RE.test(format.substring(1)); + const content = base64 + ? Buffer.from(data, 'base64').toString('utf-8') + : data; + resolved.set(id, content); + return dataUriPrefix + id; + }, + load(id) { + if (id.startsWith(dataUriPrefix)) { + return resolved.get(id.slice(dataUriPrefix.length)); + } + }, + }; +} + +/* es-module-lexer 1.4.1 */ +const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];function parse$e(E,g="@"){if(!C)return init.then((()=>parse$e(E)));const I=E.length+1,k=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;k>0&&C.memory.grow(Math.ceil(k/65536));const K=C.sa(I-1);if((A?B:Q)(E,new Uint16Array(C.memory.buffer,K,I)),!C.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,C.e()).split("\n").length}:${C.e()-E.lastIndexOf("\n",C.e()-1)}`),{idx:C.e()});const o=[],D=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.ai(),g=C.id(),I=C.ss(),k=C.se();let K;C.ip()&&(K=w(E.slice(-1===g?A-1:A,-1===g?Q+1:Q))),o.push({n:K,s:A,e:Q,ss:I,se:k,d:g,a:B});}for(;C.re();){const A=C.es(),Q=C.ee(),B=C.els(),g=C.ele(),I=E.slice(A,Q),k=I[0],K=B<0?void 0:E.slice(B,g),o=K?K[0]:"";D.push({s:A,e:Q,ls:B,le:g,n:'"'===k||"'"===k?w(I):I,ln:'"'===o||"'"===o?w(K):K});}function w(A){try{return (0, eval)(A)}catch(A){}}return [o,D,!!C.f(),!!C.ms()]}function Q(A,Q){const B=A.length;let C=0;for(;C>>8;}}function B(A,Q){const B=A.length;let C=0;for(;CA.charCodeAt(0))))).then(WebAssembly.instantiate).then((({exports:A})=>{C=A;}));var E; + +var convertSourceMap$1 = {}; + +(function (exports) { + + Object.defineProperty(exports, 'commentRegex', { + get: function getCommentRegex () { + // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data. + return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg; + } + }); + + + Object.defineProperty(exports, 'mapFileCommentRegex', { + get: function getMapFileCommentRegex () { + // Matches sourceMappingURL in either // or /* comment styles. + return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg; + } + }); + + var decodeBase64; + if (typeof Buffer !== 'undefined') { + if (typeof Buffer.from === 'function') { + decodeBase64 = decodeBase64WithBufferFrom; + } else { + decodeBase64 = decodeBase64WithNewBuffer; + } + } else { + decodeBase64 = decodeBase64WithAtob; + } + + function decodeBase64WithBufferFrom(base64) { + return Buffer.from(base64, 'base64').toString(); + } + + function decodeBase64WithNewBuffer(base64) { + if (typeof value === 'number') { + throw new TypeError('The value to decode must not be of type number.'); + } + return new Buffer(base64, 'base64').toString(); + } + + function decodeBase64WithAtob(base64) { + return decodeURIComponent(escape(atob(base64))); + } + + function stripComment(sm) { + return sm.split(',').pop(); + } + + function readFromFileMap(sm, read) { + var r = exports.mapFileCommentRegex.exec(sm); + // for some odd reason //# .. captures in 1 and /* .. */ in 2 + var filename = r[1] || r[2]; + + try { + var sm = read(filename); + if (sm != null && typeof sm.catch === 'function') { + return sm.catch(throwError); + } else { + return sm; + } + } catch (e) { + throwError(e); + } + + function throwError(e) { + throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack); + } + } + + function Converter (sm, opts) { + opts = opts || {}; + + if (opts.hasComment) { + sm = stripComment(sm); + } + + if (opts.encoding === 'base64') { + sm = decodeBase64(sm); + } else if (opts.encoding === 'uri') { + sm = decodeURIComponent(sm); + } + + if (opts.isJSON || opts.encoding) { + sm = JSON.parse(sm); + } + + this.sourcemap = sm; + } + + Converter.prototype.toJSON = function (space) { + return JSON.stringify(this.sourcemap, null, space); + }; + + if (typeof Buffer !== 'undefined') { + if (typeof Buffer.from === 'function') { + Converter.prototype.toBase64 = encodeBase64WithBufferFrom; + } else { + Converter.prototype.toBase64 = encodeBase64WithNewBuffer; + } + } else { + Converter.prototype.toBase64 = encodeBase64WithBtoa; + } + + function encodeBase64WithBufferFrom() { + var json = this.toJSON(); + return Buffer.from(json, 'utf8').toString('base64'); + } + + function encodeBase64WithNewBuffer() { + var json = this.toJSON(); + if (typeof json === 'number') { + throw new TypeError('The json to encode must not be of type number.'); + } + return new Buffer(json, 'utf8').toString('base64'); + } + + function encodeBase64WithBtoa() { + var json = this.toJSON(); + return btoa(unescape(encodeURIComponent(json))); + } + + Converter.prototype.toURI = function () { + var json = this.toJSON(); + return encodeURIComponent(json); + }; + + Converter.prototype.toComment = function (options) { + var encoding, content, data; + if (options != null && options.encoding === 'uri') { + encoding = ''; + content = this.toURI(); + } else { + encoding = ';base64'; + content = this.toBase64(); + } + data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content; + return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; + }; + + // returns copy instead of original + Converter.prototype.toObject = function () { + return JSON.parse(this.toJSON()); + }; + + Converter.prototype.addProperty = function (key, value) { + if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead'); + return this.setProperty(key, value); + }; + + Converter.prototype.setProperty = function (key, value) { + this.sourcemap[key] = value; + return this; + }; + + Converter.prototype.getProperty = function (key) { + return this.sourcemap[key]; + }; + + exports.fromObject = function (obj) { + return new Converter(obj); + }; + + exports.fromJSON = function (json) { + return new Converter(json, { isJSON: true }); + }; + + exports.fromURI = function (uri) { + return new Converter(uri, { encoding: 'uri' }); + }; + + exports.fromBase64 = function (base64) { + return new Converter(base64, { encoding: 'base64' }); + }; + + exports.fromComment = function (comment) { + var m, encoding; + comment = comment + .replace(/^\/\*/g, '//') + .replace(/\*\/$/g, ''); + m = exports.commentRegex.exec(comment); + encoding = m && m[4] || 'uri'; + return new Converter(comment, { encoding: encoding, hasComment: true }); + }; + + function makeConverter(sm) { + return new Converter(sm, { isJSON: true }); + } + + exports.fromMapFileComment = function (comment, read) { + if (typeof read === 'string') { + throw new Error( + 'String directory paths are no longer supported with `fromMapFileComment`\n' + + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' + ) + } + + var sm = readFromFileMap(comment, read); + if (sm != null && typeof sm.then === 'function') { + return sm.then(makeConverter); + } else { + return makeConverter(sm); + } + }; + + // Finds last sourcemap comment in file or returns null if none was found + exports.fromSource = function (content) { + var m = content.match(exports.commentRegex); + return m ? exports.fromComment(m.pop()) : null; + }; + + // Finds last sourcemap comment in file or returns null if none was found + exports.fromMapFileSource = function (content, read) { + if (typeof read === 'string') { + throw new Error( + 'String directory paths are no longer supported with `fromMapFileSource`\n' + + 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading' + ) + } + var m = content.match(exports.mapFileCommentRegex); + return m ? exports.fromMapFileComment(m.pop(), read) : null; + }; + + exports.removeComments = function (src) { + return src.replace(exports.commentRegex, ''); + }; + + exports.removeMapFileComments = function (src) { + return src.replace(exports.mapFileCommentRegex, ''); + }; + + exports.generateMapFileComment = function (file, options) { + var data = 'sourceMappingURL=' + file; + return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; + }; +} (convertSourceMap$1)); + +var convertSourceMap = /*@__PURE__*/getDefaultExportFromCjs(convertSourceMap$1); + +const debug$g = createDebugger('vite:sourcemap', { + onlyWhenFocused: true, +}); +// Virtual modules should be prefixed with a null byte to avoid a +// false positive "missing source" warning. We also check for certain +// prefixes used for special handling in esbuildDepPlugin. +const virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/; +async function computeSourceRoute(map, file) { + let sourceRoot; + try { + // The source root is undefined for virtual modules and permission errors. + sourceRoot = await fsp.realpath(path$o.resolve(path$o.dirname(file), map.sourceRoot || '')); + } + catch { } + return sourceRoot; +} +async function injectSourcesContent(map, file, logger) { + let sourceRootPromise; + const missingSources = []; + const sourcesContent = map.sourcesContent || []; + const sourcesContentPromises = []; + for (let index = 0; index < map.sources.length; index++) { + const sourcePath = map.sources[index]; + if (!sourcesContent[index] && + sourcePath && + !virtualSourceRE.test(sourcePath)) { + sourcesContentPromises.push((async () => { + // inject content from source file when sourcesContent is null + sourceRootPromise ??= computeSourceRoute(map, file); + const sourceRoot = await sourceRootPromise; + let resolvedSourcePath = decodeURI(sourcePath); + if (sourceRoot) { + resolvedSourcePath = path$o.resolve(sourceRoot, resolvedSourcePath); + } + sourcesContent[index] = await fsp + .readFile(resolvedSourcePath, 'utf-8') + .catch(() => { + missingSources.push(resolvedSourcePath); + return null; + }); + })()); + } + } + await Promise.all(sourcesContentPromises); + map.sourcesContent = sourcesContent; + // Use this command… + // DEBUG="vite:sourcemap" vite build + // …to log the missing sources. + if (missingSources.length) { + logger.warnOnce(`Sourcemap for "${file}" points to missing source files`); + debug$g?.(`Missing sources:\n ` + missingSources.join(`\n `)); + } +} +function genSourceMapUrl(map) { + if (typeof map !== 'string') { + map = JSON.stringify(map); + } + return `data:application/json;base64,${Buffer.from(map).toString('base64')}`; +} +function getCodeWithSourcemap(type, code, map) { + if (debug$g) { + code += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`; + } + if (type === 'js') { + code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`; + } + else if (type === 'css') { + code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`; + } + return code; +} +function applySourcemapIgnoreList(map, sourcemapPath, sourcemapIgnoreList, logger) { + let { x_google_ignoreList } = map; + if (x_google_ignoreList === undefined) { + x_google_ignoreList = []; + } + for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) { + const sourcePath = map.sources[sourcesIndex]; + if (!sourcePath) + continue; + const ignoreList = sourcemapIgnoreList(path$o.isAbsolute(sourcePath) + ? sourcePath + : path$o.resolve(path$o.dirname(sourcemapPath), sourcePath), sourcemapPath); + if (logger && typeof ignoreList !== 'boolean') { + logger.warn('sourcemapIgnoreList function must return a boolean.'); + } + if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) { + x_google_ignoreList.push(sourcesIndex); + } + } + if (x_google_ignoreList.length > 0) { + if (!map.x_google_ignoreList) + map.x_google_ignoreList = x_google_ignoreList; + } +} + +var tasks = {}; + +var utils$g = {}; + +var array$1 = {}; + +Object.defineProperty(array$1, "__esModule", { value: true }); +array$1.splitWhen = array$1.flatten = void 0; +function flatten$1(items) { + return items.reduce((collection, item) => [].concat(collection, item), []); +} +array$1.flatten = flatten$1; +function splitWhen(items, predicate) { + const result = [[]]; + let groupIndex = 0; + for (const item of items) { + if (predicate(item)) { + groupIndex++; + result[groupIndex] = []; + } + else { + result[groupIndex].push(item); + } + } + return result; +} +array$1.splitWhen = splitWhen; + +var errno$1 = {}; + +Object.defineProperty(errno$1, "__esModule", { value: true }); +errno$1.isEnoentCodeError = void 0; +function isEnoentCodeError(error) { + return error.code === 'ENOENT'; +} +errno$1.isEnoentCodeError = isEnoentCodeError; + +var fs$h = {}; + +Object.defineProperty(fs$h, "__esModule", { value: true }); +fs$h.createDirentFromStats = void 0; +let DirentFromStats$1 = class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +}; +function createDirentFromStats$1(name, stats) { + return new DirentFromStats$1(name, stats); +} +fs$h.createDirentFromStats = createDirentFromStats$1; + +var path$h = {}; + +Object.defineProperty(path$h, "__esModule", { value: true }); +path$h.convertPosixPathToPattern = path$h.convertWindowsPathToPattern = path$h.convertPathToPattern = path$h.escapePosixPath = path$h.escapeWindowsPath = path$h.escape = path$h.removeLeadingDotSegment = path$h.makeAbsolute = path$h.unixify = void 0; +const os$3 = require$$2; +const path$g = require$$0$4; +const IS_WINDOWS_PLATFORM = os$3.platform() === 'win32'; +const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ +/** + * All non-escaped special characters. + * Posix: ()*?[]{|}, !+@ before (, ! at the beginning, \\ before non-special characters. + * Windows: (){}[], !+@ before (, ! at the beginning. + */ +const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g; +const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g; +/** + * The device path (\\.\ or \\?\). + * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths + */ +const DOS_DEVICE_PATH_RE = /^\\\\([.?])/; +/** + * All backslashes except those escaping special characters. + * Windows: !()+@{} + * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions + */ +const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g; +/** + * Designed to work only with simple paths: `dir\\file`. + */ +function unixify(filepath) { + return filepath.replace(/\\/g, '/'); +} +path$h.unixify = unixify; +function makeAbsolute(cwd, filepath) { + return path$g.resolve(cwd, filepath); +} +path$h.makeAbsolute = makeAbsolute; +function removeLeadingDotSegment(entry) { + // We do not use `startsWith` because this is 10x slower than current implementation for some cases. + // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with + if (entry.charAt(0) === '.') { + const secondCharactery = entry.charAt(1); + if (secondCharactery === '/' || secondCharactery === '\\') { + return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); + } + } + return entry; +} +path$h.removeLeadingDotSegment = removeLeadingDotSegment; +path$h.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; +function escapeWindowsPath(pattern) { + return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +path$h.escapeWindowsPath = escapeWindowsPath; +function escapePosixPath(pattern) { + return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +path$h.escapePosixPath = escapePosixPath; +path$h.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; +function convertWindowsPathToPattern(filepath) { + return escapeWindowsPath(filepath) + .replace(DOS_DEVICE_PATH_RE, '//$1') + .replace(WINDOWS_BACKSLASHES_RE, '/'); +} +path$h.convertWindowsPathToPattern = convertWindowsPathToPattern; +function convertPosixPathToPattern(filepath) { + return escapePosixPath(filepath); +} +path$h.convertPosixPathToPattern = convertPosixPathToPattern; + +var pattern$1 = {}; + +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +var isExtglob$1 = function isExtglob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + var match; + while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + + return false; +}; + +/*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +var isExtglob = isExtglob$1; +var chars = { '{': '}', '(': ')', '[': ']'}; +var strictCheck = function(str) { + if (str[0] === '!') { + return true; + } + var index = 0; + var pipeIndex = -2; + var closeSquareIndex = -2; + var closeCurlyIndex = -2; + var closeParenIndex = -2; + var backSlashIndex = -2; + while (index < str.length) { + if (str[index] === '*') { + return true; + } + + if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) { + return true; + } + + if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') { + if (closeSquareIndex < index) { + closeSquareIndex = str.indexOf(']', index); + } + if (closeSquareIndex > index) { + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + } + } + + if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') { + closeCurlyIndex = str.indexOf('}', index); + if (closeCurlyIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { + return true; + } + } + } + + if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') { + closeParenIndex = str.indexOf(')', index); + if (closeParenIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + + if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') { + if (pipeIndex < index) { + pipeIndex = str.indexOf('|', index); + } + if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') { + closeParenIndex = str.indexOf(')', pipeIndex); + if (closeParenIndex > pipeIndex) { + backSlashIndex = str.indexOf('\\', pipeIndex); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; + +var relaxedCheck = function(str) { + if (str[0] === '!') { + return true; + } + var index = 0; + while (index < str.length) { + if (/[*?{}()[\]]/.test(str[index])) { + return true; + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; + +var isGlob$2 = function isGlob(str, options) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) { + return true; + } + + var check = strictCheck; + + // optionally relax check + if (options && options.strict === false) { + check = relaxedCheck; + } + + return check(str); +}; + +var isGlob$1 = isGlob$2; +var pathPosixDirname = require$$0$4.posix.dirname; +var isWin32 = require$$2.platform() === 'win32'; + +var slash = '/'; +var backslash = /\\/g; +var enclosure = /[\{\[].*[\}\]]$/; +var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; +var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; + +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + * @returns {string} + */ +var globParent$2 = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + + // flip windows path separators + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } + + // special case for strings ending in enclosure containing path separator + if (enclosure.test(str)) { + str += slash; + } + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do { + str = pathPosixDirname(str); + } while (isGlob$1(str) || globby.test(str)); + + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; + +var utils$f = {}; + +(function (exports) { + + exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + return false; + }; + + /** + * Find a node of the given type + */ + + exports.find = (node, type) => node.nodes.find(node => node.type === type); + + /** + * Find a node of the given type + */ + + exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return ((Number(max) - Number(min)) / Number(step)) >= limit; + }; + + /** + * Escape the given node with '\\' before node.value + */ + + exports.escapeNode = (block, n = 0, type) => { + let node = block.nodes[n]; + if (!node) return; + + if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { + if (node.escaped !== true) { + node.value = '\\' + node.value; + node.escaped = true; + } + } + }; + + /** + * Returns true if the given brace node should be enclosed in literal braces + */ + + exports.encloseBrace = node => { + if (node.type !== 'brace') return false; + if ((node.commas >> 0 + node.ranges >> 0) === 0) { + node.invalid = true; + return true; + } + return false; + }; + + /** + * Returns true if a brace node is invalid. + */ + + exports.isInvalidBrace = block => { + if (block.type !== 'brace') return false; + if (block.invalid === true || block.dollar) return true; + if ((block.commas >> 0 + block.ranges >> 0) === 0) { + block.invalid = true; + return true; + } + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + return false; + }; + + /** + * Returns true if a node is an open or close node + */ + + exports.isOpenOrClose = node => { + if (node.type === 'open' || node.type === 'close') { + return true; + } + return node.open === true || node.close === true; + }; + + /** + * Reduce an array of text nodes. + */ + + exports.reduce = nodes => nodes.reduce((acc, node) => { + if (node.type === 'text') acc.push(node.value); + if (node.type === 'range') node.type = 'text'; + return acc; + }, []); + + /** + * Flatten an array + */ + + exports.flatten = (...args) => { + const result = []; + const flat = arr => { + for (let i = 0; i < arr.length; i++) { + let ele = arr[i]; + Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele); + } + return result; + }; + flat(args); + return result; + }; +} (utils$f)); + +const utils$e = utils$f; + +var stringify$7 = (ast, options = {}) => { + let stringify = (node, parent = {}) => { + let invalidBlock = options.escapeInvalid && utils$e.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; + + if (node.value) { + if ((invalidBlock || invalidNode) && utils$e.isOpenOrClose(node)) { + return '\\' + node.value; + } + return node.value; + } + + if (node.value) { + return node.value; + } + + if (node.nodes) { + for (let child of node.nodes) { + output += stringify(child); + } + } + return output; + }; + + return stringify(ast); +}; + +/*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + +var isNumber$2 = function(num) { + if (typeof num === 'number') { + return num - num === 0; + } + if (typeof num === 'string' && num.trim() !== '') { + return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + } + return false; +}; + +/*! + * to-regex-range + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Released under the MIT License. + */ + +const isNumber$1 = isNumber$2; + +const toRegexRange$1 = (min, max, options) => { + if (isNumber$1(min) === false) { + throw new TypeError('toRegexRange: expected the first argument to be a number'); + } + + if (max === void 0 || min === max) { + return String(min); + } + + if (isNumber$1(max) === false) { + throw new TypeError('toRegexRange: expected the second argument to be a number.'); + } + + let opts = { relaxZeros: true, ...options }; + if (typeof opts.strictZeros === 'boolean') { + opts.relaxZeros = opts.strictZeros === false; + } + + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; + + if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) { + return toRegexRange$1.cache[cacheKey].result; + } + + let a = Math.min(min, max); + let b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + let result = min + '|' + max; + if (opts.capture) { + return `(${result})`; + } + if (opts.wrap === false) { + return result; + } + return `(?:${result})`; + } + + let isPadded = hasPadding(min) || hasPadding(max); + let state = { min, max, a, b }; + let positives = []; + let negatives = []; + + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives); + + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) { + state.result = `(?:${state.result})`; + } + + toRegexRange$1.cache[cacheKey] = state; + return state.result; +}; + +function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, '-', false) || []; + let onlyPositive = filterPatterns(pos, neg, '', false) || []; + let intersected = filterPatterns(neg, pos, '-?', true) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + + let stop = countNines(min, nines); + let stops = new Set([max]); + + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops = [...stops]; + stops.sort(compare); + return stops; +} + +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return { pattern: start, count: [], digits: 0 }; + } + + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ''; + let count = 0; + + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + + if (startDigit === stopDigit) { + pattern += startDigit; + + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit); + + } else { + count++; + } + } + + if (count) { + pattern += options.shorthand === true ? '\\d' : '[0-9]'; + } + + return { pattern, count: [count], digits }; +} + +function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(max, tok, options); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + + for (let ele of arr) { + let { string } = ele; + + // only push if _both_ are negative... + if (!intersection && !contains(comparison, 'string', string)) { + result.push(prefix + string); + } + + // or _both_ are positive + if (intersection && contains(comparison, 'string', string)) { + result.push(prefix + string); + } + } + return result; +} + +/** + * Zip strings + */ + +function zip(a, b) { + let arr = []; + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + return arr; +} + +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function contains(arr, key, val) { + return arr.some(ele => ele[key] === val); +} + +function countNines(min, len) { + return Number(String(min).slice(0, -len) + '9'.repeat(len)); +} + +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} + +function toQuantifier(digits) { + let [start = 0, stop = ''] = digits; + if (stop || start > 1) { + return `{${start + (stop ? ',' + stop : '')}}`; + } + return ''; +} + +function toCharacterClass(a, b, options) { + return `[${a}${(b - a === 1) ? '' : '-'}${b}]`; +} + +function hasPadding(str) { + return /^-?(0+)\d/.test(str); +} + +function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + + switch (diff) { + case 0: + return ''; + case 1: + return relax ? '0?' : '0'; + case 2: + return relax ? '0{0,2}' : '00'; + default: { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } +} + +/** + * Cache + */ + +toRegexRange$1.cache = {}; +toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {}); + +/** + * Expose `toRegexRange` + */ + +var toRegexRange_1 = toRegexRange$1; + +/*! + * fill-range + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Licensed under the MIT License. + */ + +const util$1 = require$$0$6; +const toRegexRange = toRegexRange_1; + +const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); + +const transform = toNumber => { + return value => toNumber === true ? Number(value) : String(value); +}; + +const isValidValue = value => { + return typeof value === 'number' || (typeof value === 'string' && value !== ''); +}; + +const isNumber = num => Number.isInteger(+num); + +const zeros = input => { + let value = `${input}`; + let index = -1; + if (value[0] === '-') value = value.slice(1); + if (value === '0') return false; + while (value[++index] === '0'); + return index > 0; +}; + +const stringify$6 = (start, end, options) => { + if (typeof start === 'string' || typeof end === 'string') { + return true; + } + return options.stringify === true; +}; + +const pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === '-' ? '-' : ''; + if (dash) input = input.slice(1); + input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0')); + } + if (toNumber === false) { + return String(input); + } + return input; +}; + +const toMaxLen = (input, maxLength) => { + let negative = input[0] === '-' ? '-' : ''; + if (negative) { + input = input.slice(1); + maxLength--; + } + while (input.length < maxLength) input = '0' + input; + return negative ? ('-' + input) : input; +}; + +const toSequence = (parts, options) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + + let prefix = options.capture ? '' : '?:'; + let positives = ''; + let negatives = ''; + let result; + + if (parts.positives.length) { + positives = parts.positives.join('|'); + } + + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.join('|')})`; + } + + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } + + if (options.wrap) { + return `(${prefix}${result})`; + } + + return result; +}; + +const toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange(a, b, { wrap: false, ...options }); + } + + let start = String.fromCharCode(a); + if (a === b) return start; + + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; +}; + +const toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? '' : '?:'; + return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + } + return toRegexRange(start, end, options); +}; + +const rangeError = (...args) => { + return new RangeError('Invalid range arguments: ' + util$1.inspect(...args)); +}; + +const invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; +}; + +const invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + return []; +}; + +const fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); + + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } + + // fix negative zero + if (a === 0) a = 0; + if (b === 0) b = 0; + + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); + + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify$6(start, end, options) === false; + let format = options.transform || transform(toNumber); + + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } + + let parts = { negatives: [], positives: [] }; + let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return step > 1 + ? toSequence(parts, options) + : toRegex(range, null, { wrap: false, ...options }); + } + + return range; +}; + +const fillLetters = (start, end, step = 1, options = {}) => { + if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) { + return invalidRange(start, end, options); + } + + + let format = options.transform || (val => String.fromCharCode(val)); + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); + + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } + + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return toRegex(range, null, { wrap: false, options }); + } + + return range; +}; + +const fill$2 = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } + + if (!isValidValue(start) || !isValidValue(end)) { + return invalidRange(start, end, options); + } + + if (typeof step === 'function') { + return fill$2(start, end, 1, { transform: step }); + } + + if (isObject(step)) { + return fill$2(start, end, 0, step); + } + + let opts = { ...options }; + if (opts.capture === true) opts.wrap = true; + step = step || opts.step || 1; + + if (!isNumber(step)) { + if (step != null && !isObject(step)) return invalidStep(step, opts); + return fill$2(start, end, 1, step); + } + + if (isNumber(start) && isNumber(end)) { + return fillNumbers(start, end, step, opts); + } + + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); +}; + +var fillRange = fill$2; + +const fill$1 = fillRange; +const utils$d = utils$f; + +const compile$1 = (ast, options = {}) => { + let walk = (node, parent = {}) => { + let invalidBlock = utils$d.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let invalid = invalidBlock === true || invalidNode === true; + let prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; + + if (node.isOpen === true) { + return prefix + node.value; + } + if (node.isClose === true) { + return prefix + node.value; + } + + if (node.type === 'open') { + return invalid ? (prefix + node.value) : '('; + } + + if (node.type === 'close') { + return invalid ? (prefix + node.value) : ')'; + } + + if (node.type === 'comma') { + return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); + } + + if (node.value) { + return node.value; + } + + if (node.nodes && node.ranges > 0) { + let args = utils$d.reduce(node.nodes); + let range = fill$1(...args, { ...options, wrap: false, toRegex: true }); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + + if (node.nodes) { + for (let child of node.nodes) { + output += walk(child, node); + } + } + return output; + }; + + return walk(ast); +}; + +var compile_1 = compile$1; + +const fill = fillRange; +const stringify$5 = stringify$7; +const utils$c = utils$f; + +const append$1 = (queue = '', stash = '', enclose = false) => { + let result = []; + + queue = [].concat(queue); + stash = [].concat(stash); + + if (!stash.length) return queue; + if (!queue.length) { + return enclose ? utils$c.flatten(stash).map(ele => `{${ele}}`) : stash; + } + + for (let item of queue) { + if (Array.isArray(item)) { + for (let value of item) { + result.push(append$1(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append$1(item, ele, enclose) : (item + ele)); + } + } + } + return utils$c.flatten(result); +}; + +const expand$2 = (ast, options = {}) => { + let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; + + let walk = (node, parent = {}) => { + node.queue = []; + + let p = parent; + let q = parent.queue; + + while (p.type !== 'brace' && p.type !== 'root' && p.parent) { + p = p.parent; + q = p.queue; + } + + if (node.invalid || node.dollar) { + q.push(append$1(q.pop(), stringify$5(node, options))); + return; + } + + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append$1(q.pop(), ['{}'])); + return; + } + + if (node.nodes && node.ranges > 0) { + let args = utils$c.reduce(node.nodes); + + if (utils$c.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + + let range = fill(...args, options); + if (range.length === 0) { + range = stringify$5(node, options); + } + + q.push(append$1(q.pop(), range)); + node.nodes = []; + return; + } + + let enclose = utils$c.encloseBrace(node); + let queue = node.queue; + let block = node; + + while (block.type !== 'brace' && block.type !== 'root' && block.parent) { + block = block.parent; + queue = block.queue; + } + + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i]; + + if (child.type === 'comma' && node.type === 'brace') { + if (i === 1) queue.push(''); + queue.push(''); + continue; + } + + if (child.type === 'close') { + q.push(append$1(q.pop(), queue, enclose)); + continue; + } + + if (child.value && child.type !== 'open') { + queue.push(append$1(queue.pop(), child.value)); + continue; + } + + if (child.nodes) { + walk(child, node); + } + } + + return queue; + }; + + return utils$c.flatten(walk(ast)); +}; + +var expand_1$1 = expand$2; + +var constants$3 = { + MAX_LENGTH: 1024 * 64, + + // Digits + CHAR_0: '0', /* 0 */ + CHAR_9: '9', /* 9 */ + + // Alphabet chars. + CHAR_UPPERCASE_A: 'A', /* A */ + CHAR_LOWERCASE_A: 'a', /* a */ + CHAR_UPPERCASE_Z: 'Z', /* Z */ + CHAR_LOWERCASE_Z: 'z', /* z */ + + CHAR_LEFT_PARENTHESES: '(', /* ( */ + CHAR_RIGHT_PARENTHESES: ')', /* ) */ + + CHAR_ASTERISK: '*', /* * */ + + // Non-alphabetic chars. + CHAR_AMPERSAND: '&', /* & */ + CHAR_AT: '@', /* @ */ + CHAR_BACKSLASH: '\\', /* \ */ + CHAR_BACKTICK: '`', /* ` */ + CHAR_CARRIAGE_RETURN: '\r', /* \r */ + CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */ + CHAR_COLON: ':', /* : */ + CHAR_COMMA: ',', /* , */ + CHAR_DOLLAR: '$', /* . */ + CHAR_DOT: '.', /* . */ + CHAR_DOUBLE_QUOTE: '"', /* " */ + CHAR_EQUAL: '=', /* = */ + CHAR_EXCLAMATION_MARK: '!', /* ! */ + CHAR_FORM_FEED: '\f', /* \f */ + CHAR_FORWARD_SLASH: '/', /* / */ + CHAR_HASH: '#', /* # */ + CHAR_HYPHEN_MINUS: '-', /* - */ + CHAR_LEFT_ANGLE_BRACKET: '<', /* < */ + CHAR_LEFT_CURLY_BRACE: '{', /* { */ + CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */ + CHAR_LINE_FEED: '\n', /* \n */ + CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */ + CHAR_PERCENT: '%', /* % */ + CHAR_PLUS: '+', /* + */ + CHAR_QUESTION_MARK: '?', /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */ + CHAR_RIGHT_CURLY_BRACE: '}', /* } */ + CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */ + CHAR_SEMICOLON: ';', /* ; */ + CHAR_SINGLE_QUOTE: '\'', /* ' */ + CHAR_SPACE: ' ', /* */ + CHAR_TAB: '\t', /* \t */ + CHAR_UNDERSCORE: '_', /* _ */ + CHAR_VERTICAL_LINE: '|', /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */ +}; + +const stringify$4 = stringify$7; + +/** + * Constants + */ + +const { + MAX_LENGTH, + CHAR_BACKSLASH, /* \ */ + CHAR_BACKTICK, /* ` */ + CHAR_COMMA, /* , */ + CHAR_DOT, /* . */ + CHAR_LEFT_PARENTHESES, /* ( */ + CHAR_RIGHT_PARENTHESES, /* ) */ + CHAR_LEFT_CURLY_BRACE, /* { */ + CHAR_RIGHT_CURLY_BRACE, /* } */ + CHAR_LEFT_SQUARE_BRACKET, /* [ */ + CHAR_RIGHT_SQUARE_BRACKET, /* ] */ + CHAR_DOUBLE_QUOTE, /* " */ + CHAR_SINGLE_QUOTE, /* ' */ + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE +} = constants$3; + +/** + * parse + */ + +const parse$d = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + let opts = options || {}; + let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + + let ast = { type: 'root', input, nodes: [] }; + let stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + let length = input.length; + let index = 0; + let depth = 0; + let value; + + /** + * Helpers + */ + + const advance = () => input[index++]; + const push = node => { + if (node.type === 'text' && prev.type === 'dot') { + prev.type = 'text'; + } + + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + + push({ type: 'bos' }); + + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + + /** + * Invalid chars + */ + + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; + } + + /** + * Escaped chars + */ + + if (value === CHAR_BACKSLASH) { + push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() }); + continue; + } + + /** + * Right square bracket (literal): ']' + */ + + if (value === CHAR_RIGHT_SQUARE_BRACKET) { + push({ type: 'text', value: '\\' + value }); + continue; + } + + /** + * Left square bracket: '[' + */ + + if (value === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + let next; + + while (index < length && (next = advance())) { + value += next; + + if (next === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + continue; + } + + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + brackets--; + + if (brackets === 0) { + break; + } + } + } + + push({ type: 'text', value }); + continue; + } + + /** + * Parentheses + */ + + if (value === CHAR_LEFT_PARENTHESES) { + block = push({ type: 'paren', nodes: [] }); + stack.push(block); + push({ type: 'text', value }); + continue; + } + + if (value === CHAR_RIGHT_PARENTHESES) { + if (block.type !== 'paren') { + push({ type: 'text', value }); + continue; + } + block = stack.pop(); + push({ type: 'text', value }); + block = stack[stack.length - 1]; + continue; + } + + /** + * Quotes: '|"|` + */ + + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + let open = value; + let next; + + if (options.keepQuotes !== true) { + value = ''; + } + + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + + value += next; + } + + push({ type: 'text', value }); + continue; + } + + /** + * Left curly brace: '{' + */ + + if (value === CHAR_LEFT_CURLY_BRACE) { + depth++; + + let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + let brace = { + type: 'brace', + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + + block = push(brace); + stack.push(block); + push({ type: 'open', value }); + continue; + } + + /** + * Right curly brace: '}' + */ + + if (value === CHAR_RIGHT_CURLY_BRACE) { + if (block.type !== 'brace') { + push({ type: 'text', value }); + continue; + } + + let type = 'close'; + block = stack.pop(); + block.close = true; + + push({ type, value }); + depth--; + + block = stack[stack.length - 1]; + continue; + } + + /** + * Comma: ',' + */ + + if (value === CHAR_COMMA && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + let open = block.nodes.shift(); + block.nodes = [open, { type: 'text', value: stringify$4(block) }]; + } + + push({ type: 'comma', value }); + block.commas++; + continue; + } + + /** + * Dot: '.' + */ + + if (value === CHAR_DOT && depth > 0 && block.commas === 0) { + let siblings = block.nodes; + + if (depth === 0 || siblings.length === 0) { + push({ type: 'text', value }); + continue; + } + + if (prev.type === 'dot') { + block.range = []; + prev.value += value; + prev.type = 'range'; + + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = 'text'; + continue; + } + + block.ranges++; + block.args = []; + continue; + } + + if (prev.type === 'range') { + siblings.pop(); + + let before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + + push({ type: 'dot', value }); + continue; + } + + /** + * Text + */ + + push({ type: 'text', value }); + } + + // Mark imbalanced braces and brackets as invalid + do { + block = stack.pop(); + + if (block.type !== 'root') { + block.nodes.forEach(node => { + if (!node.nodes) { + if (node.type === 'open') node.isOpen = true; + if (node.type === 'close') node.isClose = true; + if (!node.nodes) node.type = 'text'; + node.invalid = true; + } + }); + + // get the location of the block on parent.nodes (block's siblings) + let parent = stack[stack.length - 1]; + let index = parent.nodes.indexOf(block); + // replace the (invalid) block with it's nodes + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + + push({ type: 'eos' }); + return ast; +}; + +var parse_1$2 = parse$d; + +const stringify$3 = stringify$7; +const compile = compile_1; +const expand$1 = expand_1$1; +const parse$c = parse_1$2; + +/** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +const braces$2 = (input, options = {}) => { + let output = []; + + if (Array.isArray(input)) { + for (let pattern of input) { + let result = braces$2.create(pattern, options); + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces$2.create(input, options)); + } + + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + return output; +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * // braces.parse(pattern, [, options]); + * const ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * ``` + * @param {String} pattern Brace pattern to parse + * @param {Object} options + * @return {Object} Returns an AST + * @api public + */ + +braces$2.parse = (input, options = {}) => parse$c(input, options); + +/** + * Creates a braces string from an AST, or an AST node. + * + * ```js + * const braces = require('braces'); + * let ast = braces.parse('foo/{a,b}/bar'); + * console.log(stringify(ast.nodes[2])); //=> '{a,b}' + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces$2.stringify = (input, options = {}) => { + if (typeof input === 'string') { + return stringify$3(braces$2.parse(input, options), options); + } + return stringify$3(input, options); +}; + +/** + * Compiles a brace pattern into a regex-compatible, optimized string. + * This method is called by the main [braces](#braces) function by default. + * + * ```js + * const braces = require('braces'); + * console.log(braces.compile('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces$2.compile = (input, options = {}) => { + if (typeof input === 'string') { + input = braces$2.parse(input, options); + } + return compile(input, options); +}; + +/** + * Expands a brace pattern into an array. This method is called by the + * main [braces](#braces) function when `options.expand` is true. Before + * using this method it's recommended that you read the [performance notes](#performance)) + * and advantages of using [.compile](#compile) instead. + * + * ```js + * const braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces$2.expand = (input, options = {}) => { + if (typeof input === 'string') { + input = braces$2.parse(input, options); + } + + let result = expand$1(input, options); + + // filter out empty strings if specified + if (options.noempty === true) { + result = result.filter(Boolean); + } + + // filter out duplicates if specified + if (options.nodupes === true) { + result = [...new Set(result)]; + } + + return result; +}; + +/** + * Processes a brace pattern and returns either an expanded array + * (if `options.expand` is true), a highly optimized regex-compatible string. + * This method is called by the main [braces](#braces) function. + * + * ```js + * const braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces$2.create = (input, options = {}) => { + if (input === '' || input.length < 3) { + return [input]; + } + + return options.expand !== true + ? braces$2.compile(input, options) + : braces$2.expand(input, options); +}; + +/** + * Expose "braces" + */ + +var braces_1 = braces$2; + +const util = require$$0$6; +const braces$1 = braces_1; +const picomatch$2 = picomatch$3; +const utils$b = utils$k; +const isEmptyString = val => val === '' || val === './'; + +/** + * Returns an array of strings that match one or more glob patterns. + * + * ```js + * const mm = require('micromatch'); + * // mm(list, patterns[, options]); + * + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {String|Array} `list` List of strings to match. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ + +const micromatch$1 = (list, patterns, options) => { + patterns = [].concat(patterns); + list = [].concat(list); + + let omit = new Set(); + let keep = new Set(); + let items = new Set(); + let negatives = 0; + + let onResult = state => { + items.add(state.output); + if (options && options.onResult) { + options.onResult(state); + } + }; + + for (let i = 0; i < patterns.length; i++) { + let isMatch = picomatch$2(String(patterns[i]), { ...options, onResult }, true); + let negated = isMatch.state.negated || isMatch.state.negatedExtglob; + if (negated) negatives++; + + for (let item of list) { + let matched = isMatch(item, true); + + let match = negated ? !matched.isMatch : matched.isMatch; + if (!match) continue; + + if (negated) { + omit.add(matched.output); + } else { + omit.delete(matched.output); + keep.add(matched.output); + } + } + } + + let result = negatives === patterns.length ? [...items] : [...keep]; + let matches = result.filter(item => !omit.has(item)); + + if (options && matches.length === 0) { + if (options.failglob === true) { + throw new Error(`No matches found for "${patterns.join(', ')}"`); + } + + if (options.nonull === true || options.nullglob === true) { + return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; + } + } + + return matches; +}; + +/** + * Backwards compatibility + */ + +micromatch$1.match = micromatch$1; + +/** + * Returns a matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * const mm = require('micromatch'); + * // mm.matcher(pattern[, options]); + * + * const isMatch = mm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` + * @return {Function} Returns a matcher function. + * @api public + */ + +micromatch$1.matcher = (pattern, options) => picomatch$2(pattern, options); + +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const mm = require('micromatch'); + * // mm.isMatch(string, patterns[, options]); + * + * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(mm.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `[options]` See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch$1.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str); + +/** + * Backwards compatibility + */ + +micromatch$1.any = micromatch$1.isMatch; + +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.not(list, patterns[, options]); + * + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ + +micromatch$1.not = (list, patterns, options = {}) => { + patterns = [].concat(patterns).map(String); + let result = new Set(); + let items = []; + + let onResult = state => { + if (options.onResult) options.onResult(state); + items.push(state.output); + }; + + let matches = new Set(micromatch$1(list, patterns, { ...options, onResult })); + + for (let item of items) { + if (!matches.has(item)) { + result.add(item); + } + } + return [...result]; +}; + +/** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var mm = require('micromatch'); + * // mm.contains(string, pattern[, options]); + * + * console.log(mm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(mm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any of the patterns matches any part of `str`. + * @api public + */ + +micromatch$1.contains = (str, pattern, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + } + + if (Array.isArray(pattern)) { + return pattern.some(p => micromatch$1.contains(str, p, options)); + } + + if (typeof pattern === 'string') { + if (isEmptyString(str) || isEmptyString(pattern)) { + return false; + } + + if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) { + return true; + } + } + + return micromatch$1.isMatch(str, pattern, { ...options, contains: true }); +}; + +/** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * const mm = require('micromatch'); + * // mm.matchKeys(object, patterns[, options]); + * + * const obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(mm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ + +micromatch$1.matchKeys = (obj, patterns, options) => { + if (!utils$b.isObject(obj)) { + throw new TypeError('Expected the first argument to be an object'); + } + let keys = micromatch$1(Object.keys(obj), patterns, options); + let res = {}; + for (let key of keys) res[key] = obj[key]; + return res; +}; + +/** + * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.some(list, patterns[, options]); + * + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any `patterns` matches any of the strings in `list` + * @api public + */ + +micromatch$1.some = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch$2(String(pattern), options); + if (items.some(item => isMatch(item))) { + return true; + } + } + return false; +}; + +/** + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.every(list, patterns[, options]); + * + * console.log(mm.every('foo.js', ['foo.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if all `patterns` matches all of the strings in `list` + * @api public + */ + +micromatch$1.every = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch$2(String(pattern), options); + if (!items.every(item => isMatch(item))) { + return false; + } + } + return true; +}; + +/** + * Returns true if **all** of the given `patterns` match + * the specified string. + * + * ```js + * const mm = require('micromatch'); + * // mm.all(string, patterns[, options]); + * + * console.log(mm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch$1.all = (str, patterns, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util.inspect(str)}"`); + } + + return [].concat(patterns).every(p => picomatch$2(p, options)(str)); +}; + +/** + * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * + * ```js + * const mm = require('micromatch'); + * // mm.capture(pattern, string[, options]); + * + * console.log(mm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `glob` Glob pattern to use for matching. + * @param {String} `input` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array|null} Returns an array of captures if the input matches the glob pattern, otherwise `null`. + * @api public + */ + +micromatch$1.capture = (glob, input, options) => { + let posix = utils$b.isWindows(options); + let regex = picomatch$2.makeRe(String(glob), { ...options, capture: true }); + let match = regex.exec(posix ? utils$b.toPosixSlashes(input) : input); + + if (match) { + return match.slice(1).map(v => v === void 0 ? '' : v); + } +}; + +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * const mm = require('micromatch'); + * // mm.makeRe(pattern[, options]); + * + * console.log(mm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +micromatch$1.makeRe = (...args) => picomatch$2.makeRe(...args); + +/** + * Scan a glob pattern to separate the pattern into segments. Used + * by the [split](#split) method. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.scan(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + +micromatch$1.scan = (...args) => picomatch$2.scan(...args); + +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.parse(pattern[, options]); + * ``` + * @param {String} `glob` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as regex source string. + * @api public + */ + +micromatch$1.parse = (patterns, options) => { + let res = []; + for (let pattern of [].concat(patterns || [])) { + for (let str of braces$1(String(pattern), options)) { + res.push(picomatch$2.parse(str, options)); + } + } + return res; +}; + +/** + * Process the given brace `pattern`. + * + * ```js + * const { braces } = require('micromatch'); + * console.log(braces('foo/{a,b,c}/bar')); + * //=> [ 'foo/(a|b|c)/bar' ] + * + * console.log(braces('foo/{a,b,c}/bar', { expand: true })); + * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] + * ``` + * @param {String} `pattern` String with brace pattern to process. + * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. + * @return {Array} + * @api public + */ + +micromatch$1.braces = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { + return [pattern]; + } + return braces$1(pattern, options); +}; + +/** + * Expand braces + */ + +micromatch$1.braceExpand = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + return micromatch$1.braces(pattern, { ...options, expand: true }); +}; + +/** + * Expose micromatch + */ + +var micromatch_1 = micromatch$1; + +var micromatch$2 = /*@__PURE__*/getDefaultExportFromCjs(micromatch_1); + +Object.defineProperty(pattern$1, "__esModule", { value: true }); +pattern$1.removeDuplicateSlashes = pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0; +const path$f = require$$0$4; +const globParent$1 = globParent$2; +const micromatch = micromatch_1; +const GLOBSTAR$1 = '**'; +const ESCAPE_SYMBOL = '\\'; +const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; +const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; +const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; +const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; +const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; +/** + * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. + * The latter is due to the presence of the device path at the beginning of the UNC path. + */ +const DOUBLE_SLASH_RE$1 = /(?!^)\/{2,}/g; +function isStaticPattern(pattern, options = {}) { + return !isDynamicPattern(pattern, options); +} +pattern$1.isStaticPattern = isStaticPattern; +function isDynamicPattern(pattern, options = {}) { + /** + * A special case with an empty string is necessary for matching patterns that start with a forward slash. + * An empty string cannot be a dynamic pattern. + * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. + */ + if (pattern === '') { + return false; + } + /** + * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check + * filepath directly (without read directory). + */ + if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { + return true; + } + if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { + return true; + } + if (options.braceExpansion !== false && hasBraceExpansion(pattern)) { + return true; + } + return false; +} +pattern$1.isDynamicPattern = isDynamicPattern; +function hasBraceExpansion(pattern) { + const openingBraceIndex = pattern.indexOf('{'); + if (openingBraceIndex === -1) { + return false; + } + const closingBraceIndex = pattern.indexOf('}', openingBraceIndex + 1); + if (closingBraceIndex === -1) { + return false; + } + const braceContent = pattern.slice(openingBraceIndex, closingBraceIndex); + return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent); +} +function convertToPositivePattern(pattern) { + return isNegativePattern(pattern) ? pattern.slice(1) : pattern; +} +pattern$1.convertToPositivePattern = convertToPositivePattern; +function convertToNegativePattern(pattern) { + return '!' + pattern; +} +pattern$1.convertToNegativePattern = convertToNegativePattern; +function isNegativePattern(pattern) { + return pattern.startsWith('!') && pattern[1] !== '('; +} +pattern$1.isNegativePattern = isNegativePattern; +function isPositivePattern(pattern) { + return !isNegativePattern(pattern); +} +pattern$1.isPositivePattern = isPositivePattern; +function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); +} +pattern$1.getNegativePatterns = getNegativePatterns; +function getPositivePatterns$1(patterns) { + return patterns.filter(isPositivePattern); +} +pattern$1.getPositivePatterns = getPositivePatterns$1; +/** + * Returns patterns that can be applied inside the current directory. + * + * @example + * // ['./*', '*', 'a/*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsInsideCurrentDirectory(patterns) { + return patterns.filter((pattern) => !isPatternRelatedToParentDirectory(pattern)); +} +pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory; +/** + * Returns patterns to be expanded relative to (outside) the current directory. + * + * @example + * // ['../*', './../*'] + * getPatternsInsideCurrentDirectory(['./*', '*', 'a/*', '../*', './../*']) + */ +function getPatternsOutsideCurrentDirectory(patterns) { + return patterns.filter(isPatternRelatedToParentDirectory); +} +pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory; +function isPatternRelatedToParentDirectory(pattern) { + return pattern.startsWith('..') || pattern.startsWith('./..'); +} +pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory; +function getBaseDirectory(pattern) { + return globParent$1(pattern, { flipBackslashes: false }); +} +pattern$1.getBaseDirectory = getBaseDirectory; +function hasGlobStar(pattern) { + return pattern.includes(GLOBSTAR$1); +} +pattern$1.hasGlobStar = hasGlobStar; +function endsWithSlashGlobStar(pattern) { + return pattern.endsWith('/' + GLOBSTAR$1); +} +pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar; +function isAffectDepthOfReadingPattern(pattern) { + const basename = path$f.basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); +} +pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; +function expandPatternsWithBraceExpansion(patterns) { + return patterns.reduce((collection, pattern) => { + return collection.concat(expandBraceExpansion(pattern)); + }, []); +} +pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; +function expandBraceExpansion(pattern) { + const patterns = micromatch.braces(pattern, { expand: true, nodupes: true, keepEscaping: true }); + /** + * Sort the patterns by length so that the same depth patterns are processed side by side. + * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']` + */ + patterns.sort((a, b) => a.length - b.length); + /** + * Micromatch can return an empty string in the case of patterns like `{a,}`. + */ + return patterns.filter((pattern) => pattern !== ''); +} +pattern$1.expandBraceExpansion = expandBraceExpansion; +function getPatternParts(pattern, options) { + let { parts } = micromatch.scan(pattern, Object.assign(Object.assign({}, options), { parts: true })); + /** + * The scan method returns an empty array in some cases. + * See micromatch/picomatch#58 for more details. + */ + if (parts.length === 0) { + parts = [pattern]; + } + /** + * The scan method does not return an empty part for the pattern with a forward slash. + * This is another part of micromatch/picomatch#58. + */ + if (parts[0].startsWith('/')) { + parts[0] = parts[0].slice(1); + parts.unshift(''); + } + return parts; +} +pattern$1.getPatternParts = getPatternParts; +function makeRe(pattern, options) { + return micromatch.makeRe(pattern, options); +} +pattern$1.makeRe = makeRe; +function convertPatternsToRe(patterns, options) { + return patterns.map((pattern) => makeRe(pattern, options)); +} +pattern$1.convertPatternsToRe = convertPatternsToRe; +function matchAny(entry, patternsRe) { + return patternsRe.some((patternRe) => patternRe.test(entry)); +} +pattern$1.matchAny = matchAny; +/** + * This package only works with forward slashes as a path separator. + * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. + */ +function removeDuplicateSlashes(pattern) { + return pattern.replace(DOUBLE_SLASH_RE$1, '/'); +} +pattern$1.removeDuplicateSlashes = removeDuplicateSlashes; + +var stream$4 = {}; + +/* + * merge2 + * https://github.com/teambition/merge2 + * + * Copyright (c) 2014-2020 Teambition + * Licensed under the MIT license. + */ +const Stream = require$$0$7; +const PassThrough = Stream.PassThrough; +const slice = Array.prototype.slice; + +var merge2_1 = merge2$1; + +function merge2$1 () { + const streamsQueue = []; + const args = slice.call(arguments); + let merging = false; + let options = args[args.length - 1]; + + if (options && !Array.isArray(options) && options.pipe == null) { + args.pop(); + } else { + options = {}; + } + + const doEnd = options.end !== false; + const doPipeError = options.pipeError === true; + if (options.objectMode == null) { + options.objectMode = true; + } + if (options.highWaterMark == null) { + options.highWaterMark = 64 * 1024; + } + const mergedStream = PassThrough(options); + + function addStream () { + for (let i = 0, len = arguments.length; i < len; i++) { + streamsQueue.push(pauseStreams(arguments[i], options)); + } + mergeStream(); + return this + } + + function mergeStream () { + if (merging) { + return + } + merging = true; + + let streams = streamsQueue.shift(); + if (!streams) { + process.nextTick(endStream); + return + } + if (!Array.isArray(streams)) { + streams = [streams]; + } + + let pipesCount = streams.length + 1; + + function next () { + if (--pipesCount > 0) { + return + } + merging = false; + mergeStream(); + } + + function pipe (stream) { + function onend () { + stream.removeListener('merge2UnpipeEnd', onend); + stream.removeListener('end', onend); + if (doPipeError) { + stream.removeListener('error', onerror); + } + next(); + } + function onerror (err) { + mergedStream.emit('error', err); + } + // skip ended stream + if (stream._readableState.endEmitted) { + return next() + } + + stream.on('merge2UnpipeEnd', onend); + stream.on('end', onend); + + if (doPipeError) { + stream.on('error', onerror); + } + + stream.pipe(mergedStream, { end: false }); + // compatible for old stream + stream.resume(); + } + + for (let i = 0; i < streams.length; i++) { + pipe(streams[i]); + } + + next(); + } + + function endStream () { + merging = false; + // emit 'queueDrain' when all streams merged. + mergedStream.emit('queueDrain'); + if (doEnd) { + mergedStream.end(); + } + } + + mergedStream.setMaxListeners(0); + mergedStream.add = addStream; + mergedStream.on('unpipe', function (stream) { + stream.emit('merge2UnpipeEnd'); + }); + + if (args.length) { + addStream.apply(null, args); + } + return mergedStream +} + +// check and pause streams for pipe. +function pauseStreams (streams, options) { + if (!Array.isArray(streams)) { + // Backwards-compat with old-style streams + if (!streams._readableState && streams.pipe) { + streams = streams.pipe(PassThrough(options)); + } + if (!streams._readableState || !streams.pause || !streams.pipe) { + throw new Error('Only readable stream can be merged.') + } + streams.pause(); + } else { + for (let i = 0, len = streams.length; i < len; i++) { + streams[i] = pauseStreams(streams[i], options); + } + } + return streams +} + +Object.defineProperty(stream$4, "__esModule", { value: true }); +stream$4.merge = void 0; +const merge2 = merge2_1; +function merge$1(streams) { + const mergedStream = merge2(streams); + streams.forEach((stream) => { + stream.once('error', (error) => mergedStream.emit('error', error)); + }); + mergedStream.once('close', () => propagateCloseEventToSources(streams)); + mergedStream.once('end', () => propagateCloseEventToSources(streams)); + return mergedStream; +} +stream$4.merge = merge$1; +function propagateCloseEventToSources(streams) { + streams.forEach((stream) => stream.emit('close')); +} + +var string$2 = {}; + +Object.defineProperty(string$2, "__esModule", { value: true }); +string$2.isEmpty = string$2.isString = void 0; +function isString(input) { + return typeof input === 'string'; +} +string$2.isString = isString; +function isEmpty$1(input) { + return input === ''; +} +string$2.isEmpty = isEmpty$1; + +Object.defineProperty(utils$g, "__esModule", { value: true }); +utils$g.string = utils$g.stream = utils$g.pattern = utils$g.path = utils$g.fs = utils$g.errno = utils$g.array = void 0; +const array = array$1; +utils$g.array = array; +const errno = errno$1; +utils$g.errno = errno; +const fs$g = fs$h; +utils$g.fs = fs$g; +const path$e = path$h; +utils$g.path = path$e; +const pattern = pattern$1; +utils$g.pattern = pattern; +const stream$3 = stream$4; +utils$g.stream = stream$3; +const string$1 = string$2; +utils$g.string = string$1; + +Object.defineProperty(tasks, "__esModule", { value: true }); +tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0; +const utils$a = utils$g; +function generate(input, settings) { + const patterns = processPatterns(input, settings); + const ignore = processPatterns(settings.ignore, settings); + const positivePatterns = getPositivePatterns(patterns); + const negativePatterns = getNegativePatternsAsPositive(patterns, ignore); + const staticPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isStaticPattern(pattern, settings)); + const dynamicPatterns = positivePatterns.filter((pattern) => utils$a.pattern.isDynamicPattern(pattern, settings)); + const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); + const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, /* dynamic */ true); + return staticTasks.concat(dynamicTasks); +} +tasks.generate = generate; +function processPatterns(input, settings) { + let patterns = input; + /** + * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry + * and some problems with the micromatch package (see fast-glob issues: #365, #394). + * + * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown + * in matching in the case of a large set of patterns after expansion. + */ + if (settings.braceExpansion) { + patterns = utils$a.pattern.expandPatternsWithBraceExpansion(patterns); + } + /** + * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used + * at any nesting level. + * + * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change + * the pattern in the filter before creating a regular expression. There is no need to change the patterns + * in the application. Only on the input. + */ + if (settings.baseNameMatch) { + patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`); + } + /** + * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion. + */ + return patterns.map((pattern) => utils$a.pattern.removeDuplicateSlashes(pattern)); +} +/** + * Returns tasks grouped by basic pattern directories. + * + * Patterns that can be found inside (`./`) and outside (`../`) the current directory are handled separately. + * This is necessary because directory traversal starts at the base directory and goes deeper. + */ +function convertPatternsToTasks(positive, negative, dynamic) { + const tasks = []; + const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive); + const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive); + const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory); + const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory); + tasks.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic)); + /* + * For the sake of reducing future accesses to the file system, we merge all tasks within the current directory + * into a global task, if at least one pattern refers to the root (`.`). In this case, the global task covers the rest. + */ + if ('.' in insideCurrentDirectoryGroup) { + tasks.push(convertPatternGroupToTask('.', patternsInsideCurrentDirectory, negative, dynamic)); + } + else { + tasks.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic)); + } + return tasks; +} +tasks.convertPatternsToTasks = convertPatternsToTasks; +function getPositivePatterns(patterns) { + return utils$a.pattern.getPositivePatterns(patterns); +} +tasks.getPositivePatterns = getPositivePatterns; +function getNegativePatternsAsPositive(patterns, ignore) { + const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore); + const positive = negative.map(utils$a.pattern.convertToPositivePattern); + return positive; +} +tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive; +function groupPatternsByBaseDirectory(patterns) { + const group = {}; + return patterns.reduce((collection, pattern) => { + const base = utils$a.pattern.getBaseDirectory(pattern); + if (base in collection) { + collection[base].push(pattern); + } + else { + collection[base] = [pattern]; + } + return collection; + }, group); +} +tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; +function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map((base) => { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); +} +tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks; +function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + dynamic, + positive, + negative, + base, + patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern)) + }; +} +tasks.convertPatternGroupToTask = convertPatternGroupToTask; + +var async$7 = {}; + +var async$6 = {}; + +var out$3 = {}; + +var async$5 = {}; + +var async$4 = {}; + +var out$2 = {}; + +var async$3 = {}; + +var out$1 = {}; + +var async$2 = {}; + +Object.defineProperty(async$2, "__esModule", { value: true }); +async$2.read = void 0; +function read$3(path, settings, callback) { + settings.fs.lstat(path, (lstatError, lstat) => { + if (lstatError !== null) { + callFailureCallback$2(callback, lstatError); + return; + } + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + callSuccessCallback$2(callback, lstat); + return; + } + settings.fs.stat(path, (statError, stat) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + callFailureCallback$2(callback, statError); + return; + } + callSuccessCallback$2(callback, lstat); + return; + } + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + callSuccessCallback$2(callback, stat); + }); + }); +} +async$2.read = read$3; +function callFailureCallback$2(callback, error) { + callback(error); +} +function callSuccessCallback$2(callback, result) { + callback(null, result); +} + +var sync$8 = {}; + +Object.defineProperty(sync$8, "__esModule", { value: true }); +sync$8.read = void 0; +function read$2(path, settings) { + const lstat = settings.fs.lstatSync(path); + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return lstat; + } + try { + const stat = settings.fs.statSync(path); + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + return stat; + } + catch (error) { + if (!settings.throwErrorOnBrokenSymbolicLink) { + return lstat; + } + throw error; + } +} +sync$8.read = read$2; + +var settings$3 = {}; + +var fs$f = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; + const fs = require$$0__default; + exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync + }; + function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); + } + exports.createFileSystemAdapter = createFileSystemAdapter; +} (fs$f)); + +Object.defineProperty(settings$3, "__esModule", { value: true }); +const fs$e = fs$f; +let Settings$2 = class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); + this.fs = fs$e.createFileSystemAdapter(this._options.fs); + this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +}; +settings$3.default = Settings$2; + +Object.defineProperty(out$1, "__esModule", { value: true }); +out$1.statSync = out$1.stat = out$1.Settings = void 0; +const async$1 = async$2; +const sync$7 = sync$8; +const settings_1$3 = settings$3; +out$1.Settings = settings_1$3.default; +function stat$4(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async$1.read(path, getSettings$2(), optionsOrSettingsOrCallback); + return; + } + async$1.read(path, getSettings$2(optionsOrSettingsOrCallback), callback); +} +out$1.stat = stat$4; +function statSync(path, optionsOrSettings) { + const settings = getSettings$2(optionsOrSettings); + return sync$7.read(path, settings); +} +out$1.statSync = statSync; +function getSettings$2(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1$3.default) { + return settingsOrOptions; + } + return new settings_1$3.default(settingsOrOptions); +} + +/*! queue-microtask. MIT License. Feross Aboukhadijeh */ + +let promise$1; + +var queueMicrotask_1 = typeof queueMicrotask === 'function' + ? queueMicrotask.bind(typeof window !== 'undefined' ? window : commonjsGlobal) + // reuse resolved promise, and allocate it lazily + : cb => (promise$1 || (promise$1 = Promise.resolve())) + .then(cb) + .catch(err => setTimeout(() => { throw err }, 0)); + +/*! run-parallel. MIT License. Feross Aboukhadijeh */ + +var runParallel_1 = runParallel; + +const queueMicrotask$1 = queueMicrotask_1; + +function runParallel (tasks, cb) { + let results, pending, keys; + let isSync = true; + + if (Array.isArray(tasks)) { + results = []; + pending = tasks.length; + } else { + keys = Object.keys(tasks); + results = {}; + pending = keys.length; + } + + function done (err) { + function end () { + if (cb) cb(err, results); + cb = null; + } + if (isSync) queueMicrotask$1(end); + else end(); + } + + function each (i, err, result) { + results[i] = result; + if (--pending === 0 || err) { + done(err); + } + } + + if (!pending) { + // empty + done(null); + } else if (keys) { + // object + keys.forEach(function (key) { + tasks[key](function (err, result) { each(key, err, result); }); + }); + } else { + // array + tasks.forEach(function (task, i) { + task(function (err, result) { each(i, err, result); }); + }); + } + + isSync = false; +} + +var constants$2 = {}; + +Object.defineProperty(constants$2, "__esModule", { value: true }); +constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0; +const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); +if (NODE_PROCESS_VERSION_PARTS[0] === undefined || NODE_PROCESS_VERSION_PARTS[1] === undefined) { + throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`); +} +const MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); +const MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); +const SUPPORTED_MAJOR_VERSION = 10; +const SUPPORTED_MINOR_VERSION = 10; +const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; +const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; +/** + * IS `true` for Node.js 10.10 and greater. + */ +constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; + +var utils$9 = {}; + +var fs$d = {}; + +Object.defineProperty(fs$d, "__esModule", { value: true }); +fs$d.createDirentFromStats = void 0; +class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } +} +function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); +} +fs$d.createDirentFromStats = createDirentFromStats; + +Object.defineProperty(utils$9, "__esModule", { value: true }); +utils$9.fs = void 0; +const fs$c = fs$d; +utils$9.fs = fs$c; + +var common$a = {}; + +Object.defineProperty(common$a, "__esModule", { value: true }); +common$a.joinPathSegments = void 0; +function joinPathSegments$1(a, b, separator) { + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; +} +common$a.joinPathSegments = joinPathSegments$1; + +Object.defineProperty(async$3, "__esModule", { value: true }); +async$3.readdir = async$3.readdirWithFileTypes = async$3.read = void 0; +const fsStat$5 = out$1; +const rpl = runParallel_1; +const constants_1$1 = constants$2; +const utils$8 = utils$9; +const common$9 = common$a; +function read$1(directory, settings, callback) { + if (!settings.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + readdirWithFileTypes$1(directory, settings, callback); + return; + } + readdir$3(directory, settings, callback); +} +async$3.read = read$1; +function readdirWithFileTypes$1(directory, settings, callback) { + settings.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => { + if (readdirError !== null) { + callFailureCallback$1(callback, readdirError); + return; + } + const entries = dirents.map((dirent) => ({ + dirent, + name: dirent.name, + path: common$9.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + })); + if (!settings.followSymbolicLinks) { + callSuccessCallback$1(callback, entries); + return; + } + const tasks = entries.map((entry) => makeRplTaskEntry(entry, settings)); + rpl(tasks, (rplError, rplEntries) => { + if (rplError !== null) { + callFailureCallback$1(callback, rplError); + return; + } + callSuccessCallback$1(callback, rplEntries); + }); + }); +} +async$3.readdirWithFileTypes = readdirWithFileTypes$1; +function makeRplTaskEntry(entry, settings) { + return (done) => { + if (!entry.dirent.isSymbolicLink()) { + done(null, entry); + return; + } + settings.fs.stat(entry.path, (statError, stats) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + done(statError); + return; + } + done(null, entry); + return; + } + entry.dirent = utils$8.fs.createDirentFromStats(entry.name, stats); + done(null, entry); + }); + }; +} +function readdir$3(directory, settings, callback) { + settings.fs.readdir(directory, (readdirError, names) => { + if (readdirError !== null) { + callFailureCallback$1(callback, readdirError); + return; + } + const tasks = names.map((name) => { + const path = common$9.joinPathSegments(directory, name, settings.pathSegmentSeparator); + return (done) => { + fsStat$5.stat(path, settings.fsStatSettings, (error, stats) => { + if (error !== null) { + done(error); + return; + } + const entry = { + name, + path, + dirent: utils$8.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + done(null, entry); + }); + }; + }); + rpl(tasks, (rplError, entries) => { + if (rplError !== null) { + callFailureCallback$1(callback, rplError); + return; + } + callSuccessCallback$1(callback, entries); + }); + }); +} +async$3.readdir = readdir$3; +function callFailureCallback$1(callback, error) { + callback(error); +} +function callSuccessCallback$1(callback, result) { + callback(null, result); +} + +var sync$6 = {}; + +Object.defineProperty(sync$6, "__esModule", { value: true }); +sync$6.readdir = sync$6.readdirWithFileTypes = sync$6.read = void 0; +const fsStat$4 = out$1; +const constants_1 = constants$2; +const utils$7 = utils$9; +const common$8 = common$a; +function read(directory, settings) { + if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings); + } + return readdir$2(directory, settings); +} +sync$6.read = read; +function readdirWithFileTypes(directory, settings) { + const dirents = settings.fs.readdirSync(directory, { withFileTypes: true }); + return dirents.map((dirent) => { + const entry = { + dirent, + name: dirent.name, + path: common$8.joinPathSegments(directory, dirent.name, settings.pathSegmentSeparator) + }; + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { + try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils$7.fs.createDirentFromStats(entry.name, stats); + } + catch (error) { + if (settings.throwErrorOnBrokenSymbolicLink) { + throw error; + } + } + } + return entry; + }); +} +sync$6.readdirWithFileTypes = readdirWithFileTypes; +function readdir$2(directory, settings) { + const names = settings.fs.readdirSync(directory); + return names.map((name) => { + const entryPath = common$8.joinPathSegments(directory, name, settings.pathSegmentSeparator); + const stats = fsStat$4.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils$7.fs.createDirentFromStats(name, stats) + }; + if (settings.stats) { + entry.stats = stats; + } + return entry; + }); +} +sync$6.readdir = readdir$2; + +var settings$2 = {}; + +var fs$b = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; + const fs = require$$0__default; + exports.FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + stat: fs.stat, + lstatSync: fs.lstatSync, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync + }; + function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); + } + exports.createFileSystemAdapter = createFileSystemAdapter; +} (fs$b)); + +Object.defineProperty(settings$2, "__esModule", { value: true }); +const path$d = require$$0$4; +const fsStat$3 = out$1; +const fs$a = fs$b; +let Settings$1 = class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); + this.fs = fs$a.createFileSystemAdapter(this._options.fs); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$d.sep); + this.stats = this._getValue(this._options.stats, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + this.fsStatSettings = new fsStat$3.Settings({ + followSymbolicLink: this.followSymbolicLinks, + fs: this.fs, + throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +}; +settings$2.default = Settings$1; + +Object.defineProperty(out$2, "__esModule", { value: true }); +out$2.Settings = out$2.scandirSync = out$2.scandir = void 0; +const async = async$3; +const sync$5 = sync$6; +const settings_1$2 = settings$2; +out$2.Settings = settings_1$2.default; +function scandir(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + async.read(path, getSettings$1(), optionsOrSettingsOrCallback); + return; + } + async.read(path, getSettings$1(optionsOrSettingsOrCallback), callback); +} +out$2.scandir = scandir; +function scandirSync(path, optionsOrSettings) { + const settings = getSettings$1(optionsOrSettings); + return sync$5.read(path, settings); +} +out$2.scandirSync = scandirSync; +function getSettings$1(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1$2.default) { + return settingsOrOptions; + } + return new settings_1$2.default(settingsOrOptions); +} + +var queue = {exports: {}}; + +function reusify$1 (Constructor) { + var head = new Constructor(); + var tail = head; + + function get () { + var current = head; + + if (current.next) { + head = current.next; + } else { + head = new Constructor(); + tail = head; + } + + current.next = null; + + return current + } + + function release (obj) { + tail.next = obj; + tail = obj; + } + + return { + get: get, + release: release + } +} + +var reusify_1 = reusify$1; + +/* eslint-disable no-var */ + +var reusify = reusify_1; + +function fastqueue (context, worker, concurrency) { + if (typeof context === 'function') { + concurrency = worker; + worker = context; + context = null; + } + + if (concurrency < 1) { + throw new Error('fastqueue concurrency must be greater than 1') + } + + var cache = reusify(Task); + var queueHead = null; + var queueTail = null; + var _running = 0; + var errorHandler = null; + + var self = { + push: push, + drain: noop$4, + saturated: noop$4, + pause: pause, + paused: false, + concurrency: concurrency, + running: running, + resume: resume, + idle: idle, + length: length, + getQueue: getQueue, + unshift: unshift, + empty: noop$4, + kill: kill, + killAndDrain: killAndDrain, + error: error + }; + + return self + + function running () { + return _running + } + + function pause () { + self.paused = true; + } + + function length () { + var current = queueHead; + var counter = 0; + + while (current) { + current = current.next; + counter++; + } + + return counter + } + + function getQueue () { + var current = queueHead; + var tasks = []; + + while (current) { + tasks.push(current.value); + current = current.next; + } + + return tasks + } + + function resume () { + if (!self.paused) return + self.paused = false; + for (var i = 0; i < self.concurrency; i++) { + _running++; + release(); + } + } + + function idle () { + return _running === 0 && self.length() === 0 + } + + function push (value, done) { + var current = cache.get(); + + current.context = context; + current.release = release; + current.value = value; + current.callback = done || noop$4; + current.errorHandler = errorHandler; + + if (_running === self.concurrency || self.paused) { + if (queueTail) { + queueTail.next = current; + queueTail = current; + } else { + queueHead = current; + queueTail = current; + self.saturated(); + } + } else { + _running++; + worker.call(context, current.value, current.worked); + } + } + + function unshift (value, done) { + var current = cache.get(); + + current.context = context; + current.release = release; + current.value = value; + current.callback = done || noop$4; + + if (_running === self.concurrency || self.paused) { + if (queueHead) { + current.next = queueHead; + queueHead = current; + } else { + queueHead = current; + queueTail = current; + self.saturated(); + } + } else { + _running++; + worker.call(context, current.value, current.worked); + } + } + + function release (holder) { + if (holder) { + cache.release(holder); + } + var next = queueHead; + if (next) { + if (!self.paused) { + if (queueTail === queueHead) { + queueTail = null; + } + queueHead = next.next; + next.next = null; + worker.call(context, next.value, next.worked); + if (queueTail === null) { + self.empty(); + } + } else { + _running--; + } + } else if (--_running === 0) { + self.drain(); + } + } + + function kill () { + queueHead = null; + queueTail = null; + self.drain = noop$4; + } + + function killAndDrain () { + queueHead = null; + queueTail = null; + self.drain(); + self.drain = noop$4; + } + + function error (handler) { + errorHandler = handler; + } +} + +function noop$4 () {} + +function Task () { + this.value = null; + this.callback = noop$4; + this.next = null; + this.release = noop$4; + this.context = null; + this.errorHandler = null; + + var self = this; + + this.worked = function worked (err, result) { + var callback = self.callback; + var errorHandler = self.errorHandler; + var val = self.value; + self.value = null; + self.callback = noop$4; + if (self.errorHandler) { + errorHandler(err, val); + } + callback.call(self.context, err, result); + self.release(self); + }; +} + +function queueAsPromised (context, worker, concurrency) { + if (typeof context === 'function') { + concurrency = worker; + worker = context; + context = null; + } + + function asyncWrapper (arg, cb) { + worker.call(this, arg) + .then(function (res) { + cb(null, res); + }, cb); + } + + var queue = fastqueue(context, asyncWrapper, concurrency); + + var pushCb = queue.push; + var unshiftCb = queue.unshift; + + queue.push = push; + queue.unshift = unshift; + queue.drained = drained; + + return queue + + function push (value) { + var p = new Promise(function (resolve, reject) { + pushCb(value, function (err, result) { + if (err) { + reject(err); + return + } + resolve(result); + }); + }); + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop$4); + + return p + } + + function unshift (value) { + var p = new Promise(function (resolve, reject) { + unshiftCb(value, function (err, result) { + if (err) { + reject(err); + return + } + resolve(result); + }); + }); + + // Let's fork the promise chain to + // make the error bubble up to the user but + // not lead to a unhandledRejection + p.catch(noop$4); + + return p + } + + function drained () { + var previousDrain = queue.drain; + + var p = new Promise(function (resolve) { + queue.drain = function () { + previousDrain(); + resolve(); + }; + }); + + return p + } +} + +queue.exports = fastqueue; +queue.exports.promise = queueAsPromised; + +var queueExports = queue.exports; + +var common$7 = {}; + +Object.defineProperty(common$7, "__esModule", { value: true }); +common$7.joinPathSegments = common$7.replacePathSegmentSeparator = common$7.isAppliedFilter = common$7.isFatalError = void 0; +function isFatalError(settings, error) { + if (settings.errorFilter === null) { + return true; + } + return !settings.errorFilter(error); +} +common$7.isFatalError = isFatalError; +function isAppliedFilter(filter, value) { + return filter === null || filter(value); +} +common$7.isAppliedFilter = isAppliedFilter; +function replacePathSegmentSeparator(filepath, separator) { + return filepath.split(/[/\\]/).join(separator); +} +common$7.replacePathSegmentSeparator = replacePathSegmentSeparator; +function joinPathSegments(a, b, separator) { + if (a === '') { + return b; + } + /** + * The correct handling of cases when the first segment is a root (`/`, `C:/`) or UNC path (`//?/C:/`). + */ + if (a.endsWith(separator)) { + return a + b; + } + return a + separator + b; +} +common$7.joinPathSegments = joinPathSegments; + +var reader$1 = {}; + +Object.defineProperty(reader$1, "__esModule", { value: true }); +const common$6 = common$7; +let Reader$1 = class Reader { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._root = common$6.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + } +}; +reader$1.default = Reader$1; + +Object.defineProperty(async$4, "__esModule", { value: true }); +const events_1 = require$$0$5; +const fsScandir$2 = out$2; +const fastq = queueExports; +const common$5 = common$7; +const reader_1$4 = reader$1; +class AsyncReader extends reader_1$4.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = fsScandir$2.scandir; + this._emitter = new events_1.EventEmitter(); + this._queue = fastq(this._worker.bind(this), this._settings.concurrency); + this._isFatalError = false; + this._isDestroyed = false; + this._queue.drain = () => { + if (!this._isFatalError) { + this._emitter.emit('end'); + } + }; + } + read() { + this._isFatalError = false; + this._isDestroyed = false; + setImmediate(() => { + this._pushToQueue(this._root, this._settings.basePath); + }); + return this._emitter; + } + get isDestroyed() { + return this._isDestroyed; + } + destroy() { + if (this._isDestroyed) { + throw new Error('The reader is already destroyed'); + } + this._isDestroyed = true; + this._queue.killAndDrain(); + } + onEntry(callback) { + this._emitter.on('entry', callback); + } + onError(callback) { + this._emitter.once('error', callback); + } + onEnd(callback) { + this._emitter.once('end', callback); + } + _pushToQueue(directory, base) { + const queueItem = { directory, base }; + this._queue.push(queueItem, (error) => { + if (error !== null) { + this._handleError(error); + } + }); + } + _worker(item, done) { + this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { + if (error !== null) { + done(error, undefined); + return; + } + for (const entry of entries) { + this._handleEntry(entry, item.base); + } + done(null, undefined); + }); + } + _handleError(error) { + if (this._isDestroyed || !common$5.isFatalError(this._settings, error)) { + return; + } + this._isFatalError = true; + this._isDestroyed = true; + this._emitter.emit('error', error); + } + _handleEntry(entry, base) { + if (this._isDestroyed || this._isFatalError) { + return; + } + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common$5.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common$5.isAppliedFilter(this._settings.entryFilter, entry)) { + this._emitEntry(entry); + } + if (entry.dirent.isDirectory() && common$5.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _emitEntry(entry) { + this._emitter.emit('entry', entry); + } +} +async$4.default = AsyncReader; + +Object.defineProperty(async$5, "__esModule", { value: true }); +const async_1$4 = async$4; +class AsyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1$4.default(this._root, this._settings); + this._storage = []; + } + read(callback) { + this._reader.onError((error) => { + callFailureCallback(callback, error); + }); + this._reader.onEntry((entry) => { + this._storage.push(entry); + }); + this._reader.onEnd(() => { + callSuccessCallback(callback, this._storage); + }); + this._reader.read(); + } +} +async$5.default = AsyncProvider; +function callFailureCallback(callback, error) { + callback(error); +} +function callSuccessCallback(callback, entries) { + callback(null, entries); +} + +var stream$2 = {}; + +Object.defineProperty(stream$2, "__esModule", { value: true }); +const stream_1$5 = require$$0$7; +const async_1$3 = async$4; +class StreamProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async_1$3.default(this._root, this._settings); + this._stream = new stream_1$5.Readable({ + objectMode: true, + read: () => { }, + destroy: () => { + if (!this._reader.isDestroyed) { + this._reader.destroy(); + } + } + }); + } + read() { + this._reader.onError((error) => { + this._stream.emit('error', error); + }); + this._reader.onEntry((entry) => { + this._stream.push(entry); + }); + this._reader.onEnd(() => { + this._stream.push(null); + }); + this._reader.read(); + return this._stream; + } +} +stream$2.default = StreamProvider; + +var sync$4 = {}; + +var sync$3 = {}; + +Object.defineProperty(sync$3, "__esModule", { value: true }); +const fsScandir$1 = out$2; +const common$4 = common$7; +const reader_1$3 = reader$1; +class SyncReader extends reader_1$3.default { + constructor() { + super(...arguments); + this._scandir = fsScandir$1.scandirSync; + this._storage = []; + this._queue = new Set(); + } + read() { + this._pushToQueue(this._root, this._settings.basePath); + this._handleQueue(); + return this._storage; + } + _pushToQueue(directory, base) { + this._queue.add({ directory, base }); + } + _handleQueue() { + for (const item of this._queue.values()) { + this._handleDirectory(item.directory, item.base); + } + } + _handleDirectory(directory, base) { + try { + const entries = this._scandir(directory, this._settings.fsScandirSettings); + for (const entry of entries) { + this._handleEntry(entry, base); + } + } + catch (error) { + this._handleError(error); + } + } + _handleError(error) { + if (!common$4.isFatalError(this._settings, error)) { + return; + } + throw error; + } + _handleEntry(entry, base) { + const fullpath = entry.path; + if (base !== undefined) { + entry.path = common$4.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + if (common$4.isAppliedFilter(this._settings.entryFilter, entry)) { + this._pushToStorage(entry); + } + if (entry.dirent.isDirectory() && common$4.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, base === undefined ? undefined : entry.path); + } + } + _pushToStorage(entry) { + this._storage.push(entry); + } +} +sync$3.default = SyncReader; + +Object.defineProperty(sync$4, "__esModule", { value: true }); +const sync_1$3 = sync$3; +class SyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new sync_1$3.default(this._root, this._settings); + } + read() { + return this._reader.read(); + } +} +sync$4.default = SyncProvider; + +var settings$1 = {}; + +Object.defineProperty(settings$1, "__esModule", { value: true }); +const path$c = require$$0$4; +const fsScandir = out$2; +class Settings { + constructor(_options = {}) { + this._options = _options; + this.basePath = this._getValue(this._options.basePath, undefined); + this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY); + this.deepFilter = this._getValue(this._options.deepFilter, null); + this.entryFilter = this._getValue(this._options.entryFilter, null); + this.errorFilter = this._getValue(this._options.errorFilter, null); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$c.sep); + this.fsScandirSettings = new fsScandir.Settings({ + followSymbolicLinks: this._options.followSymbolicLinks, + fs: this._options.fs, + pathSegmentSeparator: this._options.pathSegmentSeparator, + stats: this._options.stats, + throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink + }); + } + _getValue(option, value) { + return option !== null && option !== void 0 ? option : value; + } +} +settings$1.default = Settings; + +Object.defineProperty(out$3, "__esModule", { value: true }); +out$3.Settings = out$3.walkStream = out$3.walkSync = out$3.walk = void 0; +const async_1$2 = async$5; +const stream_1$4 = stream$2; +const sync_1$2 = sync$4; +const settings_1$1 = settings$1; +out$3.Settings = settings_1$1.default; +function walk$2(directory, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + new async_1$2.default(directory, getSettings()).read(optionsOrSettingsOrCallback); + return; + } + new async_1$2.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); +} +out$3.walk = walk$2; +function walkSync(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new sync_1$2.default(directory, settings); + return provider.read(); +} +out$3.walkSync = walkSync; +function walkStream(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new stream_1$4.default(directory, settings); + return provider.read(); +} +out$3.walkStream = walkStream; +function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings_1$1.default) { + return settingsOrOptions; + } + return new settings_1$1.default(settingsOrOptions); +} + +var reader = {}; + +Object.defineProperty(reader, "__esModule", { value: true }); +const path$b = require$$0$4; +const fsStat$2 = out$1; +const utils$6 = utils$g; +class Reader { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new fsStat$2.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); + } + _getFullEntryPath(filepath) { + return path$b.resolve(this._settings.cwd, filepath); + } + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils$6.fs.createDirentFromStats(pattern, stats) + }; + if (this._settings.stats) { + entry.stats = stats; + } + return entry; + } + _isFatalError(error) { + return !utils$6.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; + } +} +reader.default = Reader; + +var stream$1 = {}; + +Object.defineProperty(stream$1, "__esModule", { value: true }); +const stream_1$3 = require$$0$7; +const fsStat$1 = out$1; +const fsWalk$2 = out$3; +const reader_1$2 = reader; +class ReaderStream extends reader_1$2.default { + constructor() { + super(...arguments); + this._walkStream = fsWalk$2.walkStream; + this._stat = fsStat$1.stat; + } + dynamic(root, options) { + return this._walkStream(root, options); + } + static(patterns, options) { + const filepaths = patterns.map(this._getFullEntryPath, this); + const stream = new stream_1$3.PassThrough({ objectMode: true }); + stream._write = (index, _enc, done) => { + return this._getEntry(filepaths[index], patterns[index], options) + .then((entry) => { + if (entry !== null && options.entryFilter(entry)) { + stream.push(entry); + } + if (index === filepaths.length - 1) { + stream.end(); + } + done(); + }) + .catch(done); + }; + for (let i = 0; i < filepaths.length; i++) { + stream.write(i); + } + return stream; + } + _getEntry(filepath, pattern, options) { + return this._getStat(filepath) + .then((stats) => this._makeEntry(stats, pattern)) + .catch((error) => { + if (options.errorFilter(error)) { + return null; + } + throw error; + }); + } + _getStat(filepath) { + return new Promise((resolve, reject) => { + this._stat(filepath, this._fsStatSettings, (error, stats) => { + return error === null ? resolve(stats) : reject(error); + }); + }); + } +} +stream$1.default = ReaderStream; + +Object.defineProperty(async$6, "__esModule", { value: true }); +const fsWalk$1 = out$3; +const reader_1$1 = reader; +const stream_1$2 = stream$1; +class ReaderAsync extends reader_1$1.default { + constructor() { + super(...arguments); + this._walkAsync = fsWalk$1.walk; + this._readerStream = new stream_1$2.default(this._settings); + } + dynamic(root, options) { + return new Promise((resolve, reject) => { + this._walkAsync(root, options, (error, entries) => { + if (error === null) { + resolve(entries); + } + else { + reject(error); + } + }); + }); + } + async static(patterns, options) { + const entries = []; + const stream = this._readerStream.static(patterns, options); + // After #235, replace it with an asynchronous iterator. + return new Promise((resolve, reject) => { + stream.once('error', reject); + stream.on('data', (entry) => entries.push(entry)); + stream.once('end', () => resolve(entries)); + }); + } +} +async$6.default = ReaderAsync; + +var provider = {}; + +var deep = {}; + +var partial = {}; + +var matcher = {}; + +Object.defineProperty(matcher, "__esModule", { value: true }); +const utils$5 = utils$g; +class Matcher { + constructor(_patterns, _settings, _micromatchOptions) { + this._patterns = _patterns; + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this._storage = []; + this._fillStorage(); + } + _fillStorage() { + for (const pattern of this._patterns) { + const segments = this._getPatternSegments(pattern); + const sections = this._splitSegmentsIntoSections(segments); + this._storage.push({ + complete: sections.length <= 1, + pattern, + segments, + sections + }); + } + } + _getPatternSegments(pattern) { + const parts = utils$5.pattern.getPatternParts(pattern, this._micromatchOptions); + return parts.map((part) => { + const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings); + if (!dynamic) { + return { + dynamic: false, + pattern: part + }; + } + return { + dynamic: true, + pattern: part, + patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions) + }; + }); + } + _splitSegmentsIntoSections(segments) { + return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern)); + } +} +matcher.default = Matcher; + +Object.defineProperty(partial, "__esModule", { value: true }); +const matcher_1 = matcher; +class PartialMatcher extends matcher_1.default { + match(filepath) { + const parts = filepath.split('/'); + const levels = parts.length; + const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels); + for (const pattern of patterns) { + const section = pattern.sections[0]; + /** + * In this case, the pattern has a globstar and we must read all directories unconditionally, + * but only if the level has reached the end of the first group. + * + * fixtures/{a,b}/** + * ^ true/false ^ always true + */ + if (!pattern.complete && levels > section.length) { + return true; + } + const match = parts.every((part, index) => { + const segment = pattern.segments[index]; + if (segment.dynamic && segment.patternRe.test(part)) { + return true; + } + if (!segment.dynamic && segment.pattern === part) { + return true; + } + return false; + }); + if (match) { + return true; + } + } + return false; + } +} +partial.default = PartialMatcher; + +Object.defineProperty(deep, "__esModule", { value: true }); +const utils$4 = utils$g; +const partial_1 = partial; +class DeepFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + } + getFilter(basePath, positive, negative) { + const matcher = this._getMatcher(positive); + const negativeRe = this._getNegativePatternsRe(negative); + return (entry) => this._filter(basePath, entry, matcher, negativeRe); + } + _getMatcher(patterns) { + return new partial_1.default(patterns, this._settings, this._micromatchOptions); + } + _getNegativePatternsRe(patterns) { + const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern); + return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); + } + _filter(basePath, entry, matcher, negativeRe) { + if (this._isSkippedByDeep(basePath, entry.path)) { + return false; + } + if (this._isSkippedSymbolicLink(entry)) { + return false; + } + const filepath = utils$4.path.removeLeadingDotSegment(entry.path); + if (this._isSkippedByPositivePatterns(filepath, matcher)) { + return false; + } + return this._isSkippedByNegativePatterns(filepath, negativeRe); + } + _isSkippedByDeep(basePath, entryPath) { + /** + * Avoid unnecessary depth calculations when it doesn't matter. + */ + if (this._settings.deep === Infinity) { + return false; + } + return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; + } + _getEntryLevel(basePath, entryPath) { + const entryPathDepth = entryPath.split('/').length; + if (basePath === '') { + return entryPathDepth; + } + const basePathDepth = basePath.split('/').length; + return entryPathDepth - basePathDepth; + } + _isSkippedSymbolicLink(entry) { + return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); + } + _isSkippedByPositivePatterns(entryPath, matcher) { + return !this._settings.baseNameMatch && !matcher.match(entryPath); + } + _isSkippedByNegativePatterns(entryPath, patternsRe) { + return !utils$4.pattern.matchAny(entryPath, patternsRe); + } +} +deep.default = DeepFilter; + +var entry$1 = {}; + +Object.defineProperty(entry$1, "__esModule", { value: true }); +const utils$3 = utils$g; +class EntryFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = new Map(); + } + getFilter(positive, negative) { + const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions); + const negativeRe = utils$3.pattern.convertPatternsToRe(negative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })); + return (entry) => this._filter(entry, positiveRe, negativeRe); + } + _filter(entry, positiveRe, negativeRe) { + const filepath = utils$3.path.removeLeadingDotSegment(entry.path); + if (this._settings.unique && this._isDuplicateEntry(filepath)) { + return false; + } + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { + return false; + } + if (this._isSkippedByAbsoluteNegativePatterns(filepath, negativeRe)) { + return false; + } + const isDirectory = entry.dirent.isDirectory(); + const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory) && !this._isMatchToPatterns(filepath, negativeRe, isDirectory); + if (this._settings.unique && isMatched) { + this._createIndexRecord(filepath); + } + return isMatched; + } + _isDuplicateEntry(filepath) { + return this.index.has(filepath); + } + _createIndexRecord(filepath) { + this.index.set(filepath, undefined); + } + _onlyFileFilter(entry) { + return this._settings.onlyFiles && !entry.dirent.isFile(); + } + _onlyDirectoryFilter(entry) { + return this._settings.onlyDirectories && !entry.dirent.isDirectory(); + } + _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { + if (!this._settings.absolute) { + return false; + } + const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath); + return utils$3.pattern.matchAny(fullpath, patternsRe); + } + _isMatchToPatterns(filepath, patternsRe, isDirectory) { + // Trying to match files and directories by patterns. + const isMatched = utils$3.pattern.matchAny(filepath, patternsRe); + // A pattern with a trailling slash can be used for directory matching. + // To apply such pattern, we need to add a tralling slash to the path. + if (!isMatched && isDirectory) { + return utils$3.pattern.matchAny(filepath + '/', patternsRe); + } + return isMatched; + } +} +entry$1.default = EntryFilter; + +var error$2 = {}; + +Object.defineProperty(error$2, "__esModule", { value: true }); +const utils$2 = utils$g; +class ErrorFilter { + constructor(_settings) { + this._settings = _settings; + } + getFilter() { + return (error) => this._isNonFatalError(error); + } + _isNonFatalError(error) { + return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors; + } +} +error$2.default = ErrorFilter; + +var entry = {}; + +Object.defineProperty(entry, "__esModule", { value: true }); +const utils$1 = utils$g; +class EntryTransformer { + constructor(_settings) { + this._settings = _settings; + } + getTransformer() { + return (entry) => this._transform(entry); + } + _transform(entry) { + let filepath = entry.path; + if (this._settings.absolute) { + filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath); + filepath = utils$1.path.unixify(filepath); + } + if (this._settings.markDirectories && entry.dirent.isDirectory()) { + filepath += '/'; + } + if (!this._settings.objectMode) { + return filepath; + } + return Object.assign(Object.assign({}, entry), { path: filepath }); + } +} +entry.default = EntryTransformer; + +Object.defineProperty(provider, "__esModule", { value: true }); +const path$a = require$$0$4; +const deep_1 = deep; +const entry_1 = entry$1; +const error_1 = error$2; +const entry_2 = entry; +class Provider { + constructor(_settings) { + this._settings = _settings; + this.errorFilter = new error_1.default(this._settings); + this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions()); + this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions()); + this.entryTransformer = new entry_2.default(this._settings); + } + _getRootDirectory(task) { + return path$a.resolve(this._settings.cwd, task.base); + } + _getReaderOptions(task) { + const basePath = task.base === '.' ? '' : task.base; + return { + basePath, + pathSegmentSeparator: '/', + concurrency: this._settings.concurrency, + deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), + entryFilter: this.entryFilter.getFilter(task.positive, task.negative), + errorFilter: this.errorFilter.getFilter(), + followSymbolicLinks: this._settings.followSymbolicLinks, + fs: this._settings.fs, + stats: this._settings.stats, + throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, + transform: this.entryTransformer.getTransformer() + }; + } + _getMicromatchOptions() { + return { + dot: this._settings.dot, + matchBase: this._settings.baseNameMatch, + nobrace: !this._settings.braceExpansion, + nocase: !this._settings.caseSensitiveMatch, + noext: !this._settings.extglob, + noglobstar: !this._settings.globstar, + posix: true, + strictSlashes: false + }; + } +} +provider.default = Provider; + +Object.defineProperty(async$7, "__esModule", { value: true }); +const async_1$1 = async$6; +const provider_1$2 = provider; +class ProviderAsync extends provider_1$2.default { + constructor() { + super(...arguments); + this._reader = new async_1$1.default(this._settings); + } + async read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = await this.api(root, task, options); + return entries.map((entry) => options.transform(entry)); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +async$7.default = ProviderAsync; + +var stream = {}; + +Object.defineProperty(stream, "__esModule", { value: true }); +const stream_1$1 = require$$0$7; +const stream_2 = stream$1; +const provider_1$1 = provider; +class ProviderStream extends provider_1$1.default { + constructor() { + super(...arguments); + this._reader = new stream_2.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const source = this.api(root, task, options); + const destination = new stream_1$1.Readable({ objectMode: true, read: () => { } }); + source + .once('error', (error) => destination.emit('error', error)) + .on('data', (entry) => destination.emit('data', options.transform(entry))) + .once('end', () => destination.emit('end')); + destination + .once('close', () => source.destroy()); + return destination; + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +stream.default = ProviderStream; + +var sync$2 = {}; + +var sync$1 = {}; + +Object.defineProperty(sync$1, "__esModule", { value: true }); +const fsStat = out$1; +const fsWalk = out$3; +const reader_1 = reader; +class ReaderSync extends reader_1.default { + constructor() { + super(...arguments); + this._walkSync = fsWalk.walkSync; + this._statSync = fsStat.statSync; + } + dynamic(root, options) { + return this._walkSync(root, options); + } + static(patterns, options) { + const entries = []; + for (const pattern of patterns) { + const filepath = this._getFullEntryPath(pattern); + const entry = this._getEntry(filepath, pattern, options); + if (entry === null || !options.entryFilter(entry)) { + continue; + } + entries.push(entry); + } + return entries; + } + _getEntry(filepath, pattern, options) { + try { + const stats = this._getStat(filepath); + return this._makeEntry(stats, pattern); + } + catch (error) { + if (options.errorFilter(error)) { + return null; + } + throw error; + } + } + _getStat(filepath) { + return this._statSync(filepath, this._fsStatSettings); + } +} +sync$1.default = ReaderSync; + +Object.defineProperty(sync$2, "__esModule", { value: true }); +const sync_1$1 = sync$1; +const provider_1 = provider; +class ProviderSync extends provider_1.default { + constructor() { + super(...arguments); + this._reader = new sync_1$1.default(this._settings); + } + read(task) { + const root = this._getRootDirectory(task); + const options = this._getReaderOptions(task); + const entries = this.api(root, task, options); + return entries.map(options.transform); + } + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + return this._reader.static(task.patterns, options); + } +} +sync$2.default = ProviderSync; + +var settings = {}; + +(function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; + const fs = require$$0__default; + const os = require$$2; + /** + * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. + * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 + */ + const CPU_COUNT = Math.max(os.cpus().length, 1); + exports.DEFAULT_FILE_SYSTEM_ADAPTER = { + lstat: fs.lstat, + lstatSync: fs.lstatSync, + stat: fs.stat, + statSync: fs.statSync, + readdir: fs.readdir, + readdirSync: fs.readdirSync + }; + class Settings { + constructor(_options = {}) { + this._options = _options; + this.absolute = this._getValue(this._options.absolute, false); + this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); + this.braceExpansion = this._getValue(this._options.braceExpansion, true); + this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); + this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); + this.cwd = this._getValue(this._options.cwd, process.cwd()); + this.deep = this._getValue(this._options.deep, Infinity); + this.dot = this._getValue(this._options.dot, false); + this.extglob = this._getValue(this._options.extglob, true); + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); + this.fs = this._getFileSystemMethods(this._options.fs); + this.globstar = this._getValue(this._options.globstar, true); + this.ignore = this._getValue(this._options.ignore, []); + this.markDirectories = this._getValue(this._options.markDirectories, false); + this.objectMode = this._getValue(this._options.objectMode, false); + this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); + this.onlyFiles = this._getValue(this._options.onlyFiles, true); + this.stats = this._getValue(this._options.stats, false); + this.suppressErrors = this._getValue(this._options.suppressErrors, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); + this.unique = this._getValue(this._options.unique, true); + if (this.onlyDirectories) { + this.onlyFiles = false; + } + if (this.stats) { + this.objectMode = true; + } + // Remove the cast to the array in the next major (#404). + this.ignore = [].concat(this.ignore); + } + _getValue(option, value) { + return option === undefined ? value : option; + } + _getFileSystemMethods(methods = {}) { + return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); + } + } + exports.default = Settings; +} (settings)); + +const taskManager = tasks; +const async_1 = async$7; +const stream_1 = stream; +const sync_1 = sync$2; +const settings_1 = settings; +const utils = utils$g; +async function FastGlob(source, options) { + assertPatternsInput(source); + const works = getWorks(source, async_1.default, options); + const result = await Promise.all(works); + return utils.array.flatten(result); +} +// https://github.com/typescript-eslint/typescript-eslint/issues/60 +// eslint-disable-next-line no-redeclare +(function (FastGlob) { + FastGlob.glob = FastGlob; + FastGlob.globSync = sync; + FastGlob.globStream = stream; + FastGlob.async = FastGlob; + function sync(source, options) { + assertPatternsInput(source); + const works = getWorks(source, sync_1.default, options); + return utils.array.flatten(works); + } + FastGlob.sync = sync; + function stream(source, options) { + assertPatternsInput(source); + const works = getWorks(source, stream_1.default, options); + /** + * The stream returned by the provider cannot work with an asynchronous iterator. + * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. + * This affects performance (+25%). I don't see best solution right now. + */ + return utils.stream.merge(works); + } + FastGlob.stream = stream; + function generateTasks(source, options) { + assertPatternsInput(source); + const patterns = [].concat(source); + const settings = new settings_1.default(options); + return taskManager.generate(patterns, settings); + } + FastGlob.generateTasks = generateTasks; + function isDynamicPattern(source, options) { + assertPatternsInput(source); + const settings = new settings_1.default(options); + return utils.pattern.isDynamicPattern(source, settings); + } + FastGlob.isDynamicPattern = isDynamicPattern; + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escape(source); + } + FastGlob.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertPathToPattern(source); + } + FastGlob.convertPathToPattern = convertPathToPattern; + (function (posix) { + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escapePosixPath(source); + } + posix.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertPosixPathToPattern(source); + } + posix.convertPathToPattern = convertPathToPattern; + })(FastGlob.posix || (FastGlob.posix = {})); + (function (win32) { + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escapeWindowsPath(source); + } + win32.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertWindowsPathToPattern(source); + } + win32.convertPathToPattern = convertPathToPattern; + })(FastGlob.win32 || (FastGlob.win32 = {})); +})(FastGlob || (FastGlob = {})); +function getWorks(source, _Provider, options) { + const patterns = [].concat(source); + const settings = new settings_1.default(options); + const tasks = taskManager.generate(patterns, settings); + const provider = new _Provider(settings); + return tasks.map(provider.read, provider); +} +function assertPatternsInput(input) { + const source = [].concat(input); + const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item)); + if (!isValidSource) { + throw new TypeError('Patterns must be a string (non empty) or an array of strings'); + } +} +var out = FastGlob; + +var glob = /*@__PURE__*/getDefaultExportFromCjs(out); + +function e(e,n,r){throw new Error(r?`No known conditions for "${n}" specifier in "${e}" package`:`Missing "${n}" specifier in "${e}" package`)}function n(n,i,o,f){let s,u,l=r(n,o),c=function(e){let n=new Set(["default",...e.conditions||[]]);return e.unsafe||n.add(e.require?"require":"import"),e.unsafe||n.add(e.browser?"browser":"node"),n}(f||{}),a=i[l];if(void 0===a){let e,n,r,t;for(t in i)n&&t.length1&&(r=t.indexOf("*",1),~r&&(e=RegExp("^"+t.substring(0,r)+"(.*)"+t.substring(1+r)).exec(l),e&&e[1]&&(u=e[1],n=t))));a=i[n];}return a||e(n,l),s=t(a,c),s||e(n,l,1),u&&function(e,n){let r,t=0,i=e.length,o=/[*]/g,f=/[/]$/;for(;t0xffff code points that are a valid part of identifiers. The +// offset starts at 0x10000, and each pair of numbers represents an +// offset to the next range, and then a size of the range. + +// Reserved word lists for various dialects of the language + +var reservedWords = { + 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", + 5: "class enum extends super const export import", + 6: "enum", + strict: "implements interface let package private protected public static yield", + strictBind: "eval arguments" +}; + +// And the keywords + +var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; + +var keywords$1 = { + 5: ecma5AndLessKeywords, + "5module": ecma5AndLessKeywords + " export import", + 6: ecma5AndLessKeywords + " const class extends export import super" +}; + +var keywordRelationalOperator = /^in(stanceof)?$/; + +// ## Character categories + +var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); +var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + +// This has a complexity linear to the value of the code. The +// assumption is that looking up astral identifier characters is +// rare. +function isInAstralSet(code, set) { + var pos = 0x10000; + for (var i = 0; i < set.length; i += 2) { + pos += set[i]; + if (pos > code) { return false } + pos += set[i + 1]; + if (pos >= code) { return true } + } + return false +} + +// Test whether a given character code starts an identifier. + +function isIdentifierStart(code, astral) { + if (code < 65) { return code === 36 } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) +} + +// Test whether a given character is part of an identifier. + +function isIdentifierChar(code, astral) { + if (code < 48) { return code === 36 } + if (code < 58) { return true } + if (code < 65) { return false } + if (code < 91) { return true } + if (code < 97) { return code === 95 } + if (code < 123) { return true } + if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } + if (astral === false) { return false } + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) +} + +// ## Token types + +// The assignment of fine-grained, information-carrying type objects +// allows the tokenizer to store the information it has about a +// token in a way that is very cheap for the parser to look up. + +// All token type variables start with an underscore, to make them +// easy to recognize. + +// The `beforeExpr` property is used to disambiguate between regular +// expressions and divisions. It is set on all token types that can +// be followed by an expression (thus, a slash after them would be a +// regular expression). +// +// The `startsExpr` property is used to check if the token ends a +// `yield` expression. It is set on all token types that either can +// directly start an expression (like a quotation mark) or can +// continue an expression (like the body of a string). +// +// `isLoop` marks a keyword as starting a loop, which is important +// to know when parsing a label, in order to allow or disallow +// continue jumps to that label. + +var TokenType = function TokenType(label, conf) { + if ( conf === void 0 ) conf = {}; + + this.label = label; + this.keyword = conf.keyword; + this.beforeExpr = !!conf.beforeExpr; + this.startsExpr = !!conf.startsExpr; + this.isLoop = !!conf.isLoop; + this.isAssign = !!conf.isAssign; + this.prefix = !!conf.prefix; + this.postfix = !!conf.postfix; + this.binop = conf.binop || null; + this.updateContext = null; +}; + +function binop(name, prec) { + return new TokenType(name, {beforeExpr: true, binop: prec}) +} +var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; + +// Map keyword names to token types. + +var keywords$2 = {}; + +// Succinct definitions of keyword token types +function kw(name, options) { + if ( options === void 0 ) options = {}; + + options.keyword = name; + return keywords$2[name] = new TokenType(name, options) +} + +var types$1 = { + num: new TokenType("num", startsExpr), + regexp: new TokenType("regexp", startsExpr), + string: new TokenType("string", startsExpr), + name: new TokenType("name", startsExpr), + privateId: new TokenType("privateId", startsExpr), + eof: new TokenType("eof"), + + // Punctuation token types. + bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), + bracketR: new TokenType("]"), + braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), + braceR: new TokenType("}"), + parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), + parenR: new TokenType(")"), + comma: new TokenType(",", beforeExpr), + semi: new TokenType(";", beforeExpr), + colon: new TokenType(":", beforeExpr), + dot: new TokenType("."), + question: new TokenType("?", beforeExpr), + questionDot: new TokenType("?."), + arrow: new TokenType("=>", beforeExpr), + template: new TokenType("template"), + invalidTemplate: new TokenType("invalidTemplate"), + ellipsis: new TokenType("...", beforeExpr), + backQuote: new TokenType("`", startsExpr), + dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + eq: new TokenType("=", {beforeExpr: true, isAssign: true}), + assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), + incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), + prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), + logicalOR: binop("||", 1), + logicalAND: binop("&&", 2), + bitwiseOR: binop("|", 3), + bitwiseXOR: binop("^", 4), + bitwiseAND: binop("&", 5), + equality: binop("==/!=/===/!==", 6), + relational: binop("/<=/>=", 7), + bitShift: binop("<>/>>>", 8), + plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), + modulo: binop("%", 10), + star: binop("*", 10), + slash: binop("/", 10), + starstar: new TokenType("**", {beforeExpr: true}), + coalesce: binop("??", 1), + + // Keyword token types. + _break: kw("break"), + _case: kw("case", beforeExpr), + _catch: kw("catch"), + _continue: kw("continue"), + _debugger: kw("debugger"), + _default: kw("default", beforeExpr), + _do: kw("do", {isLoop: true, beforeExpr: true}), + _else: kw("else", beforeExpr), + _finally: kw("finally"), + _for: kw("for", {isLoop: true}), + _function: kw("function", startsExpr), + _if: kw("if"), + _return: kw("return", beforeExpr), + _switch: kw("switch"), + _throw: kw("throw", beforeExpr), + _try: kw("try"), + _var: kw("var"), + _const: kw("const"), + _while: kw("while", {isLoop: true}), + _with: kw("with"), + _new: kw("new", {beforeExpr: true, startsExpr: true}), + _this: kw("this", startsExpr), + _super: kw("super", startsExpr), + _class: kw("class", startsExpr), + _extends: kw("extends", beforeExpr), + _export: kw("export"), + _import: kw("import", startsExpr), + _null: kw("null", startsExpr), + _true: kw("true", startsExpr), + _false: kw("false", startsExpr), + _in: kw("in", {beforeExpr: true, binop: 7}), + _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), + _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), + _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), + _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) +}; + +// Matches a whole line break (where CRLF is considered a single +// line break). Used to count lines. + +var lineBreak = /\r\n?|\n|\u2028|\u2029/; +var lineBreakG = new RegExp(lineBreak.source, "g"); + +function isNewLine(code) { + return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 +} + +function nextLineBreak(code, from, end) { + if ( end === void 0 ) end = code.length; + + for (var i = from; i < end; i++) { + var next = code.charCodeAt(i); + if (isNewLine(next)) + { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 } + } + return -1 +} + +var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; + +var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; + +var ref = Object.prototype; +var hasOwnProperty$1 = ref.hasOwnProperty; +var toString$1 = ref.toString; + +var hasOwn = Object.hasOwn || (function (obj, propName) { return ( + hasOwnProperty$1.call(obj, propName) +); }); + +var isArray = Array.isArray || (function (obj) { return ( + toString$1.call(obj) === "[object Array]" +); }); + +var regexpCache = Object.create(null); + +function wordsRegexp(words) { + return regexpCache[words] || (regexpCache[words] = new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")) +} + +function codePointToString(code) { + // UTF-16 Decoding + if (code <= 0xFFFF) { return String.fromCharCode(code) } + code -= 0x10000; + return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) +} + +var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; + +// These are used when `options.locations` is on, for the +// `startLoc` and `endLoc` properties. + +var Position = function Position(line, col) { + this.line = line; + this.column = col; +}; + +Position.prototype.offset = function offset (n) { + return new Position(this.line, this.column + n) +}; + +var SourceLocation = function SourceLocation(p, start, end) { + this.start = start; + this.end = end; + if (p.sourceFile !== null) { this.source = p.sourceFile; } +}; + +// The `getLineInfo` function is mostly useful when the +// `locations` option is off (for performance reasons) and you +// want to find the line/column position for a given character +// offset. `input` should be the code string that the offset refers +// into. + +function getLineInfo(input, offset) { + for (var line = 1, cur = 0;;) { + var nextBreak = nextLineBreak(input, cur, offset); + if (nextBreak < 0) { return new Position(line, offset - cur) } + ++line; + cur = nextBreak; + } +} + +// A second argument must be given to configure the parser process. +// These options are recognized (only `ecmaVersion` is required): + +var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 + // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` + // (the latest version the library supports). This influences + // support for strict mode, the set of reserved words, and support + // for new syntax features. + ecmaVersion: null, + // `sourceType` indicates the mode the code should be parsed in. + // Can be either `"script"` or `"module"`. This influences global + // strict mode and parsing of `import` and `export` declarations. + sourceType: "script", + // `onInsertedSemicolon` can be a callback that will be called when + // a semicolon is automatically inserted. It will be passed the + // position of the inserted semicolon as an offset, and if + // `locations` is enabled, it is given the location as a `{line, + // column}` object as second argument. + onInsertedSemicolon: null, + // `onTrailingComma` is similar to `onInsertedSemicolon`, but for + // trailing commas. + onTrailingComma: null, + // By default, reserved words are only enforced if ecmaVersion >= 5. + // Set `allowReserved` to a boolean value to explicitly turn this on + // an off. When this option has the value "never", reserved words + // and keywords can also not be used as property names. + allowReserved: null, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program, and an import.meta expression + // in a script isn't considered an error. + allowImportExportEverywhere: false, + // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. + // When enabled, await identifiers are allowed to appear at the top-level scope, + // but they are still not allowed in non-async functions. + allowAwaitOutsideFunction: null, + // When enabled, super identifiers are not constrained to + // appearing in methods and do not raise an error when they appear elsewhere. + allowSuperOutsideMethod: null, + // When enabled, hashbang directive in the beginning of file is + // allowed and treated as a line comment. Enabled by default when + // `ecmaVersion` >= 2023. + allowHashBang: false, + // By default, the parser will verify that private properties are + // only used in places where they are valid and have been declared. + // Set this to false to turn such checks off. + checkPrivateFields: true, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // A function can be passed as `onToken` option, which will + // cause Acorn to call that function with object in the same + // format as tokens returned from `tokenizer().getToken()`. Note + // that you are not allowed to call the parser from the + // callback—that will corrupt its internal state. + onToken: null, + // A function can be passed as `onComment` option, which will + // cause Acorn to call that function with `(block, text, start, + // end)` parameters whenever a comment is skipped. `block` is a + // boolean indicating whether this is a block (`/* */`) comment, + // `text` is the content of the comment, and `start` and `end` are + // character offsets that denote the start and end of the comment. + // When the `locations` option is on, two more parameters are + // passed, the full `{line, column}` locations of the start and + // end of the comments. Note that you are not allowed to call the + // parser from the callback—that will corrupt its internal state. + // When this option has an array as value, objects representing the + // comments are pushed to it. + onComment: null, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `locations` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null, + // This value, if given, is stored in every node, whether + // `locations` is on or off. + directSourceFile: null, + // When enabled, parenthesized expressions are represented by + // (non-standard) ParenthesizedExpression nodes + preserveParens: false +}; + +// Interpret and default an options object + +var warnedAboutEcmaVersion = false; + +function getOptions(opts) { + var options = {}; + + for (var opt in defaultOptions) + { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; } + + if (options.ecmaVersion === "latest") { + options.ecmaVersion = 1e8; + } else if (options.ecmaVersion == null) { + if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { + warnedAboutEcmaVersion = true; + console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); + } + options.ecmaVersion = 11; + } else if (options.ecmaVersion >= 2015) { + options.ecmaVersion -= 2009; + } + + if (options.allowReserved == null) + { options.allowReserved = options.ecmaVersion < 5; } + + if (!opts || opts.allowHashBang == null) + { options.allowHashBang = options.ecmaVersion >= 14; } + + if (isArray(options.onToken)) { + var tokens = options.onToken; + options.onToken = function (token) { return tokens.push(token); }; + } + if (isArray(options.onComment)) + { options.onComment = pushComment(options, options.onComment); } + + return options +} + +function pushComment(options, array) { + return function(block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? "Block" : "Line", + value: text, + start: start, + end: end + }; + if (options.locations) + { comment.loc = new SourceLocation(this, startLoc, endLoc); } + if (options.ranges) + { comment.range = [start, end]; } + array.push(comment); + } +} + +// Each scope gets a bitset that may contain these flags +var + SCOPE_TOP = 1, + SCOPE_FUNCTION = 2, + SCOPE_ASYNC = 4, + SCOPE_GENERATOR = 8, + SCOPE_ARROW = 16, + SCOPE_SIMPLE_CATCH = 32, + SCOPE_SUPER = 64, + SCOPE_DIRECT_SUPER = 128, + SCOPE_CLASS_STATIC_BLOCK = 256, + SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK; + +function functionFlags(async, generator) { + return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) +} + +// Used in checkLVal* and declareName to determine the type of a binding +var + BIND_NONE = 0, // Not a binding + BIND_VAR = 1, // Var-style binding + BIND_LEXICAL = 2, // Let- or const-style binding + BIND_FUNCTION = 3, // Function declaration + BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding + BIND_OUTSIDE = 5; // Special case for function names as bound inside the function + +var Parser$1 = function Parser(options, input, startPos) { + this.options = options = getOptions(options); + this.sourceFile = options.sourceFile; + this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); + var reserved = ""; + if (options.allowReserved !== true) { + reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; + if (options.sourceType === "module") { reserved += " await"; } + } + this.reservedWords = wordsRegexp(reserved); + var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; + this.reservedWordsStrict = wordsRegexp(reservedStrict); + this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); + this.input = String(input); + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + this.containsEsc = false; + + // Set up token state + + // The current position of the tokenizer in the input. + if (startPos) { + this.pos = startPos; + this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; + this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; + } else { + this.pos = this.lineStart = 0; + this.curLine = 1; + } + + // Properties of the current token: + // Its type + this.type = types$1.eof; + // For tokens that include more information than their type, the value + this.value = null; + // Its start and end offset + this.start = this.end = this.pos; + // And, if locations are used, the {line, column} object + // corresponding to those offsets + this.startLoc = this.endLoc = this.curPosition(); + + // Position information for the previous token + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; + + // The context stack is used to superficially track syntactic + // context to predict whether a regular expression is allowed in a + // given position. + this.context = this.initialContext(); + this.exprAllowed = true; + + // Figure out if it's a module code. + this.inModule = options.sourceType === "module"; + this.strict = this.inModule || this.strictDirective(this.pos); + + // Used to signify the start of a potential arrow function + this.potentialArrowAt = -1; + this.potentialArrowInForAwait = false; + + // Positions to delayed-check that yield/await does not exist in default parameters. + this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; + // Labels in scope. + this.labels = []; + // Thus-far undefined exports. + this.undefinedExports = Object.create(null); + + // If enabled, skip leading hashbang line. + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") + { this.skipLineComment(2); } + + // Scope tracking for duplicate variable names (see scope.js) + this.scopeStack = []; + this.enterScope(SCOPE_TOP); + + // For RegExp validation + this.regexpState = null; + + // The stack of private names. + // Each element has two properties: 'declared' and 'used'. + // When it exited from the outermost class definition, all used private names must be declared. + this.privateNameStack = []; +}; + +var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; + +Parser$1.prototype.parse = function parse () { + var node = this.options.program || this.startNode(); + this.nextToken(); + return this.parseTopLevel(node) +}; + +prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; + +prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit }; + +prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit }; + +prototypeAccessors.canAwait.get = function () { + for (var i = this.scopeStack.length - 1; i >= 0; i--) { + var scope = this.scopeStack[i]; + if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false } + if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 } + } + return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction +}; + +prototypeAccessors.allowSuper.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod +}; + +prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; + +prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; + +prototypeAccessors.allowNewDotTarget.get = function () { + var ref = this.currentThisScope(); + var flags = ref.flags; + var inClassFieldInit = ref.inClassFieldInit; + return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit +}; + +prototypeAccessors.inClassStaticBlock.get = function () { + return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0 +}; + +Parser$1.extend = function extend () { + var plugins = [], len = arguments.length; + while ( len-- ) plugins[ len ] = arguments[ len ]; + + var cls = this; + for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } + return cls +}; + +Parser$1.parse = function parse (input, options) { + return new this(options, input).parse() +}; + +Parser$1.parseExpressionAt = function parseExpressionAt (input, pos, options) { + var parser = new this(options, input, pos); + parser.nextToken(); + return parser.parseExpression() +}; + +Parser$1.tokenizer = function tokenizer (input, options) { + return new this(options, input) +}; + +Object.defineProperties( Parser$1.prototype, prototypeAccessors ); + +var pp$9 = Parser$1.prototype; + +// ## Parser utilities + +var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; +pp$9.strictDirective = function(start) { + if (this.options.ecmaVersion < 5) { return false } + for (;;) { + // Try to find string literal. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + var match = literal.exec(this.input.slice(start)); + if (!match) { return false } + if ((match[1] || match[2]) === "use strict") { + skipWhiteSpace.lastIndex = start + match[0].length; + var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; + var next = this.input.charAt(end); + return next === ";" || next === "}" || + (lineBreak.test(spaceAfter[0]) && + !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) + } + start += match[0].length; + + // Skip semicolon, if any. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + if (this.input[start] === ";") + { start++; } + } +}; + +// Predicate that tests whether the next token is of the given +// type, and if yes, consumes it as a side effect. + +pp$9.eat = function(type) { + if (this.type === type) { + this.next(); + return true + } else { + return false + } +}; + +// Tests whether parsed token is a contextual keyword. + +pp$9.isContextual = function(name) { + return this.type === types$1.name && this.value === name && !this.containsEsc +}; + +// Consumes contextual keyword if possible. + +pp$9.eatContextual = function(name) { + if (!this.isContextual(name)) { return false } + this.next(); + return true +}; + +// Asserts that following token is given contextual keyword. + +pp$9.expectContextual = function(name) { + if (!this.eatContextual(name)) { this.unexpected(); } +}; + +// Test whether a semicolon can be inserted at the current position. + +pp$9.canInsertSemicolon = function() { + return this.type === types$1.eof || + this.type === types$1.braceR || + lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) +}; + +pp$9.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) + { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } + return true + } +}; + +// Consume a semicolon, or, failing that, see if we are allowed to +// pretend that there is a semicolon at this position. + +pp$9.semicolon = function() { + if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); } +}; + +pp$9.afterTrailingComma = function(tokType, notNext) { + if (this.type === tokType) { + if (this.options.onTrailingComma) + { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } + if (!notNext) + { this.next(); } + return true + } +}; + +// Expect a token of a given type. If found, consume it, otherwise, +// raise an unexpected token error. + +pp$9.expect = function(type) { + this.eat(type) || this.unexpected(); +}; + +// Raise an unexpected token error. + +pp$9.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); +}; + +var DestructuringErrors = function DestructuringErrors() { + this.shorthandAssign = + this.trailingComma = + this.parenthesizedAssign = + this.parenthesizedBind = + this.doubleProto = + -1; +}; + +pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) { + if (!refDestructuringErrors) { return } + if (refDestructuringErrors.trailingComma > -1) + { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } + var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; + if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); } +}; + +pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { + if (!refDestructuringErrors) { return false } + var shorthandAssign = refDestructuringErrors.shorthandAssign; + var doubleProto = refDestructuringErrors.doubleProto; + if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } + if (shorthandAssign >= 0) + { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } + if (doubleProto >= 0) + { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } +}; + +pp$9.checkYieldAwaitInDefaultParams = function() { + if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) + { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } + if (this.awaitPos) + { this.raise(this.awaitPos, "Await expression cannot be a default value"); } +}; + +pp$9.isSimpleAssignTarget = function(expr) { + if (expr.type === "ParenthesizedExpression") + { return this.isSimpleAssignTarget(expr.expression) } + return expr.type === "Identifier" || expr.type === "MemberExpression" +}; + +var pp$8 = Parser$1.prototype; + +// ### Statement parsing + +// Parse a program. Initializes the parser, reads any number of +// statements, and wraps them in a Program node. Optionally takes a +// `program` argument. If present, the statements will be appended +// to its body instead of creating a new node. + +pp$8.parseTopLevel = function(node) { + var exports = Object.create(null); + if (!node.body) { node.body = []; } + while (this.type !== types$1.eof) { + var stmt = this.parseStatement(null, true, exports); + node.body.push(stmt); + } + if (this.inModule) + { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) + { + var name = list[i]; + + this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); + } } + this.adaptDirectivePrologue(node.body); + this.next(); + node.sourceType = this.options.sourceType; + return this.finishNode(node, "Program") +}; + +var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; + +pp$8.isLet = function(context) { + if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + // For ambiguous cases, determine if a LexicalDeclaration (or only a + // Statement) is allowed here. If context is not empty then only a Statement + // is allowed. However, `let [` is an explicit negative lookahead for + // ExpressionStatement, so special-case it first. + if (nextCh === 91 || nextCh === 92) { return true } // '[', '/' + if (context) { return false } + + if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral + if (isIdentifierStart(nextCh, true)) { + var pos = next + 1; + while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } + if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } + var ident = this.input.slice(next, pos); + if (!keywordRelationalOperator.test(ident)) { return true } + } + return false +}; + +// check 'async [no LineTerminator here] function' +// - 'async /*foo*/ function' is OK. +// - 'async /*\n*/ function' is invalid. +pp$8.isAsyncFunction = function() { + if (this.options.ecmaVersion < 8 || !this.isContextual("async")) + { return false } + + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, after; + return !lineBreak.test(this.input.slice(this.pos, next)) && + this.input.slice(next, next + 8) === "function" && + (next + 8 === this.input.length || + !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) +}; + +// Parse a single statement. +// +// If expecting a statement and finding a slash operator, parse a +// regular expression literal. This is to handle cases like +// `if (foo) /blah/.exec(foo)`, where looking at the previous token +// does not help. + +pp$8.parseStatement = function(context, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind; + + if (this.isLet(context)) { + starttype = types$1._var; + kind = "let"; + } + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword) + case types$1._debugger: return this.parseDebuggerStatement(node) + case types$1._do: return this.parseDoStatement(node) + case types$1._for: return this.parseForStatement(node) + case types$1._function: + // Function as sole body of either an if statement or a labeled statement + // works, but not when it is part of a labeled statement that is the sole + // body of an if statement. + if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } + return this.parseFunctionStatement(node, false, !context) + case types$1._class: + if (context) { this.unexpected(); } + return this.parseClass(node, true) + case types$1._if: return this.parseIfStatement(node) + case types$1._return: return this.parseReturnStatement(node) + case types$1._switch: return this.parseSwitchStatement(node) + case types$1._throw: return this.parseThrowStatement(node) + case types$1._try: return this.parseTryStatement(node) + case types$1._const: case types$1._var: + kind = kind || this.value; + if (context && kind !== "var") { this.unexpected(); } + return this.parseVarStatement(node, kind) + case types$1._while: return this.parseWhileStatement(node) + case types$1._with: return this.parseWithStatement(node) + case types$1.braceL: return this.parseBlock(true, node) + case types$1.semi: return this.parseEmptyStatement(node) + case types$1._export: + case types$1._import: + if (this.options.ecmaVersion > 10 && starttype === types$1._import) { + skipWhiteSpace.lastIndex = this.pos; + var skip = skipWhiteSpace.exec(this.input); + var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); + if (nextCh === 40 || nextCh === 46) // '(' or '.' + { return this.parseExpressionStatement(node, this.parseExpression()) } + } + + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) + { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } + if (!this.inModule) + { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } + } + return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports) + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + default: + if (this.isAsyncFunction()) { + if (context) { this.unexpected(); } + this.next(); + return this.parseFunctionStatement(node, true, !context) + } + + var maybeName = this.value, expr = this.parseExpression(); + if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) + { return this.parseLabeledStatement(node, maybeName, expr, context) } + else { return this.parseExpressionStatement(node, expr) } + } +}; + +pp$8.parseBreakContinueStatement = function(node, keyword) { + var isBreak = keyword === "break"; + this.next(); + if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; } + else if (this.type !== types$1.name) { this.unexpected(); } + else { + node.label = this.parseIdent(); + this.semicolon(); + } + + // Verify that there is an actual destination to break or + // continue to. + var i = 0; + for (; i < this.labels.length; ++i) { + var lab = this.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } + if (node.label && isBreak) { break } + } + } + if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") +}; + +pp$8.parseDebuggerStatement = function(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement") +}; + +pp$8.parseDoStatement = function(node) { + this.next(); + this.labels.push(loopLabel); + node.body = this.parseStatement("do"); + this.labels.pop(); + this.expect(types$1._while); + node.test = this.parseParenExpression(); + if (this.options.ecmaVersion >= 6) + { this.eat(types$1.semi); } + else + { this.semicolon(); } + return this.finishNode(node, "DoWhileStatement") +}; + +// Disambiguating between a `for` and a `for`/`in` or `for`/`of` +// loop is non-trivial. Basically, we have to parse the init `var` +// statement or expression, disallowing the `in` operator (see +// the second parameter to `parseExpression`), and then check +// whether the next token is `in` or `of`. When there is no init +// part (semicolon immediately after the opening parenthesis), it +// is a regular `for` loop. + +pp$8.parseForStatement = function(node) { + this.next(); + var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; + this.labels.push(loopLabel); + this.enterScope(0); + this.expect(types$1.parenL); + if (this.type === types$1.semi) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, null) + } + var isLet = this.isLet(); + if (this.type === types$1._var || this.type === types$1._const || isLet) { + var init$1 = this.startNode(), kind = isLet ? "let" : this.value; + this.next(); + this.parseVar(init$1, true, kind); + this.finishNode(init$1, "VariableDeclaration"); + if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + return this.parseForIn(node, init$1) + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init$1) + } + var startsWithLet = this.isContextual("let"), isForOf = false; + var refDestructuringErrors = new DestructuringErrors; + var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); + if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { + if (this.options.ecmaVersion >= 9) { + if (this.type === types$1._in) { + if (awaitAt > -1) { this.unexpected(awaitAt); } + } else { node.await = awaitAt > -1; } + } + if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } + this.toAssignable(init, false, refDestructuringErrors); + this.checkLValPattern(init); + return this.parseForIn(node, init) + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init) +}; + +pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) +}; + +pp$8.parseIfStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + // allow function declarations in branches, but only in non-strict mode + node.consequent = this.parseStatement("if"); + node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; + return this.finishNode(node, "IfStatement") +}; + +pp$8.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) + { this.raise(this.start, "'return' outside of function"); } + this.next(); + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; } + else { node.argument = this.parseExpression(); this.semicolon(); } + return this.finishNode(node, "ReturnStatement") +}; + +pp$8.parseSwitchStatement = function(node) { + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(types$1.braceL); + this.labels.push(switchLabel); + this.enterScope(0); + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + var cur; + for (var sawDefault = false; this.type !== types$1.braceR;) { + if (this.type === types$1._case || this.type === types$1._default) { + var isCase = this.type === types$1._case; + if (cur) { this.finishNode(cur, "SwitchCase"); } + node.cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } + sawDefault = true; + cur.test = null; + } + this.expect(types$1.colon); + } else { + if (!cur) { this.unexpected(); } + cur.consequent.push(this.parseStatement(null)); + } + } + this.exitScope(); + if (cur) { this.finishNode(cur, "SwitchCase"); } + this.next(); // Closing brace + this.labels.pop(); + return this.finishNode(node, "SwitchStatement") +}; + +pp$8.parseThrowStatement = function(node) { + this.next(); + if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) + { this.raise(this.lastTokEnd, "Illegal newline after throw"); } + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement") +}; + +// Reused empty array added for node fields that are always empty. + +var empty$1 = []; + +pp$8.parseCatchClauseParam = function() { + var param = this.parseBindingAtom(); + var simple = param.type === "Identifier"; + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); + this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); + this.expect(types$1.parenR); + + return param +}; + +pp$8.parseTryStatement = function(node) { + this.next(); + node.block = this.parseBlock(); + node.handler = null; + if (this.type === types$1._catch) { + var clause = this.startNode(); + this.next(); + if (this.eat(types$1.parenL)) { + clause.param = this.parseCatchClauseParam(); + } else { + if (this.options.ecmaVersion < 10) { this.unexpected(); } + clause.param = null; + this.enterScope(0); + } + clause.body = this.parseBlock(false); + this.exitScope(); + node.handler = this.finishNode(clause, "CatchClause"); + } + node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; + if (!node.handler && !node.finalizer) + { this.raise(node.start, "Missing catch or finally clause"); } + return this.finishNode(node, "TryStatement") +}; + +pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) { + this.next(); + this.parseVar(node, false, kind, allowMissingInitializer); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration") +}; + +pp$8.parseWhileStatement = function(node) { + this.next(); + node.test = this.parseParenExpression(); + this.labels.push(loopLabel); + node.body = this.parseStatement("while"); + this.labels.pop(); + return this.finishNode(node, "WhileStatement") +}; + +pp$8.parseWithStatement = function(node) { + if (this.strict) { this.raise(this.start, "'with' in strict mode"); } + this.next(); + node.object = this.parseParenExpression(); + node.body = this.parseStatement("with"); + return this.finishNode(node, "WithStatement") +}; + +pp$8.parseEmptyStatement = function(node) { + this.next(); + return this.finishNode(node, "EmptyStatement") +}; + +pp$8.parseLabeledStatement = function(node, maybeName, expr, context) { + for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) + { + var label = list[i$1]; + + if (label.name === maybeName) + { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } } + var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; + for (var i = this.labels.length - 1; i >= 0; i--) { + var label$1 = this.labels[i]; + if (label$1.statementStart === node.start) { + // Update information about previous labels on this node + label$1.statementStart = this.start; + label$1.kind = kind; + } else { break } + } + this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); + node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); + this.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement") +}; + +pp$8.parseExpressionStatement = function(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement") +}; + +// Parse a semicolon-enclosed block of statements, handling `"use +// strict"` declarations when `allowStrict` is true (used for +// function bodies). + +pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) { + if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; + if ( node === void 0 ) node = this.startNode(); + + node.body = []; + this.expect(types$1.braceL); + if (createNewLexicalScope) { this.enterScope(0); } + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + if (exitStrict) { this.strict = false; } + this.next(); + if (createNewLexicalScope) { this.exitScope(); } + return this.finishNode(node, "BlockStatement") +}; + +// Parse a regular `for` loop. The disambiguation code in +// `parseStatement` will already have parsed the init statement or +// expression. + +pp$8.parseFor = function(node, init) { + node.init = init; + this.expect(types$1.semi); + node.test = this.type === types$1.semi ? null : this.parseExpression(); + this.expect(types$1.semi); + node.update = this.type === types$1.parenR ? null : this.parseExpression(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, "ForStatement") +}; + +// Parse a `for`/`in` and `for`/`of` loop, which are almost +// same from parser's perspective. + +pp$8.parseForIn = function(node, init) { + var isForIn = this.type === types$1._in; + this.next(); + + if ( + init.type === "VariableDeclaration" && + init.declarations[0].init != null && + ( + !isForIn || + this.options.ecmaVersion < 8 || + this.strict || + init.kind !== "var" || + init.declarations[0].id.type !== "Identifier" + ) + ) { + this.raise( + init.start, + ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") + ); + } + node.left = init; + node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); + this.expect(types$1.parenR); + node.body = this.parseStatement("for"); + this.exitScope(); + this.labels.pop(); + return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") +}; + +// Parse a list of variable declarations. + +pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) { + node.declarations = []; + node.kind = kind; + for (;;) { + var decl = this.startNode(); + this.parseVarId(decl, kind); + if (this.eat(types$1.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { + this.unexpected(); + } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { + this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types$1.comma)) { break } + } + return node +}; + +pp$8.parseVarId = function(decl, kind) { + decl.id = this.parseBindingAtom(); + this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); +}; + +var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; + +// Parse a function declaration or literal (depending on the +// `statement & FUNC_STATEMENT`). + +// Remove `allowExpressionBody` for 7.0.0, as it is only called with false +pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { + this.initFunction(node); + if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { + if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT)) + { this.unexpected(); } + node.generator = this.eat(types$1.star); + } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + if (statement & FUNC_STATEMENT) { + node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent(); + if (node.id && !(statement & FUNC_HANGING_STATEMENT)) + // If it is a regular function declaration in sloppy mode, then it is + // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding + // mode depends on properties of the current scope (see + // treatFunctionsAsVar). + { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } + } + + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(node.async, node.generator)); + + if (!(statement & FUNC_STATEMENT)) + { node.id = this.type === types$1.name ? this.parseIdent() : null; } + + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody, false, forInit); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") +}; + +pp$8.parseFunctionParams = function(node) { + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); +}; + +// Parse a class declaration or literal (depending on the +// `isStatement` parameter). + +pp$8.parseClass = function(node, isStatement) { + this.next(); + + // ecma-262 14.6 Class Definitions + // A class definition is always strict mode code. + var oldStrict = this.strict; + this.strict = true; + + this.parseClassId(node, isStatement); + this.parseClassSuper(node); + var privateNameMap = this.enterClassBody(); + var classBody = this.startNode(); + var hadConstructor = false; + classBody.body = []; + this.expect(types$1.braceL); + while (this.type !== types$1.braceR) { + var element = this.parseClassElement(node.superClass !== null); + if (element) { + classBody.body.push(element); + if (element.type === "MethodDefinition" && element.kind === "constructor") { + if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); } + hadConstructor = true; + } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { + this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); + } + } + } + this.strict = oldStrict; + this.next(); + node.body = this.finishNode(classBody, "ClassBody"); + this.exitClassBody(); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") +}; + +pp$8.parseClassElement = function(constructorAllowsSuper) { + if (this.eat(types$1.semi)) { return null } + + var ecmaVersion = this.options.ecmaVersion; + var node = this.startNode(); + var keyName = ""; + var isGenerator = false; + var isAsync = false; + var kind = "method"; + var isStatic = false; + + if (this.eatContextual("static")) { + // Parse static init block + if (ecmaVersion >= 13 && this.eat(types$1.braceL)) { + this.parseClassStaticBlock(node); + return node + } + if (this.isClassElementNameStart() || this.type === types$1.star) { + isStatic = true; + } else { + keyName = "static"; + } + } + node.static = isStatic; + if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { + isAsync = true; + } else { + keyName = "async"; + } + } + if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) { + isGenerator = true; + } + if (!keyName && !isAsync && !isGenerator) { + var lastValue = this.value; + if (this.eatContextual("get") || this.eatContextual("set")) { + if (this.isClassElementNameStart()) { + kind = lastValue; + } else { + keyName = lastValue; + } + } + } + + // Parse element name + if (keyName) { + // 'async', 'get', 'set', or 'static' were not a keyword contextually. + // The last token is any of those. Make it the element name. + node.computed = false; + node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); + node.key.name = keyName; + this.finishNode(node.key, "Identifier"); + } else { + this.parseClassElementName(node); + } + + // Parse element value + if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { + var isConstructor = !node.static && checkKeyName(node, "constructor"); + var allowsDirectSuper = isConstructor && constructorAllowsSuper; + // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. + if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } + node.kind = isConstructor ? "constructor" : kind; + this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); + } else { + this.parseClassField(node); + } + + return node +}; + +pp$8.isClassElementNameStart = function() { + return ( + this.type === types$1.name || + this.type === types$1.privateId || + this.type === types$1.num || + this.type === types$1.string || + this.type === types$1.bracketL || + this.type.keyword + ) +}; + +pp$8.parseClassElementName = function(element) { + if (this.type === types$1.privateId) { + if (this.value === "constructor") { + this.raise(this.start, "Classes can't have an element named '#constructor'"); + } + element.computed = false; + element.key = this.parsePrivateIdent(); + } else { + this.parsePropertyName(element); + } +}; + +pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + // Check key and flags + var key = method.key; + if (method.kind === "constructor") { + if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } + if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } + } else if (method.static && checkKeyName(method, "prototype")) { + this.raise(key.start, "Classes may not have a static property named prototype"); + } + + // Parse value + var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + + // Check value + if (method.kind === "get" && value.params.length !== 0) + { this.raiseRecoverable(value.start, "getter should have no params"); } + if (method.kind === "set" && value.params.length !== 1) + { this.raiseRecoverable(value.start, "setter should have exactly one param"); } + if (method.kind === "set" && value.params[0].type === "RestElement") + { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } + + return this.finishNode(method, "MethodDefinition") +}; + +pp$8.parseClassField = function(field) { + if (checkKeyName(field, "constructor")) { + this.raise(field.key.start, "Classes can't have a field named 'constructor'"); + } else if (field.static && checkKeyName(field, "prototype")) { + this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); + } + + if (this.eat(types$1.eq)) { + // To raise SyntaxError if 'arguments' exists in the initializer. + var scope = this.currentThisScope(); + var inClassFieldInit = scope.inClassFieldInit; + scope.inClassFieldInit = true; + field.value = this.parseMaybeAssign(); + scope.inClassFieldInit = inClassFieldInit; + } else { + field.value = null; + } + this.semicolon(); + + return this.finishNode(field, "PropertyDefinition") +}; + +pp$8.parseClassStaticBlock = function(node) { + node.body = []; + + var oldLabels = this.labels; + this.labels = []; + this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); + while (this.type !== types$1.braceR) { + var stmt = this.parseStatement(null); + node.body.push(stmt); + } + this.next(); + this.exitScope(); + this.labels = oldLabels; + + return this.finishNode(node, "StaticBlock") +}; + +pp$8.parseClassId = function(node, isStatement) { + if (this.type === types$1.name) { + node.id = this.parseIdent(); + if (isStatement) + { this.checkLValSimple(node.id, BIND_LEXICAL, false); } + } else { + if (isStatement === true) + { this.unexpected(); } + node.id = null; + } +}; + +pp$8.parseClassSuper = function(node) { + node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null; +}; + +pp$8.enterClassBody = function() { + var element = {declared: Object.create(null), used: []}; + this.privateNameStack.push(element); + return element.declared +}; + +pp$8.exitClassBody = function() { + var ref = this.privateNameStack.pop(); + var declared = ref.declared; + var used = ref.used; + if (!this.options.checkPrivateFields) { return } + var len = this.privateNameStack.length; + var parent = len === 0 ? null : this.privateNameStack[len - 1]; + for (var i = 0; i < used.length; ++i) { + var id = used[i]; + if (!hasOwn(declared, id.name)) { + if (parent) { + parent.used.push(id); + } else { + this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); + } + } + } +}; + +function isPrivateNameConflicted(privateNameMap, element) { + var name = element.key.name; + var curr = privateNameMap[name]; + + var next = "true"; + if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { + next = (element.static ? "s" : "i") + element.kind; + } + + // `class { get #a(){}; static set #a(_){} }` is also conflict. + if ( + curr === "iget" && next === "iset" || + curr === "iset" && next === "iget" || + curr === "sget" && next === "sset" || + curr === "sset" && next === "sget" + ) { + privateNameMap[name] = "true"; + return false + } else if (!curr) { + privateNameMap[name] = next; + return false + } else { + return true + } +} + +function checkKeyName(node, name) { + var computed = node.computed; + var key = node.key; + return !computed && ( + key.type === "Identifier" && key.name === name || + key.type === "Literal" && key.value === name + ) +} + +// Parses module export declaration. + +pp$8.parseExportAllDeclaration = function(node, exports) { + if (this.options.ecmaVersion >= 11) { + if (this.eatContextual("as")) { + node.exported = this.parseModuleExportName(); + this.checkExport(exports, node.exported, this.lastTokStart); + } else { + node.exported = null; + } + } + this.expectContextual("from"); + if (this.type !== types$1.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + this.semicolon(); + return this.finishNode(node, "ExportAllDeclaration") +}; + +pp$8.parseExport = function(node, exports) { + this.next(); + // export * from '...' + if (this.eat(types$1.star)) { + return this.parseExportAllDeclaration(node, exports) + } + if (this.eat(types$1._default)) { // export default ... + this.checkExport(exports, "default", this.lastTokStart); + node.declaration = this.parseExportDefaultDeclaration(); + return this.finishNode(node, "ExportDefaultDeclaration") + } + // export var|const|let|function|class ... + if (this.shouldParseExportStatement()) { + node.declaration = this.parseExportDeclaration(node); + if (node.declaration.type === "VariableDeclaration") + { this.checkVariableExport(exports, node.declaration.declarations); } + else + { this.checkExport(exports, node.declaration.id, node.declaration.id.start); } + node.specifiers = []; + node.source = null; + } else { // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(exports); + if (this.eatContextual("from")) { + if (this.type !== types$1.string) { this.unexpected(); } + node.source = this.parseExprAtom(); + } else { + for (var i = 0, list = node.specifiers; i < list.length; i += 1) { + // check for keywords used as local names + var spec = list[i]; + + this.checkUnreserved(spec.local); + // check if export is defined + this.checkLocalExport(spec.local); + + if (spec.local.type === "Literal") { + this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); + } + } + + node.source = null; + } + this.semicolon(); + } + return this.finishNode(node, "ExportNamedDeclaration") +}; + +pp$8.parseExportDeclaration = function(node) { + return this.parseStatement(null) +}; + +pp$8.parseExportDefaultDeclaration = function() { + var isAsync; + if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { + var fNode = this.startNode(); + this.next(); + if (isAsync) { this.next(); } + return this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync) + } else if (this.type === types$1._class) { + var cNode = this.startNode(); + return this.parseClass(cNode, "nullableID") + } else { + var declaration = this.parseMaybeAssign(); + this.semicolon(); + return declaration + } +}; + +pp$8.checkExport = function(exports, name, pos) { + if (!exports) { return } + if (typeof name !== "string") + { name = name.type === "Identifier" ? name.name : name.value; } + if (hasOwn(exports, name)) + { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } + exports[name] = true; +}; + +pp$8.checkPatternExport = function(exports, pat) { + var type = pat.type; + if (type === "Identifier") + { this.checkExport(exports, pat, pat.start); } + else if (type === "ObjectPattern") + { for (var i = 0, list = pat.properties; i < list.length; i += 1) + { + var prop = list[i]; + + this.checkPatternExport(exports, prop); + } } + else if (type === "ArrayPattern") + { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { + var elt = list$1[i$1]; + + if (elt) { this.checkPatternExport(exports, elt); } + } } + else if (type === "Property") + { this.checkPatternExport(exports, pat.value); } + else if (type === "AssignmentPattern") + { this.checkPatternExport(exports, pat.left); } + else if (type === "RestElement") + { this.checkPatternExport(exports, pat.argument); } +}; + +pp$8.checkVariableExport = function(exports, decls) { + if (!exports) { return } + for (var i = 0, list = decls; i < list.length; i += 1) + { + var decl = list[i]; + + this.checkPatternExport(exports, decl.id); + } +}; + +pp$8.shouldParseExportStatement = function() { + return this.type.keyword === "var" || + this.type.keyword === "const" || + this.type.keyword === "class" || + this.type.keyword === "function" || + this.isLet() || + this.isAsyncFunction() +}; + +// Parses a comma-separated list of module exports. + +pp$8.parseExportSpecifier = function(exports) { + var node = this.startNode(); + node.local = this.parseModuleExportName(); + + node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; + this.checkExport( + exports, + node.exported, + node.exported.start + ); + + return this.finishNode(node, "ExportSpecifier") +}; + +pp$8.parseExportSpecifiers = function(exports) { + var nodes = [], first = true; + // export { x, y as z } [from '...'] + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + nodes.push(this.parseExportSpecifier(exports)); + } + return nodes +}; + +// Parses import declaration. + +pp$8.parseImport = function(node) { + this.next(); + + // import '...' + if (this.type === types$1.string) { + node.specifiers = empty$1; + node.source = this.parseExprAtom(); + } else { + node.specifiers = this.parseImportSpecifiers(); + this.expectContextual("from"); + node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); + } + this.semicolon(); + return this.finishNode(node, "ImportDeclaration") +}; + +// Parses a comma-separated list of module imports. + +pp$8.parseImportSpecifier = function() { + var node = this.startNode(); + node.imported = this.parseModuleExportName(); + + if (this.eatContextual("as")) { + node.local = this.parseIdent(); + } else { + this.checkUnreserved(node.imported); + node.local = node.imported; + } + this.checkLValSimple(node.local, BIND_LEXICAL); + + return this.finishNode(node, "ImportSpecifier") +}; + +pp$8.parseImportDefaultSpecifier = function() { + // import defaultObj, { x, y as z } from '...' + var node = this.startNode(); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportDefaultSpecifier") +}; + +pp$8.parseImportNamespaceSpecifier = function() { + var node = this.startNode(); + this.next(); + this.expectContextual("as"); + node.local = this.parseIdent(); + this.checkLValSimple(node.local, BIND_LEXICAL); + return this.finishNode(node, "ImportNamespaceSpecifier") +}; + +pp$8.parseImportSpecifiers = function() { + var nodes = [], first = true; + if (this.type === types$1.name) { + nodes.push(this.parseImportDefaultSpecifier()); + if (!this.eat(types$1.comma)) { return nodes } + } + if (this.type === types$1.star) { + nodes.push(this.parseImportNamespaceSpecifier()); + return nodes + } + this.expect(types$1.braceL); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + nodes.push(this.parseImportSpecifier()); + } + return nodes +}; + +pp$8.parseModuleExportName = function() { + if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { + var stringLiteral = this.parseLiteral(this.value); + if (loneSurrogate.test(stringLiteral.value)) { + this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); + } + return stringLiteral + } + return this.parseIdent(true) +}; + +// Set `ExpressionStatement#directive` property for directive prologues. +pp$8.adaptDirectivePrologue = function(statements) { + for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { + statements[i].directive = statements[i].expression.raw.slice(1, -1); + } +}; +pp$8.isDirectiveCandidate = function(statement) { + return ( + this.options.ecmaVersion >= 5 && + statement.type === "ExpressionStatement" && + statement.expression.type === "Literal" && + typeof statement.expression.value === "string" && + // Reject parenthesized strings. + (this.input[statement.start] === "\"" || this.input[statement.start] === "'") + ) +}; + +var pp$7 = Parser$1.prototype; + +// Convert existing expression atom to assignable pattern +// if possible. + +pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) { + if (this.options.ecmaVersion >= 6 && node) { + switch (node.type) { + case "Identifier": + if (this.inAsync && node.name === "await") + { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } + break + + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + break + + case "ObjectExpression": + node.type = "ObjectPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + for (var i = 0, list = node.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.toAssignable(prop, isBinding); + // Early error: + // AssignmentRestProperty[Yield, Await] : + // `...` DestructuringAssignmentTarget[Yield, Await] + // + // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. + if ( + prop.type === "RestElement" && + (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") + ) { + this.raise(prop.argument.start, "Unexpected token"); + } + } + break + + case "Property": + // AssignmentProperty has type === "Property" + if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } + this.toAssignable(node.value, isBinding); + break + + case "ArrayExpression": + node.type = "ArrayPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + this.toAssignableList(node.elements, isBinding); + break + + case "SpreadElement": + node.type = "RestElement"; + this.toAssignable(node.argument, isBinding); + if (node.argument.type === "AssignmentPattern") + { this.raise(node.argument.start, "Rest elements cannot have a default value"); } + break + + case "AssignmentExpression": + if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } + node.type = "AssignmentPattern"; + delete node.operator; + this.toAssignable(node.left, isBinding); + break + + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + break + + case "ChainExpression": + this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (!isBinding) { break } + + default: + this.raise(node.start, "Assigning to rvalue"); + } + } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + return node +}; + +// Convert list of expression atoms to binding list. + +pp$7.toAssignableList = function(exprList, isBinding) { + var end = exprList.length; + for (var i = 0; i < end; i++) { + var elt = exprList[i]; + if (elt) { this.toAssignable(elt, isBinding); } + } + if (end) { + var last = exprList[end - 1]; + if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") + { this.unexpected(last.argument.start); } + } + return exprList +}; + +// Parses spread element. + +pp$7.parseSpread = function(refDestructuringErrors) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node, "SpreadElement") +}; + +pp$7.parseRestBinding = function() { + var node = this.startNode(); + this.next(); + + // RestElement inside of a function parameter must be an identifier + if (this.options.ecmaVersion === 6 && this.type !== types$1.name) + { this.unexpected(); } + + node.argument = this.parseBindingAtom(); + + return this.finishNode(node, "RestElement") +}; + +// Parses lvalue (assignable) atom. + +pp$7.parseBindingAtom = function() { + if (this.options.ecmaVersion >= 6) { + switch (this.type) { + case types$1.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(types$1.bracketR, true, true); + return this.finishNode(node, "ArrayPattern") + + case types$1.braceL: + return this.parseObj(true) + } + } + return this.parseIdent() +}; + +pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) { + var elts = [], first = true; + while (!this.eat(close)) { + if (first) { first = false; } + else { this.expect(types$1.comma); } + if (allowEmpty && this.type === types$1.comma) { + elts.push(null); + } else if (allowTrailingComma && this.afterTrailingComma(close)) { + break + } else if (this.type === types$1.ellipsis) { + var rest = this.parseRestBinding(); + this.parseBindingListItem(rest); + elts.push(rest); + if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); } + this.expect(close); + break + } else { + elts.push(this.parseAssignableListItem(allowModifiers)); + } + } + return elts +}; + +pp$7.parseAssignableListItem = function(allowModifiers) { + var elem = this.parseMaybeDefault(this.start, this.startLoc); + this.parseBindingListItem(elem); + return elem +}; + +pp$7.parseBindingListItem = function(param) { + return param +}; + +// Parses assignment pattern around given atom if possible. + +pp$7.parseMaybeDefault = function(startPos, startLoc, left) { + left = left || this.parseBindingAtom(); + if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern") +}; + +// The following three functions all verify that a node is an lvalue — +// something that can be bound, or assigned to. In order to do so, they perform +// a variety of checks: +// +// - Check that none of the bound/assigned-to identifiers are reserved words. +// - Record name declarations for bindings in the appropriate scope. +// - Check duplicate argument names, if checkClashes is set. +// +// If a complex binding pattern is encountered (e.g., object and array +// destructuring), the entire pattern is recursively checked. +// +// There are three versions of checkLVal*() appropriate for different +// circumstances: +// +// - checkLValSimple() shall be used if the syntactic construct supports +// nothing other than identifiers and member expressions. Parenthesized +// expressions are also correctly handled. This is generally appropriate for +// constructs for which the spec says +// +// > It is a Syntax Error if AssignmentTargetType of [the production] is not +// > simple. +// +// It is also appropriate for checking if an identifier is valid and not +// defined elsewhere, like import declarations or function/class identifiers. +// +// Examples where this is used include: +// a += …; +// import a from '…'; +// where a is the node to be checked. +// +// - checkLValPattern() shall be used if the syntactic construct supports +// anything checkLValSimple() supports, as well as object and array +// destructuring patterns. This is generally appropriate for constructs for +// which the spec says +// +// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor +// > an ArrayLiteral and AssignmentTargetType of [the production] is not +// > simple. +// +// Examples where this is used include: +// (a = …); +// const a = …; +// try { … } catch (a) { … } +// where a is the node to be checked. +// +// - checkLValInnerPattern() shall be used if the syntactic construct supports +// anything checkLValPattern() supports, as well as default assignment +// patterns, rest elements, and other constructs that may appear within an +// object or array destructuring pattern. +// +// As a special case, function parameters also use checkLValInnerPattern(), +// as they also support defaults and rest constructs. +// +// These functions deliberately support both assignment and binding constructs, +// as the logic for both is exceedingly similar. If the node is the target of +// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it +// should be set to the appropriate BIND_* constant, like BIND_VAR or +// BIND_LEXICAL. +// +// If the function is called with a non-BIND_NONE bindingType, then +// additionally a checkClashes object may be specified to allow checking for +// duplicate argument names. checkClashes is ignored if the provided construct +// is an assignment (i.e., bindingType is BIND_NONE). + +pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + var isBind = bindingType !== BIND_NONE; + + switch (expr.type) { + case "Identifier": + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } + if (isBind) { + if (bindingType === BIND_LEXICAL && expr.name === "let") + { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } + if (checkClashes) { + if (hasOwn(checkClashes, expr.name)) + { this.raiseRecoverable(expr.start, "Argument name clash"); } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } + } + break + + case "ChainExpression": + this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); + break + + case "MemberExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } + break + + case "ParenthesizedExpression": + if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } + return this.checkLValSimple(expr.expression, bindingType, checkClashes) + + default: + this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); + } +}; + +pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "ObjectPattern": + for (var i = 0, list = expr.properties; i < list.length; i += 1) { + var prop = list[i]; + + this.checkLValInnerPattern(prop, bindingType, checkClashes); + } + break + + case "ArrayPattern": + for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { + var elem = list$1[i$1]; + + if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } + } + break + + default: + this.checkLValSimple(expr, bindingType, checkClashes); + } +}; + +pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; + + switch (expr.type) { + case "Property": + // AssignmentProperty has type === "Property" + this.checkLValInnerPattern(expr.value, bindingType, checkClashes); + break + + case "AssignmentPattern": + this.checkLValPattern(expr.left, bindingType, checkClashes); + break + + case "RestElement": + this.checkLValPattern(expr.argument, bindingType, checkClashes); + break + + default: + this.checkLValPattern(expr, bindingType, checkClashes); + } +}; + +// The algorithm used to determine whether a regexp can appear at a +// given point in the program is loosely based on sweet.js' approach. +// See https://github.com/mozilla/sweet.js/wiki/design + + +var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; + this.generator = !!generator; +}; + +var types$2 = { + b_stat: new TokContext("{", false), + b_expr: new TokContext("{", true), + b_tmpl: new TokContext("${", false), + p_stat: new TokContext("(", false), + p_expr: new TokContext("(", true), + q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), + f_stat: new TokContext("function", false), + f_expr: new TokContext("function", true), + f_expr_gen: new TokContext("function", true, false, null, true), + f_gen: new TokContext("function", false, false, null, true) +}; + +var pp$6 = Parser$1.prototype; + +pp$6.initialContext = function() { + return [types$2.b_stat] +}; + +pp$6.curContext = function() { + return this.context[this.context.length - 1] +}; + +pp$6.braceIsBlock = function(prevType) { + var parent = this.curContext(); + if (parent === types$2.f_expr || parent === types$2.f_stat) + { return true } + if (prevType === types$1.colon && (parent === types$2.b_stat || parent === types$2.b_expr)) + { return !parent.isExpr } + + // The check for `tt.name && exprAllowed` detects whether we are + // after a `yield` or `of` construct. See the `updateContext` for + // `tt.name`. + if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) + { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } + if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) + { return true } + if (prevType === types$1.braceL) + { return parent === types$2.b_stat } + if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) + { return false } + return !this.exprAllowed +}; + +pp$6.inGeneratorContext = function() { + for (var i = this.context.length - 1; i >= 1; i--) { + var context = this.context[i]; + if (context.token === "function") + { return context.generator } + } + return false +}; + +pp$6.updateContext = function(prevType) { + var update, type = this.type; + if (type.keyword && prevType === types$1.dot) + { this.exprAllowed = false; } + else if (update = type.updateContext) + { update.call(this, prevType); } + else + { this.exprAllowed = type.beforeExpr; } +}; + +// Used to handle edge cases when token context could not be inferred correctly during tokenization phase + +pp$6.overrideContext = function(tokenCtx) { + if (this.curContext() !== tokenCtx) { + this.context[this.context.length - 1] = tokenCtx; + } +}; + +// Token-specific context update code + +types$1.parenR.updateContext = types$1.braceR.updateContext = function() { + if (this.context.length === 1) { + this.exprAllowed = true; + return + } + var out = this.context.pop(); + if (out === types$2.b_stat && this.curContext().token === "function") { + out = this.context.pop(); + } + this.exprAllowed = !out.isExpr; +}; + +types$1.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types$2.b_stat : types$2.b_expr); + this.exprAllowed = true; +}; + +types$1.dollarBraceL.updateContext = function() { + this.context.push(types$2.b_tmpl); + this.exprAllowed = true; +}; + +types$1.parenL.updateContext = function(prevType) { + var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; + this.context.push(statementParens ? types$2.p_stat : types$2.p_expr); + this.exprAllowed = true; +}; + +types$1.incDec.updateContext = function() { + // tokExprAllowed stays unchanged +}; + +types$1._function.updateContext = types$1._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types$1._else && + !(prevType === types$1.semi && this.curContext() !== types$2.p_stat) && + !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && + !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types$2.b_stat)) + { this.context.push(types$2.f_expr); } + else + { this.context.push(types$2.f_stat); } + this.exprAllowed = false; +}; + +types$1.colon.updateContext = function() { + if (this.curContext().token === "function") { this.context.pop(); } + this.exprAllowed = true; +}; + +types$1.backQuote.updateContext = function() { + if (this.curContext() === types$2.q_tmpl) + { this.context.pop(); } + else + { this.context.push(types$2.q_tmpl); } + this.exprAllowed = false; +}; + +types$1.star.updateContext = function(prevType) { + if (prevType === types$1._function) { + var index = this.context.length - 1; + if (this.context[index] === types$2.f_expr) + { this.context[index] = types$2.f_expr_gen; } + else + { this.context[index] = types$2.f_gen; } + } + this.exprAllowed = true; +}; + +types$1.name.updateContext = function(prevType) { + var allowed = false; + if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { + if (this.value === "of" && !this.exprAllowed || + this.value === "yield" && this.inGeneratorContext()) + { allowed = true; } + } + this.exprAllowed = allowed; +}; + +// A recursive descent parser operates by defining functions for all +// syntactic elements, and recursively calling those, each function +// advancing the input stream and returning an AST node. Precedence +// of constructs (for example, the fact that `!x[1]` means `!(x[1])` +// instead of `(!x)[1]` is handled by the fact that the parser +// function that parses unary prefix operators is called first, and +// in turn calls the function that parses `[]` subscripts — that +// way, it'll receive the node for `x[1]` already parsed, and wraps +// *that* in the unary operator node. +// +// Acorn uses an [operator precedence parser][opp] to handle binary +// operator precedence, because it is much more compact than using +// the technique outlined above, which uses different, nesting +// functions to specify precedence, for all of the ten binary +// precedence levels that JavaScript defines. +// +// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + + +var pp$5 = Parser$1.prototype; + +// Check if property name clashes with already added. +// Object/class getters and setters are not allowed to clash — +// either with each other or with an init property — and in +// strict mode, init properties are also not allowed to be repeated. + +pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) { + if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") + { return } + if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) + { return } + var key = prop.key; + var name; + switch (key.type) { + case "Identifier": name = key.name; break + case "Literal": name = String(key.value); break + default: return + } + var kind = prop.kind; + if (this.options.ecmaVersion >= 6) { + if (name === "__proto__" && kind === "init") { + if (propHash.proto) { + if (refDestructuringErrors) { + if (refDestructuringErrors.doubleProto < 0) { + refDestructuringErrors.doubleProto = key.start; + } + } else { + this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); + } + } + propHash.proto = true; + } + return + } + name = "$" + name; + var other = propHash[name]; + if (other) { + var redefinition; + if (kind === "init") { + redefinition = this.strict && other.init || other.get || other.set; + } else { + redefinition = other.init || other[kind]; + } + if (redefinition) + { this.raiseRecoverable(key.start, "Redefinition of property"); } + } else { + other = propHash[name] = { + init: false, + get: false, + set: false + }; + } + other[kind] = true; +}; + +// ### Expression parsing + +// These nest, from the most general expression type at the top to +// 'atomic', nondivisible expression types at the bottom. Most of +// the functions will simply let the function(s) below them parse, +// and, *if* the syntactic construct they handle is present, wrap +// the AST node that the inner parser gave them in another node. + +// Parse a full expression. The optional arguments are used to +// forbid the `in` operator (in for loops initalization expressions) +// and provide reference for storing '=' operator inside shorthand +// property assignment in contexts where both object expression +// and object pattern might appear (so it's possible to raise +// delayed syntax error at correct position). + +pp$5.parseExpression = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); + if (this.type === types$1.comma) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } + return this.finishNode(node, "SequenceExpression") + } + return expr +}; + +// Parse an assignment expression. This includes applications of +// operators like `+=`. + +pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { + if (this.isContextual("yield")) { + if (this.inGenerator) { return this.parseYield(forInit) } + // The tokenizer will assume an expression is allowed after + // `yield`, but this isn't that kind of yield + else { this.exprAllowed = false; } + } + + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + oldDoubleProto = refDestructuringErrors.doubleProto; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; + } else { + refDestructuringErrors = new DestructuringErrors; + ownDestructuringErrors = true; + } + + var startPos = this.start, startLoc = this.startLoc; + if (this.type === types$1.parenL || this.type === types$1.name) { + this.potentialArrowAt = this.start; + this.potentialArrowInForAwait = forInit === "await"; + } + var left = this.parseMaybeConditional(forInit, refDestructuringErrors); + if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } + if (this.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.value; + if (this.type === types$1.eq) + { left = this.toAssignable(left, false, refDestructuringErrors); } + if (!ownDestructuringErrors) { + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; + } + if (refDestructuringErrors.shorthandAssign >= left.start) + { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly + if (this.type === types$1.eq) + { this.checkLValPattern(left); } + else + { this.checkLValSimple(left); } + node.left = left; + this.next(); + node.right = this.parseMaybeAssign(forInit); + if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; } + return this.finishNode(node, "AssignmentExpression") + } else { + if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } + } + if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } + if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } + return left +}; + +// Parse a ternary conditional (`?:`) operator. + +pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprOps(forInit, refDestructuringErrors); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + if (this.eat(types$1.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(types$1.colon); + node.alternate = this.parseMaybeAssign(forInit); + return this.finishNode(node, "ConditionalExpression") + } + return expr +}; + +// Start the precedence parser. + +pp$5.parseExprOps = function(forInit, refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) +}; + +// Parse binary operators with the operator precedence parsing +// algorithm. `left` is the left-hand side of the operator. +// `minPrec` provides context that allows the function to stop and +// defer further parser to one of its callers when it encounters an +// operator that has a lower precedence than the set it is parsing. + +pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { + var prec = this.type.binop; + if (prec != null && (!forInit || this.type !== types$1._in)) { + if (prec > minPrec) { + var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND; + var coalesce = this.type === types$1.coalesce; + if (coalesce) { + // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. + // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. + prec = types$1.logicalAND.binop; + } + var op = this.value; + this.next(); + var startPos = this.start, startLoc = this.startLoc; + var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); + var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); + if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) { + this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); + } + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) + } + } + return left +}; + +pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) { + if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); } + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.operator = op; + node.right = right; + return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") +}; + +// Parse unary operators, both prefix and postfix. + +pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { + var startPos = this.start, startLoc = this.startLoc, expr; + if (this.isContextual("await") && this.canAwait) { + expr = this.parseAwait(forInit); + sawUnary = true; + } else if (this.type.prefix) { + var node = this.startNode(), update = this.type === types$1.incDec; + node.operator = this.value; + node.prefix = true; + this.next(); + node.argument = this.parseMaybeUnary(null, true, update, forInit); + this.checkExpressionErrors(refDestructuringErrors, true); + if (update) { this.checkLValSimple(node.argument); } + else if (this.strict && node.operator === "delete" && + node.argument.type === "Identifier") + { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } + else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) + { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } + else { sawUnary = true; } + expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } else if (!sawUnary && this.type === types$1.privateId) { + if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); } + expr = this.parsePrivateIdent(); + // only could be private fields in 'in', such as #x in obj + if (this.type !== types$1._in) { this.unexpected(); } + } else { + expr = this.parseExprSubscripts(refDestructuringErrors, forInit); + if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } + while (this.type.postfix && !this.canInsertSemicolon()) { + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.operator = this.value; + node$1.prefix = false; + node$1.argument = expr; + this.checkLValSimple(expr); + this.next(); + expr = this.finishNode(node$1, "UpdateExpression"); + } + } + + if (!incDec && this.eat(types$1.starstar)) { + if (sawUnary) + { this.unexpected(this.lastTokStart); } + else + { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } + } else { + return expr + } +}; + +function isPrivateFieldAccess(node) { + return ( + node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || + node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) + ) +} + +// Parse call, dot, and `[]`-subscript expressions. + +pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors, forInit); + if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") + { return expr } + var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); + if (refDestructuringErrors && result.type === "MemberExpression") { + if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } + if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } + if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } + } + return result +}; + +pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { + var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && + this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && + this.potentialArrowAt === base.start; + var optionalChained = false; + + while (true) { + var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); + + if (element.optional) { optionalChained = true; } + if (element === base || element.type === "ArrowFunctionExpression") { + if (optionalChained) { + var chainNode = this.startNodeAt(startPos, startLoc); + chainNode.expression = element; + element = this.finishNode(chainNode, "ChainExpression"); + } + return element + } + + base = element; + } +}; + +pp$5.shouldParseAsyncArrow = function() { + return !this.canInsertSemicolon() && this.eat(types$1.arrow) +}; + +pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) +}; + +pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { + var optionalSupported = this.options.ecmaVersion >= 11; + var optional = optionalSupported && this.eat(types$1.questionDot); + if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } + + var computed = this.eat(types$1.bracketL); + if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + if (computed) { + node.property = this.parseExpression(); + this.expect(types$1.bracketR); + } else if (this.type === types$1.privateId && base.type !== "Super") { + node.property = this.parsePrivateIdent(); + } else { + node.property = this.parseIdent(this.options.allowReserved !== "never"); + } + node.computed = !!computed; + if (optionalSupported) { + node.optional = optional; + } + base = this.finishNode(node, "MemberExpression"); + } else if (!noCalls && this.eat(types$1.parenL)) { + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); + if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + if (this.awaitIdentPos > 0) + { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit) + } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; + var node$1 = this.startNodeAt(startPos, startLoc); + node$1.callee = base; + node$1.arguments = exprList; + if (optionalSupported) { + node$1.optional = optional; + } + base = this.finishNode(node$1, "CallExpression"); + } else if (this.type === types$1.backQuote) { + if (optional || optionalChained) { + this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); + } + var node$2 = this.startNodeAt(startPos, startLoc); + node$2.tag = base; + node$2.quasi = this.parseTemplate({isTagged: true}); + base = this.finishNode(node$2, "TaggedTemplateExpression"); + } + return base +}; + +// Parse an atomic expression — either a single token that is an +// expression, an expression started by a keyword like `function` or +// `new`, or an expression wrapped in punctuation like `()`, `[]`, +// or `{}`. + +pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) { + // If a division operator appears in an expression position, the + // tokenizer got confused, and we force it to read a regexp instead. + if (this.type === types$1.slash) { this.readRegexp(); } + + var node, canBeArrow = this.potentialArrowAt === this.start; + switch (this.type) { + case types$1._super: + if (!this.allowSuper) + { this.raise(this.start, "'super' keyword outside a method"); } + node = this.startNode(); + this.next(); + if (this.type === types$1.parenL && !this.allowDirectSuper) + { this.raise(node.start, "super() call outside constructor of a subclass"); } + // The `super` keyword can appear at below: + // SuperProperty: + // super [ Expression ] + // super . IdentifierName + // SuperCall: + // super ( Arguments ) + if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) + { this.unexpected(); } + return this.finishNode(node, "Super") + + case types$1._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression") + + case types$1.name: + var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; + var id = this.parseIdent(false); + if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) { + this.overrideContext(types$2.f_expr); + return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) + } + if (canBeArrow && !this.canInsertSemicolon()) { + if (this.eat(types$1.arrow)) + { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } + if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && + (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { + id = this.parseIdent(false); + if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) + { this.unexpected(); } + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) + } + } + return id + + case types$1.regexp: + var value = this.value; + node = this.parseLiteral(value.value); + node.regex = {pattern: value.pattern, flags: value.flags}; + return node + + case types$1.num: case types$1.string: + return this.parseLiteral(this.value) + + case types$1._null: case types$1._true: case types$1._false: + node = this.startNode(); + node.value = this.type === types$1._null ? null : this.type === types$1._true; + node.raw = this.type.keyword; + this.next(); + return this.finishNode(node, "Literal") + + case types$1.parenL: + var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); + if (refDestructuringErrors) { + if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) + { refDestructuringErrors.parenthesizedAssign = start; } + if (refDestructuringErrors.parenthesizedBind < 0) + { refDestructuringErrors.parenthesizedBind = start; } + } + return expr + + case types$1.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node, "ArrayExpression") + + case types$1.braceL: + this.overrideContext(types$2.b_expr); + return this.parseObj(false, refDestructuringErrors) + + case types$1._function: + node = this.startNode(); + this.next(); + return this.parseFunction(node, 0) + + case types$1._class: + return this.parseClass(this.startNode(), false) + + case types$1._new: + return this.parseNew() + + case types$1.backQuote: + return this.parseTemplate() + + case types$1._import: + if (this.options.ecmaVersion >= 11) { + return this.parseExprImport(forNew) + } else { + return this.unexpected() + } + + default: + return this.parseExprAtomDefault() + } +}; + +pp$5.parseExprAtomDefault = function() { + this.unexpected(); +}; + +pp$5.parseExprImport = function(forNew) { + var node = this.startNode(); + + // Consume `import` as an identifier for `import.meta`. + // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } + var meta = this.parseIdent(true); + + if (this.type === types$1.parenL && !forNew) { + return this.parseDynamicImport(node) + } else if (this.type === types$1.dot) { + node.meta = meta; + return this.parseImportMeta(node) + } else { + this.unexpected(); + } +}; + +pp$5.parseDynamicImport = function(node) { + this.next(); // skip `(` + + // Parse node.source. + node.source = this.parseMaybeAssign(); + + // Verify ending. + if (!this.eat(types$1.parenR)) { + var errorPos = this.start; + if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { + this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); + } else { + this.unexpected(errorPos); + } + } + + return this.finishNode(node, "ImportExpression") +}; + +pp$5.parseImportMeta = function(node) { + this.next(); // skip `.` + + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + + if (node.property.name !== "meta") + { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } + if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) + { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } + + return this.finishNode(node, "MetaProperty") +}; + +pp$5.parseLiteral = function(value) { + var node = this.startNode(); + node.value = value; + node.raw = this.input.slice(this.start, this.end); + if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } + this.next(); + return this.finishNode(node, "Literal") +}; + +pp$5.parseParenExpression = function() { + this.expect(types$1.parenL); + var val = this.parseExpression(); + this.expect(types$1.parenR); + return val +}; + +pp$5.shouldParseArrow = function(exprList) { + return !this.canInsertSemicolon() +}; + +pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { + var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; + if (this.options.ecmaVersion >= 6) { + this.next(); + + var innerStartPos = this.start, innerStartLoc = this.startLoc; + var exprList = [], first = true, lastIsComma = false; + var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; + this.yieldPos = 0; + this.awaitPos = 0; + // Do not save awaitIdentPos to allow checking awaits nested in parameters + while (this.type !== types$1.parenR) { + first ? first = false : this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { + lastIsComma = true; + break + } else if (this.type === types$1.ellipsis) { + spreadStart = this.start; + exprList.push(this.parseParenItem(this.parseRestBinding())); + if (this.type === types$1.comma) { + this.raiseRecoverable( + this.start, + "Comma is not permitted after the rest element" + ); + } + break + } else { + exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); + } + } + var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; + this.expect(types$1.parenR); + + if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) { + this.checkPatternErrors(refDestructuringErrors, false); + this.checkYieldAwaitInDefaultParams(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + return this.parseParenArrowList(startPos, startLoc, exprList, forInit) + } + + if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } + if (spreadStart) { this.unexpected(spreadStart); } + this.checkExpressionErrors(refDestructuringErrors, true); + this.yieldPos = oldYieldPos || this.yieldPos; + this.awaitPos = oldAwaitPos || this.awaitPos; + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + } else { + val = this.parseParenExpression(); + } + + if (this.options.preserveParens) { + var par = this.startNodeAt(startPos, startLoc); + par.expression = val; + return this.finishNode(par, "ParenthesizedExpression") + } else { + return val + } +}; + +pp$5.parseParenItem = function(item) { + return item +}; + +pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { + return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit) +}; + +// New's precedence is slightly tricky. It must allow its argument to +// be a `[]` or dot subscript expression, but not a call — at least, +// not without wrapping it in parentheses. Thus, it uses the noCalls +// argument to parseSubscripts to prevent it from consuming the +// argument list. + +var empty = []; + +pp$5.parseNew = function() { + if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } + var node = this.startNode(); + this.next(); + if (this.options.ecmaVersion >= 6 && this.type === types$1.dot) { + var meta = this.startNodeAt(node.start, node.startLoc); + meta.name = "new"; + node.meta = this.finishNode(meta, "Identifier"); + this.next(); + var containsEsc = this.containsEsc; + node.property = this.parseIdent(true); + if (node.property.name !== "target") + { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } + if (containsEsc) + { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } + if (!this.allowNewDotTarget) + { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } + return this.finishNode(node, "MetaProperty") + } + var startPos = this.start, startLoc = this.startLoc; + node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false); + if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); } + else { node.arguments = empty; } + return this.finishNode(node, "NewExpression") +}; + +// Parse template expression. + +pp$5.parseTemplateElement = function(ref) { + var isTagged = ref.isTagged; + + var elem = this.startNode(); + if (this.type === types$1.invalidTemplate) { + if (!isTagged) { + this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); + } + elem.value = { + raw: this.value, + cooked: null + }; + } else { + elem.value = { + raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), + cooked: this.value + }; + } + this.next(); + elem.tail = this.type === types$1.backQuote; + return this.finishNode(elem, "TemplateElement") +}; + +pp$5.parseTemplate = function(ref) { + if ( ref === void 0 ) ref = {}; + var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; + + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement({isTagged: isTagged}); + node.quasis = [curElt]; + while (!curElt.tail) { + if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); } + this.expect(types$1.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(types$1.braceR); + node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); + } + this.next(); + return this.finishNode(node, "TemplateLiteral") +}; + +pp$5.isAsyncProp = function(prop) { + return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && + (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) && + !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) +}; + +// Parse an object literal or binding pattern. + +pp$5.parseObj = function(isPattern, refDestructuringErrors) { + var node = this.startNode(), first = true, propHash = {}; + node.properties = []; + this.next(); + while (!this.eat(types$1.braceR)) { + if (!first) { + this.expect(types$1.comma); + if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break } + } else { first = false; } + + var prop = this.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } + node.properties.push(prop); + } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") +}; + +pp$5.parseProperty = function(isPattern, refDestructuringErrors) { + var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; + if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { + if (isPattern) { + prop.argument = this.parseIdent(false); + if (this.type === types$1.comma) { + this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); + } + return this.finishNode(prop, "RestElement") + } + // Parse argument. + prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); + // To disallow trailing comma via `this.toAssignable()`. + if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { + refDestructuringErrors.trailingComma = this.start; + } + // Finish + return this.finishNode(prop, "SpreadElement") + } + if (this.options.ecmaVersion >= 6) { + prop.method = false; + prop.shorthand = false; + if (isPattern || refDestructuringErrors) { + startPos = this.start; + startLoc = this.startLoc; + } + if (!isPattern) + { isGenerator = this.eat(types$1.star); } + } + var containsEsc = this.containsEsc; + this.parsePropertyName(prop); + if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { + isAsync = true; + isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star); + this.parsePropertyName(prop); + } else { + isAsync = false; + } + this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); + return this.finishNode(prop, "Property") +}; + +pp$5.parseGetterSetter = function(prop) { + prop.kind = prop.key.name; + this.parsePropertyName(prop); + prop.value = this.parseMethod(false); + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.value.params.length !== paramCount) { + var start = prop.value.start; + if (prop.kind === "get") + { this.raiseRecoverable(start, "getter should have no params"); } + else + { this.raiseRecoverable(start, "setter should have exactly one param"); } + } else { + if (prop.kind === "set" && prop.value.params[0].type === "RestElement") + { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } + } +}; + +pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types$1.colon) + { this.unexpected(); } + + if (this.eat(types$1.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); + prop.kind = "init"; + } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) { + if (isPattern) { this.unexpected(); } + prop.kind = "init"; + prop.method = true; + prop.value = this.parseMethod(isGenerator, isAsync); + } else if (!isPattern && !containsEsc && + this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set") && + (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { + if (isGenerator || isAsync) { this.unexpected(); } + this.parseGetterSetter(prop); + } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { + if (isGenerator || isAsync) { this.unexpected(); } + this.checkUnreserved(prop.key); + if (prop.key.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = startPos; } + prop.kind = "init"; + if (isPattern) { + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else if (this.type === types$1.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) + { refDestructuringErrors.shorthandAssign = this.start; } + prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); + } else { + prop.value = this.copyNode(prop.key); + } + prop.shorthand = true; + } else { this.unexpected(); } +}; + +pp$5.parsePropertyName = function(prop) { + if (this.options.ecmaVersion >= 6) { + if (this.eat(types$1.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(types$1.bracketR); + return prop.key + } else { + prop.computed = false; + } + } + return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") +}; + +// Initialize empty function node. + +pp$5.initFunction = function(node) { + node.id = null; + if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } + if (this.options.ecmaVersion >= 8) { node.async = false; } +}; + +// Parse object or class method. + +pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { + var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.initFunction(node); + if (this.options.ecmaVersion >= 6) + { node.generator = isGenerator; } + if (this.options.ecmaVersion >= 8) + { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); + + this.expect(types$1.parenL); + node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false, true, false); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression") +}; + +// Parse arrow function expression with given parameters. + +pp$5.parseArrowExpression = function(node, params, isAsync, forInit) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; + + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node); + if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } + + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + + node.params = this.toAssignableList(params, true); + this.parseFunctionBody(node, true, false, forInit); + + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression") +}; + +// Parse function body and check parameters. + +pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { + var isExpression = isArrowFunction && this.type !== types$1.braceL; + var oldStrict = this.strict, useStrict = false; + + if (isExpression) { + node.body = this.parseMaybeAssign(forInit); + node.expression = true; + this.checkParams(node, false); + } else { + var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); + if (!oldStrict || nonSimple) { + useStrict = this.strictDirective(this.end); + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + if (useStrict && nonSimple) + { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } + } + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldLabels = this.labels; + this.labels = []; + if (useStrict) { this.strict = true; } + + // Add the params to varDeclaredNames to ensure that an error is thrown + // if a let/const declaration in the function clashes with one of the params. + this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); + // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' + if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } + node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; + } + this.exitScope(); +}; + +pp$5.isSimpleParamList = function(params) { + for (var i = 0, list = params; i < list.length; i += 1) + { + var param = list[i]; + + if (param.type !== "Identifier") { return false + } } + return true +}; + +// Checks function params for various disallowed patterns such as using "eval" +// or "arguments" and duplicate parameters. + +pp$5.checkParams = function(node, allowDuplicates) { + var nameHash = Object.create(null); + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; + + this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); + } +}; + +// Parses a comma-separated list of expressions, and returns them as +// an array. `close` is the token type that ends the list, and +// `allowEmpty` can be turned on to allow subsequent commas with +// nothing in between them to be parsed as `null` (which is needed +// for array literals). + +pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { + var elts = [], first = true; + while (!this.eat(close)) { + if (!first) { + this.expect(types$1.comma); + if (allowTrailingComma && this.afterTrailingComma(close)) { break } + } else { first = false; } + + var elt = (void 0); + if (allowEmpty && this.type === types$1.comma) + { elt = null; } + else if (this.type === types$1.ellipsis) { + elt = this.parseSpread(refDestructuringErrors); + if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) + { refDestructuringErrors.trailingComma = this.start; } + } else { + elt = this.parseMaybeAssign(false, refDestructuringErrors); + } + elts.push(elt); + } + return elts +}; + +pp$5.checkUnreserved = function(ref) { + var start = ref.start; + var end = ref.end; + var name = ref.name; + + if (this.inGenerator && name === "yield") + { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } + if (this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } + if (this.currentThisScope().inClassFieldInit && name === "arguments") + { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } + if (this.inClassStaticBlock && (name === "arguments" || name === "await")) + { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } + if (this.keywords.test(name)) + { this.raise(start, ("Unexpected keyword '" + name + "'")); } + if (this.options.ecmaVersion < 6 && + this.input.slice(start, end).indexOf("\\") !== -1) { return } + var re = this.strict ? this.reservedWordsStrict : this.reservedWords; + if (re.test(name)) { + if (!this.inAsync && name === "await") + { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } + this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); + } +}; + +// Parse the next token as an identifier. If `liberal` is true (used +// when parsing properties), it will also convert keywords into +// identifiers. + +pp$5.parseIdent = function(liberal) { + var node = this.parseIdentNode(); + this.next(!!liberal); + this.finishNode(node, "Identifier"); + if (!liberal) { + this.checkUnreserved(node); + if (node.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = node.start; } + } + return node +}; + +pp$5.parseIdentNode = function() { + var node = this.startNode(); + if (this.type === types$1.name) { + node.name = this.value; + } else if (this.type.keyword) { + node.name = this.type.keyword; + + // To fix https://github.com/acornjs/acorn/issues/575 + // `class` and `function` keywords push new context into this.context. + // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. + // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword + if ((node.name === "class" || node.name === "function") && + (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { + this.context.pop(); + } + this.type = types$1.name; + } else { + this.unexpected(); + } + return node +}; + +pp$5.parsePrivateIdent = function() { + var node = this.startNode(); + if (this.type === types$1.privateId) { + node.name = this.value; + } else { + this.unexpected(); + } + this.next(); + this.finishNode(node, "PrivateIdentifier"); + + // For validating existence + if (this.options.checkPrivateFields) { + if (this.privateNameStack.length === 0) { + this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); + } else { + this.privateNameStack[this.privateNameStack.length - 1].used.push(node); + } + } + + return node +}; + +// Parses yield expression inside generator. + +pp$5.parseYield = function(forInit) { + if (!this.yieldPos) { this.yieldPos = this.start; } + + var node = this.startNode(); + this.next(); + if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(types$1.star); + node.argument = this.parseMaybeAssign(forInit); + } + return this.finishNode(node, "YieldExpression") +}; + +pp$5.parseAwait = function(forInit) { + if (!this.awaitPos) { this.awaitPos = this.start; } + + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true, false, forInit); + return this.finishNode(node, "AwaitExpression") +}; + +var pp$4 = Parser$1.prototype; + +// This function is used to raise exceptions on parse errors. It +// takes an offset integer (into the current `input`) to indicate +// the location of the error, attaches the position to the end +// of the error message, and then raises a `SyntaxError` with that +// message. + +pp$4.raise = function(pos, message) { + var loc = getLineInfo(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + var err = new SyntaxError(message); + err.pos = pos; err.loc = loc; err.raisedAt = this.pos; + throw err +}; + +pp$4.raiseRecoverable = pp$4.raise; + +pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) + } +}; + +var pp$3 = Parser$1.prototype; + +var Scope = function Scope(flags) { + this.flags = flags; + // A list of var-declared names in the current lexical scope + this.var = []; + // A list of lexically-declared names in the current lexical scope + this.lexical = []; + // A list of lexically-declared FunctionDeclaration names in the current lexical scope + this.functions = []; + // A switch to disallow the identifier reference 'arguments' + this.inClassFieldInit = false; +}; + +// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. + +pp$3.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); +}; + +pp$3.exitScope = function() { + this.scopeStack.pop(); +}; + +// The spec says: +// > At the top level of a function, or script, function declarations are +// > treated like var declarations rather than like lexical declarations. +pp$3.treatFunctionsAsVarInScope = function(scope) { + return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) +}; + +pp$3.declareName = function(name, bindingType, pos) { + var redeclared = false; + if (bindingType === BIND_LEXICAL) { + var scope = this.currentScope(); + redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; + scope.lexical.push(name); + if (this.inModule && (scope.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + } else if (bindingType === BIND_SIMPLE_CATCH) { + var scope$1 = this.currentScope(); + scope$1.lexical.push(name); + } else if (bindingType === BIND_FUNCTION) { + var scope$2 = this.currentScope(); + if (this.treatFunctionsAsVar) + { redeclared = scope$2.lexical.indexOf(name) > -1; } + else + { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } + scope$2.functions.push(name); + } else { + for (var i = this.scopeStack.length - 1; i >= 0; --i) { + var scope$3 = this.scopeStack[i]; + if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || + !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { + redeclared = true; + break + } + scope$3.var.push(name); + if (this.inModule && (scope$3.flags & SCOPE_TOP)) + { delete this.undefinedExports[name]; } + if (scope$3.flags & SCOPE_VAR) { break } + } + } + if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } +}; + +pp$3.checkLocalExport = function(id) { + // scope.functions must be empty as Module code is always strict. + if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && + this.scopeStack[0].var.indexOf(id.name) === -1) { + this.undefinedExports[id.name] = id; + } +}; + +pp$3.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1] +}; + +pp$3.currentVarScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR) { return scope } + } +}; + +// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. +pp$3.currentThisScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } + } +}; + +var Node = function Node(parser, pos, loc) { + this.type = ""; + this.start = pos; + this.end = 0; + if (parser.options.locations) + { this.loc = new SourceLocation(parser, loc); } + if (parser.options.directSourceFile) + { this.sourceFile = parser.options.directSourceFile; } + if (parser.options.ranges) + { this.range = [pos, 0]; } +}; + +// Start an AST node, attaching a start offset. + +var pp$2 = Parser$1.prototype; + +pp$2.startNode = function() { + return new Node(this, this.start, this.startLoc) +}; + +pp$2.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc) +}; + +// Finish an AST node, adding `type` and `end` properties. + +function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + if (this.options.locations) + { node.loc.end = loc; } + if (this.options.ranges) + { node.range[1] = pos; } + return node +} + +pp$2.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) +}; + +// Finish node at given position + +pp$2.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) +}; + +pp$2.copyNode = function(node) { + var newNode = new Node(this, node.start, this.startLoc); + for (var prop in node) { newNode[prop] = node[prop]; } + return newNode +}; + +// This file contains Unicode properties extracted from the ECMAScript specification. +// The lists are extracted like so: +// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) + +// #table-binary-unicode-properties +var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; +var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; +var ecma11BinaryProperties = ecma10BinaryProperties; +var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; +var ecma13BinaryProperties = ecma12BinaryProperties; +var ecma14BinaryProperties = ecma13BinaryProperties; + +var unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties, + 12: ecma12BinaryProperties, + 13: ecma13BinaryProperties, + 14: ecma14BinaryProperties +}; + +// #table-binary-unicode-properties-of-strings +var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"; + +var unicodeBinaryPropertiesOfStrings = { + 9: "", + 10: "", + 11: "", + 12: "", + 13: "", + 14: ecma14BinaryPropertiesOfStrings +}; + +// #table-unicode-general-category-values +var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; + +// #table-unicode-script-values +var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; +var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; +var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; +var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; +var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; +var ecma14ScriptValues = ecma13ScriptValues + " Hrkt Katakana_Or_Hiragana Kawi Nag_Mundari Nagm Unknown Zzzz"; + +var unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues, + 12: ecma12ScriptValues, + 13: ecma13ScriptValues, + 14: ecma14ScriptValues +}; + +var data = {}; +function buildUnicodeData(ecmaVersion) { + var d = data[ecmaVersion] = { + binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), + binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]), + nonBinary: { + General_Category: wordsRegexp(unicodeGeneralCategoryValues), + Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) + } + }; + d.nonBinary.Script_Extensions = d.nonBinary.Script; + + d.nonBinary.gc = d.nonBinary.General_Category; + d.nonBinary.sc = d.nonBinary.Script; + d.nonBinary.scx = d.nonBinary.Script_Extensions; +} + +for (var i$1 = 0, list = [9, 10, 11, 12, 13, 14]; i$1 < list.length; i$1 += 1) { + var ecmaVersion = list[i$1]; + + buildUnicodeData(ecmaVersion); +} + +var pp$1 = Parser$1.prototype; + +var RegExpValidationState = function RegExpValidationState(parser) { + this.parser = parser; + this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : ""); + this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion]; + this.source = ""; + this.flags = ""; + this.start = 0; + this.switchU = false; + this.switchV = false; + this.switchN = false; + this.pos = 0; + this.lastIntValue = 0; + this.lastStringValue = ""; + this.lastAssertionIsQuantifiable = false; + this.numCapturingParens = 0; + this.maxBackReference = 0; + this.groupNames = []; + this.backReferenceNames = []; +}; + +RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { + var unicodeSets = flags.indexOf("v") !== -1; + var unicode = flags.indexOf("u") !== -1; + this.start = start | 0; + this.source = pattern + ""; + this.flags = flags; + if (unicodeSets && this.parser.options.ecmaVersion >= 15) { + this.switchU = true; + this.switchV = true; + this.switchN = true; + } else { + this.switchU = unicode && this.parser.options.ecmaVersion >= 6; + this.switchV = false; + this.switchN = unicode && this.parser.options.ecmaVersion >= 9; + } +}; + +RegExpValidationState.prototype.raise = function raise (message) { + this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); +}; + +// If u flag is given, this returns the code point at the index (it combines a surrogate pair). +// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). +RegExpValidationState.prototype.at = function at (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return -1 + } + var c = s.charCodeAt(i); + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { + return c + } + var next = s.charCodeAt(i + 1); + return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c +}; + +RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { + if ( forceU === void 0 ) forceU = false; + + var s = this.source; + var l = s.length; + if (i >= l) { + return l + } + var c = s.charCodeAt(i), next; + if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || + (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { + return i + 1 + } + return i + 2 +}; + +RegExpValidationState.prototype.current = function current (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.pos, forceU) +}; + +RegExpValidationState.prototype.lookahead = function lookahead (forceU) { + if ( forceU === void 0 ) forceU = false; + + return this.at(this.nextIndex(this.pos, forceU), forceU) +}; + +RegExpValidationState.prototype.advance = function advance (forceU) { + if ( forceU === void 0 ) forceU = false; + + this.pos = this.nextIndex(this.pos, forceU); +}; + +RegExpValidationState.prototype.eat = function eat (ch, forceU) { + if ( forceU === void 0 ) forceU = false; + + if (this.current(forceU) === ch) { + this.advance(forceU); + return true + } + return false +}; + +RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) { + if ( forceU === void 0 ) forceU = false; + + var pos = this.pos; + for (var i = 0, list = chs; i < list.length; i += 1) { + var ch = list[i]; + + var current = this.at(pos, forceU); + if (current === -1 || current !== ch) { + return false + } + pos = this.nextIndex(pos, forceU); + } + this.pos = pos; + return true +}; + +/** + * Validate the flags part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ +pp$1.validateRegExpFlags = function(state) { + var validFlags = state.validFlags; + var flags = state.flags; + + var u = false; + var v = false; + + for (var i = 0; i < flags.length; i++) { + var flag = flags.charAt(i); + if (validFlags.indexOf(flag) === -1) { + this.raise(state.start, "Invalid regular expression flag"); + } + if (flags.indexOf(flag, i + 1) > -1) { + this.raise(state.start, "Duplicate regular expression flag"); + } + if (flag === "u") { u = true; } + if (flag === "v") { v = true; } + } + if (this.options.ecmaVersion >= 15 && u && v) { + this.raise(state.start, "Invalid regular expression flag"); + } +}; + +/** + * Validate the pattern part of a given RegExpLiteral. + * + * @param {RegExpValidationState} state The state to validate RegExp. + * @returns {void} + */ +pp$1.validateRegExpPattern = function(state) { + this.regexp_pattern(state); + + // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of + // parsing contains a |GroupName|, reparse with the goal symbol + // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* + // exception if _P_ did not conform to the grammar, if any elements of _P_ + // were not matched by the parse, or if any Early Error conditions exist. + if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { + state.switchN = true; + this.regexp_pattern(state); + } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern +pp$1.regexp_pattern = function(state) { + state.pos = 0; + state.lastIntValue = 0; + state.lastStringValue = ""; + state.lastAssertionIsQuantifiable = false; + state.numCapturingParens = 0; + state.maxBackReference = 0; + state.groupNames.length = 0; + state.backReferenceNames.length = 0; + + this.regexp_disjunction(state); + + if (state.pos !== state.source.length) { + // Make the same messages as V8. + if (state.eat(0x29 /* ) */)) { + state.raise("Unmatched ')'"); + } + if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { + state.raise("Lone quantifier brackets"); + } + } + if (state.maxBackReference > state.numCapturingParens) { + state.raise("Invalid escape"); + } + for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { + var name = list[i]; + + if (state.groupNames.indexOf(name) === -1) { + state.raise("Invalid named capture referenced"); + } + } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction +pp$1.regexp_disjunction = function(state) { + this.regexp_alternative(state); + while (state.eat(0x7C /* | */)) { + this.regexp_alternative(state); + } + + // Make the same message as V8. + if (this.regexp_eatQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + if (state.eat(0x7B /* { */)) { + state.raise("Lone quantifier brackets"); + } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative +pp$1.regexp_alternative = function(state) { + while (state.pos < state.source.length && this.regexp_eatTerm(state)) + { } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term +pp$1.regexp_eatTerm = function(state) { + if (this.regexp_eatAssertion(state)) { + // Handle `QuantifiableAssertion Quantifier` alternative. + // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion + // is a QuantifiableAssertion. + if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { + // Make the same message as V8. + if (state.switchU) { + state.raise("Invalid quantifier"); + } + } + return true + } + + if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { + this.regexp_eatQuantifier(state); + return true + } + + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion +pp$1.regexp_eatAssertion = function(state) { + var start = state.pos; + state.lastAssertionIsQuantifiable = false; + + // ^, $ + if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { + return true + } + + // \b \B + if (state.eat(0x5C /* \ */)) { + if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { + return true + } + state.pos = start; + } + + // Lookahead / Lookbehind + if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { + var lookbehind = false; + if (this.options.ecmaVersion >= 9) { + lookbehind = state.eat(0x3C /* < */); + } + if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { + this.regexp_disjunction(state); + if (!state.eat(0x29 /* ) */)) { + state.raise("Unterminated group"); + } + state.lastAssertionIsQuantifiable = !lookbehind; + return true + } + } + + state.pos = start; + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier +pp$1.regexp_eatQuantifier = function(state, noError) { + if ( noError === void 0 ) noError = false; + + if (this.regexp_eatQuantifierPrefix(state, noError)) { + state.eat(0x3F /* ? */); + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix +pp$1.regexp_eatQuantifierPrefix = function(state, noError) { + return ( + state.eat(0x2A /* * */) || + state.eat(0x2B /* + */) || + state.eat(0x3F /* ? */) || + this.regexp_eatBracedQuantifier(state, noError) + ) +}; +pp$1.regexp_eatBracedQuantifier = function(state, noError) { + var start = state.pos; + if (state.eat(0x7B /* { */)) { + var min = 0, max = -1; + if (this.regexp_eatDecimalDigits(state)) { + min = state.lastIntValue; + if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { + max = state.lastIntValue; + } + if (state.eat(0x7D /* } */)) { + // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term + if (max !== -1 && max < min && !noError) { + state.raise("numbers out of order in {} quantifier"); + } + return true + } + } + if (state.switchU && !noError) { + state.raise("Incomplete quantifier"); + } + state.pos = start; + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom +pp$1.regexp_eatAtom = function(state) { + return ( + this.regexp_eatPatternCharacters(state) || + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) + ) +}; +pp$1.regexp_eatReverseSolidusAtomEscape = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatAtomEscape(state)) { + return true + } + state.pos = start; + } + return false +}; +pp$1.regexp_eatUncapturingGroup = function(state) { + var start = state.pos; + if (state.eat(0x28 /* ( */)) { + if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + return true + } + state.raise("Unterminated group"); + } + state.pos = start; + } + return false +}; +pp$1.regexp_eatCapturingGroup = function(state) { + if (state.eat(0x28 /* ( */)) { + if (this.options.ecmaVersion >= 9) { + this.regexp_groupSpecifier(state); + } else if (state.current() === 0x3F /* ? */) { + state.raise("Invalid group"); + } + this.regexp_disjunction(state); + if (state.eat(0x29 /* ) */)) { + state.numCapturingParens += 1; + return true + } + state.raise("Unterminated group"); + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom +pp$1.regexp_eatExtendedAtom = function(state) { + return ( + state.eat(0x2E /* . */) || + this.regexp_eatReverseSolidusAtomEscape(state) || + this.regexp_eatCharacterClass(state) || + this.regexp_eatUncapturingGroup(state) || + this.regexp_eatCapturingGroup(state) || + this.regexp_eatInvalidBracedQuantifier(state) || + this.regexp_eatExtendedPatternCharacter(state) + ) +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier +pp$1.regexp_eatInvalidBracedQuantifier = function(state) { + if (this.regexp_eatBracedQuantifier(state, true)) { + state.raise("Nothing to repeat"); + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter +pp$1.regexp_eatSyntaxCharacter = function(state) { + var ch = state.current(); + if (isSyntaxCharacter(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false +}; +function isSyntaxCharacter(ch) { + return ( + ch === 0x24 /* $ */ || + ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || + ch === 0x2E /* . */ || + ch === 0x3F /* ? */ || + ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter +// But eat eager. +pp$1.regexp_eatPatternCharacters = function(state) { + var start = state.pos; + var ch = 0; + while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { + state.advance(); + } + return state.pos !== start +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter +pp$1.regexp_eatExtendedPatternCharacter = function(state) { + var ch = state.current(); + if ( + ch !== -1 && + ch !== 0x24 /* $ */ && + !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && + ch !== 0x2E /* . */ && + ch !== 0x3F /* ? */ && + ch !== 0x5B /* [ */ && + ch !== 0x5E /* ^ */ && + ch !== 0x7C /* | */ + ) { + state.advance(); + return true + } + return false +}; + +// GroupSpecifier :: +// [empty] +// `?` GroupName +pp$1.regexp_groupSpecifier = function(state) { + if (state.eat(0x3F /* ? */)) { + if (this.regexp_eatGroupName(state)) { + if (state.groupNames.indexOf(state.lastStringValue) !== -1) { + state.raise("Duplicate capture group name"); + } + state.groupNames.push(state.lastStringValue); + return + } + state.raise("Invalid group"); + } +}; + +// GroupName :: +// `<` RegExpIdentifierName `>` +// Note: this updates `state.lastStringValue` property with the eaten name. +pp$1.regexp_eatGroupName = function(state) { + state.lastStringValue = ""; + if (state.eat(0x3C /* < */)) { + if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { + return true + } + state.raise("Invalid capture group name"); + } + return false +}; + +// RegExpIdentifierName :: +// RegExpIdentifierStart +// RegExpIdentifierName RegExpIdentifierPart +// Note: this updates `state.lastStringValue` property with the eaten name. +pp$1.regexp_eatRegExpIdentifierName = function(state) { + state.lastStringValue = ""; + if (this.regexp_eatRegExpIdentifierStart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + while (this.regexp_eatRegExpIdentifierPart(state)) { + state.lastStringValue += codePointToString(state.lastIntValue); + } + return true + } + return false +}; + +// RegExpIdentifierStart :: +// UnicodeIDStart +// `$` +// `_` +// `\` RegExpUnicodeEscapeSequence[+U] +pp$1.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false +}; +function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ +} + +// RegExpIdentifierPart :: +// UnicodeIDContinue +// `$` +// `_` +// `\` RegExpUnicodeEscapeSequence[+U] +// +// +pp$1.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var forceU = this.options.ecmaVersion >= 11; + var ch = state.current(forceU); + state.advance(forceU); + + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state.lastIntValue = ch; + return true + } + + state.pos = start; + return false +}; +function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape +pp$1.regexp_eatAtomEscape = function(state) { + if ( + this.regexp_eatBackReference(state) || + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) || + (state.switchN && this.regexp_eatKGroupName(state)) + ) { + return true + } + if (state.switchU) { + // Make the same message as V8. + if (state.current() === 0x63 /* c */) { + state.raise("Invalid unicode escape"); + } + state.raise("Invalid escape"); + } + return false +}; +pp$1.regexp_eatBackReference = function(state) { + var start = state.pos; + if (this.regexp_eatDecimalEscape(state)) { + var n = state.lastIntValue; + if (state.switchU) { + // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape + if (n > state.maxBackReference) { + state.maxBackReference = n; + } + return true + } + if (n <= state.numCapturingParens) { + return true + } + state.pos = start; + } + return false +}; +pp$1.regexp_eatKGroupName = function(state) { + if (state.eat(0x6B /* k */)) { + if (this.regexp_eatGroupName(state)) { + state.backReferenceNames.push(state.lastStringValue); + return true + } + state.raise("Invalid named reference"); + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape +pp$1.regexp_eatCharacterEscape = function(state) { + return ( + this.regexp_eatControlEscape(state) || + this.regexp_eatCControlLetter(state) || + this.regexp_eatZero(state) || + this.regexp_eatHexEscapeSequence(state) || + this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || + (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || + this.regexp_eatIdentityEscape(state) + ) +}; +pp$1.regexp_eatCControlLetter = function(state) { + var start = state.pos; + if (state.eat(0x63 /* c */)) { + if (this.regexp_eatControlLetter(state)) { + return true + } + state.pos = start; + } + return false +}; +pp$1.regexp_eatZero = function(state) { + if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { + state.lastIntValue = 0; + state.advance(); + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape +pp$1.regexp_eatControlEscape = function(state) { + var ch = state.current(); + if (ch === 0x74 /* t */) { + state.lastIntValue = 0x09; /* \t */ + state.advance(); + return true + } + if (ch === 0x6E /* n */) { + state.lastIntValue = 0x0A; /* \n */ + state.advance(); + return true + } + if (ch === 0x76 /* v */) { + state.lastIntValue = 0x0B; /* \v */ + state.advance(); + return true + } + if (ch === 0x66 /* f */) { + state.lastIntValue = 0x0C; /* \f */ + state.advance(); + return true + } + if (ch === 0x72 /* r */) { + state.lastIntValue = 0x0D; /* \r */ + state.advance(); + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter +pp$1.regexp_eatControlLetter = function(state) { + var ch = state.current(); + if (isControlLetter(ch)) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false +}; +function isControlLetter(ch) { + return ( + (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || + (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) + ) +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence +pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { + if ( forceU === void 0 ) forceU = false; + + var start = state.pos; + var switchU = forceU || state.switchU; + + if (state.eat(0x75 /* u */)) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { + var leadSurrogateEnd = state.pos; + if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { + var trail = state.lastIntValue; + if (trail >= 0xDC00 && trail <= 0xDFFF) { + state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + return true + } + } + state.pos = leadSurrogateEnd; + state.lastIntValue = lead; + } + return true + } + if ( + switchU && + state.eat(0x7B /* { */) && + this.regexp_eatHexDigits(state) && + state.eat(0x7D /* } */) && + isValidUnicode(state.lastIntValue) + ) { + return true + } + if (switchU) { + state.raise("Invalid unicode escape"); + } + state.pos = start; + } + + return false +}; +function isValidUnicode(ch) { + return ch >= 0 && ch <= 0x10FFFF +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape +pp$1.regexp_eatIdentityEscape = function(state) { + if (state.switchU) { + if (this.regexp_eatSyntaxCharacter(state)) { + return true + } + if (state.eat(0x2F /* / */)) { + state.lastIntValue = 0x2F; /* / */ + return true + } + return false + } + + var ch = state.current(); + if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape +pp$1.regexp_eatDecimalEscape = function(state) { + state.lastIntValue = 0; + var ch = state.current(); + if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { + do { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) + return true + } + return false +}; + +// Return values used by character set parsing methods, needed to +// forbid negation of sets that can match strings. +var CharSetNone = 0; // Nothing parsed +var CharSetOk = 1; // Construct parsed, cannot contain strings +var CharSetString = 2; // Construct parsed, can contain strings + +// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape +pp$1.regexp_eatCharacterClassEscape = function(state) { + var ch = state.current(); + + if (isCharacterClassEscape(ch)) { + state.lastIntValue = -1; + state.advance(); + return CharSetOk + } + + var negate = false; + if ( + state.switchU && + this.options.ecmaVersion >= 9 && + ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */) + ) { + state.lastIntValue = -1; + state.advance(); + var result; + if ( + state.eat(0x7B /* { */) && + (result = this.regexp_eatUnicodePropertyValueExpression(state)) && + state.eat(0x7D /* } */) + ) { + if (negate && result === CharSetString) { state.raise("Invalid property name"); } + return result + } + state.raise("Invalid property name"); + } + + return CharSetNone +}; + +function isCharacterClassEscape(ch) { + return ( + ch === 0x64 /* d */ || + ch === 0x44 /* D */ || + ch === 0x73 /* s */ || + ch === 0x53 /* S */ || + ch === 0x77 /* w */ || + ch === 0x57 /* W */ + ) +} + +// UnicodePropertyValueExpression :: +// UnicodePropertyName `=` UnicodePropertyValue +// LoneUnicodePropertyNameOrValue +pp$1.regexp_eatUnicodePropertyValueExpression = function(state) { + var start = state.pos; + + // UnicodePropertyName `=` UnicodePropertyValue + if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { + var name = state.lastStringValue; + if (this.regexp_eatUnicodePropertyValue(state)) { + var value = state.lastStringValue; + this.regexp_validateUnicodePropertyNameAndValue(state, name, value); + return CharSetOk + } + } + state.pos = start; + + // LoneUnicodePropertyNameOrValue + if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { + var nameOrValue = state.lastStringValue; + return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue) + } + return CharSetNone +}; + +pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { + if (!hasOwn(state.unicodeProperties.nonBinary, name)) + { state.raise("Invalid property name"); } + if (!state.unicodeProperties.nonBinary[name].test(value)) + { state.raise("Invalid property value"); } +}; + +pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { + if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk } + if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString } + state.raise("Invalid property name"); +}; + +// UnicodePropertyName :: +// UnicodePropertyNameCharacters +pp$1.regexp_eatUnicodePropertyName = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyNameCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" +}; + +function isUnicodePropertyNameCharacter(ch) { + return isControlLetter(ch) || ch === 0x5F /* _ */ +} + +// UnicodePropertyValue :: +// UnicodePropertyValueCharacters +pp$1.regexp_eatUnicodePropertyValue = function(state) { + var ch = 0; + state.lastStringValue = ""; + while (isUnicodePropertyValueCharacter(ch = state.current())) { + state.lastStringValue += codePointToString(ch); + state.advance(); + } + return state.lastStringValue !== "" +}; +function isUnicodePropertyValueCharacter(ch) { + return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) +} + +// LoneUnicodePropertyNameOrValue :: +// UnicodePropertyValueCharacters +pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { + return this.regexp_eatUnicodePropertyValue(state) +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass +pp$1.regexp_eatCharacterClass = function(state) { + if (state.eat(0x5B /* [ */)) { + var negate = state.eat(0x5E /* ^ */); + var result = this.regexp_classContents(state); + if (!state.eat(0x5D /* ] */)) + { state.raise("Unterminated character class"); } + if (negate && result === CharSetString) + { state.raise("Negated character class may contain strings"); } + return true + } + return false +}; + +// https://tc39.es/ecma262/#prod-ClassContents +// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges +pp$1.regexp_classContents = function(state) { + if (state.current() === 0x5D /* ] */) { return CharSetOk } + if (state.switchV) { return this.regexp_classSetExpression(state) } + this.regexp_nonEmptyClassRanges(state); + return CharSetOk +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges +// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash +pp$1.regexp_nonEmptyClassRanges = function(state) { + while (this.regexp_eatClassAtom(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { + var right = state.lastIntValue; + if (state.switchU && (left === -1 || right === -1)) { + state.raise("Invalid character class"); + } + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + } + } +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom +// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash +pp$1.regexp_eatClassAtom = function(state) { + var start = state.pos; + + if (state.eat(0x5C /* \ */)) { + if (this.regexp_eatClassEscape(state)) { + return true + } + if (state.switchU) { + // Make the same message as V8. + var ch$1 = state.current(); + if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { + state.raise("Invalid class escape"); + } + state.raise("Invalid escape"); + } + state.pos = start; + } + + var ch = state.current(); + if (ch !== 0x5D /* ] */) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape +pp$1.regexp_eatClassEscape = function(state) { + var start = state.pos; + + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + + if (state.switchU && state.eat(0x2D /* - */)) { + state.lastIntValue = 0x2D; /* - */ + return true + } + + if (!state.switchU && state.eat(0x63 /* c */)) { + if (this.regexp_eatClassControlLetter(state)) { + return true + } + state.pos = start; + } + + return ( + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) + ) +}; + +// https://tc39.es/ecma262/#prod-ClassSetExpression +// https://tc39.es/ecma262/#prod-ClassUnion +// https://tc39.es/ecma262/#prod-ClassIntersection +// https://tc39.es/ecma262/#prod-ClassSubtraction +pp$1.regexp_classSetExpression = function(state) { + var result = CharSetOk, subResult; + if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) { + if (subResult === CharSetString) { result = CharSetString; } + // https://tc39.es/ecma262/#prod-ClassIntersection + var start = state.pos; + while (state.eatChars([0x26, 0x26] /* && */)) { + if ( + state.current() !== 0x26 /* & */ && + (subResult = this.regexp_eatClassSetOperand(state)) + ) { + if (subResult !== CharSetString) { result = CharSetOk; } + continue + } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { return result } + // https://tc39.es/ecma262/#prod-ClassSubtraction + while (state.eatChars([0x2D, 0x2D] /* -- */)) { + if (this.regexp_eatClassSetOperand(state)) { continue } + state.raise("Invalid character in character class"); + } + if (start !== state.pos) { return result } + } else { + state.raise("Invalid character in character class"); + } + // https://tc39.es/ecma262/#prod-ClassUnion + for (;;) { + if (this.regexp_eatClassSetRange(state)) { continue } + subResult = this.regexp_eatClassSetOperand(state); + if (!subResult) { return result } + if (subResult === CharSetString) { result = CharSetString; } + } +}; + +// https://tc39.es/ecma262/#prod-ClassSetRange +pp$1.regexp_eatClassSetRange = function(state) { + var start = state.pos; + if (this.regexp_eatClassSetCharacter(state)) { + var left = state.lastIntValue; + if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) { + var right = state.lastIntValue; + if (left !== -1 && right !== -1 && left > right) { + state.raise("Range out of order in character class"); + } + return true + } + state.pos = start; + } + return false +}; + +// https://tc39.es/ecma262/#prod-ClassSetOperand +pp$1.regexp_eatClassSetOperand = function(state) { + if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk } + return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state) +}; + +// https://tc39.es/ecma262/#prod-NestedClass +pp$1.regexp_eatNestedClass = function(state) { + var start = state.pos; + if (state.eat(0x5B /* [ */)) { + var negate = state.eat(0x5E /* ^ */); + var result = this.regexp_classContents(state); + if (state.eat(0x5D /* ] */)) { + if (negate && result === CharSetString) { + state.raise("Negated character class may contain strings"); + } + return result + } + state.pos = start; + } + if (state.eat(0x5C /* \ */)) { + var result$1 = this.regexp_eatCharacterClassEscape(state); + if (result$1) { + return result$1 + } + state.pos = start; + } + return null +}; + +// https://tc39.es/ecma262/#prod-ClassStringDisjunction +pp$1.regexp_eatClassStringDisjunction = function(state) { + var start = state.pos; + if (state.eatChars([0x5C, 0x71] /* \q */)) { + if (state.eat(0x7B /* { */)) { + var result = this.regexp_classStringDisjunctionContents(state); + if (state.eat(0x7D /* } */)) { + return result + } + } else { + // Make the same message as V8. + state.raise("Invalid escape"); + } + state.pos = start; + } + return null +}; + +// https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents +pp$1.regexp_classStringDisjunctionContents = function(state) { + var result = this.regexp_classString(state); + while (state.eat(0x7C /* | */)) { + if (this.regexp_classString(state) === CharSetString) { result = CharSetString; } + } + return result +}; + +// https://tc39.es/ecma262/#prod-ClassString +// https://tc39.es/ecma262/#prod-NonEmptyClassString +pp$1.regexp_classString = function(state) { + var count = 0; + while (this.regexp_eatClassSetCharacter(state)) { count++; } + return count === 1 ? CharSetOk : CharSetString +}; + +// https://tc39.es/ecma262/#prod-ClassSetCharacter +pp$1.regexp_eatClassSetCharacter = function(state) { + var start = state.pos; + if (state.eat(0x5C /* \ */)) { + if ( + this.regexp_eatCharacterEscape(state) || + this.regexp_eatClassSetReservedPunctuator(state) + ) { + return true + } + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } + state.pos = start; + return false + } + var ch = state.current(); + if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false } + if (isClassSetSyntaxCharacter(ch)) { return false } + state.advance(); + state.lastIntValue = ch; + return true +}; + +// https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator +function isClassSetReservedDoublePunctuatorCharacter(ch) { + return ( + ch === 0x21 /* ! */ || + ch >= 0x23 /* # */ && ch <= 0x26 /* & */ || + ch >= 0x2A /* * */ && ch <= 0x2C /* , */ || + ch === 0x2E /* . */ || + ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ || + ch === 0x5E /* ^ */ || + ch === 0x60 /* ` */ || + ch === 0x7E /* ~ */ + ) +} + +// https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter +function isClassSetSyntaxCharacter(ch) { + return ( + ch === 0x28 /* ( */ || + ch === 0x29 /* ) */ || + ch === 0x2D /* - */ || + ch === 0x2F /* / */ || + ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ || + ch >= 0x7B /* { */ && ch <= 0x7D /* } */ + ) +} + +// https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator +pp$1.regexp_eatClassSetReservedPunctuator = function(state) { + var ch = state.current(); + if (isClassSetReservedPunctuator(ch)) { + state.lastIntValue = ch; + state.advance(); + return true + } + return false +}; + +// https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator +function isClassSetReservedPunctuator(ch) { + return ( + ch === 0x21 /* ! */ || + ch === 0x23 /* # */ || + ch === 0x25 /* % */ || + ch === 0x26 /* & */ || + ch === 0x2C /* , */ || + ch === 0x2D /* - */ || + ch >= 0x3A /* : */ && ch <= 0x3E /* > */ || + ch === 0x40 /* @ */ || + ch === 0x60 /* ` */ || + ch === 0x7E /* ~ */ + ) +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter +pp$1.regexp_eatClassControlLetter = function(state) { + var ch = state.current(); + if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { + state.lastIntValue = ch % 0x20; + state.advance(); + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence +pp$1.regexp_eatHexEscapeSequence = function(state) { + var start = state.pos; + if (state.eat(0x78 /* x */)) { + if (this.regexp_eatFixedHexDigits(state, 2)) { + return true + } + if (state.switchU) { + state.raise("Invalid escape"); + } + state.pos = start; + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits +pp$1.regexp_eatDecimalDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isDecimalDigit(ch = state.current())) { + state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); + state.advance(); + } + return state.pos !== start +}; +function isDecimalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits +pp$1.regexp_eatHexDigits = function(state) { + var start = state.pos; + var ch = 0; + state.lastIntValue = 0; + while (isHexDigit(ch = state.current())) { + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return state.pos !== start +}; +function isHexDigit(ch) { + return ( + (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || + (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || + (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) + ) +} +function hexToInt(ch) { + if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { + return 10 + (ch - 0x41 /* A */) + } + if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { + return 10 + (ch - 0x61 /* a */) + } + return ch - 0x30 /* 0 */ +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence +// Allows only 0-377(octal) i.e. 0-255(decimal). +pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) { + if (this.regexp_eatOctalDigit(state)) { + var n1 = state.lastIntValue; + if (this.regexp_eatOctalDigit(state)) { + var n2 = state.lastIntValue; + if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { + state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; + } else { + state.lastIntValue = n1 * 8 + n2; + } + } else { + state.lastIntValue = n1; + } + return true + } + return false +}; + +// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit +pp$1.regexp_eatOctalDigit = function(state) { + var ch = state.current(); + if (isOctalDigit(ch)) { + state.lastIntValue = ch - 0x30; /* 0 */ + state.advance(); + return true + } + state.lastIntValue = 0; + return false +}; +function isOctalDigit(ch) { + return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ +} + +// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits +// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit +// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence +pp$1.regexp_eatFixedHexDigits = function(state, length) { + var start = state.pos; + state.lastIntValue = 0; + for (var i = 0; i < length; ++i) { + var ch = state.current(); + if (!isHexDigit(ch)) { + state.pos = start; + return false + } + state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); + state.advance(); + } + return true +}; + +// Object type used to represent tokens. Note that normally, tokens +// simply exist as properties on the parser object. This is only +// used for the onToken callback and the external tokenizer. + +var Token = function Token(p) { + this.type = p.type; + this.value = p.value; + this.start = p.start; + this.end = p.end; + if (p.options.locations) + { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } + if (p.options.ranges) + { this.range = [p.start, p.end]; } +}; + +// ## Tokenizer + +var pp = Parser$1.prototype; + +// Move to the next token + +pp.next = function(ignoreEscapeSequenceInKeyword) { + if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) + { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } + if (this.options.onToken) + { this.options.onToken(new Token(this)); } + + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); +}; + +pp.getToken = function() { + this.next(); + return new Token(this) +}; + +// If we're in an ES6 environment, make parsers iterable +if (typeof Symbol !== "undefined") + { pp[Symbol.iterator] = function() { + var this$1$1 = this; + + return { + next: function () { + var token = this$1$1.getToken(); + return { + done: token.type === types$1.eof, + value: token + } + } + } + }; } + +// Toggle strict mode. Re-reads the next number or string to please +// pedantic tests (`"use strict"; 010;` should fail). + +// Read a single token, updating the parser object's token-related +// properties. + +pp.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } + + this.start = this.pos; + if (this.options.locations) { this.startLoc = this.curPosition(); } + if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) } + + if (curContext.override) { return curContext.override(this) } + else { this.readToken(this.fullCharCodeAtPos()); } +}; + +pp.readToken = function(code) { + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) + { return this.readWord() } + + return this.getTokenFromCode(code) +}; + +pp.fullCharCodeAtPos = function() { + var code = this.input.charCodeAt(this.pos); + if (code <= 0xd7ff || code >= 0xdc00) { return code } + var next = this.input.charCodeAt(this.pos + 1); + return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 +}; + +pp.skipBlockComment = function() { + var startLoc = this.options.onComment && this.curPosition(); + var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); + if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } + this.pos = end + 2; + if (this.options.locations) { + for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) { + ++this.curLine; + pos = this.lineStart = nextBreak; + } + } + if (this.options.onComment) + { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, + startLoc, this.curPosition()); } +}; + +pp.skipLineComment = function(startSkip) { + var start = this.pos; + var startLoc = this.options.onComment && this.curPosition(); + var ch = this.input.charCodeAt(this.pos += startSkip); + while (this.pos < this.input.length && !isNewLine(ch)) { + ch = this.input.charCodeAt(++this.pos); + } + if (this.options.onComment) + { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, + startLoc, this.curPosition()); } +}; + +// Called at the start of the parse and after every token. Skips +// whitespace and comments, and. + +pp.skipSpace = function() { + loop: while (this.pos < this.input.length) { + var ch = this.input.charCodeAt(this.pos); + switch (ch) { + case 32: case 160: // ' ' + ++this.pos; + break + case 13: + if (this.input.charCodeAt(this.pos + 1) === 10) { + ++this.pos; + } + case 10: case 8232: case 8233: + ++this.pos; + if (this.options.locations) { + ++this.curLine; + this.lineStart = this.pos; + } + break + case 47: // '/' + switch (this.input.charCodeAt(this.pos + 1)) { + case 42: // '*' + this.skipBlockComment(); + break + case 47: + this.skipLineComment(2); + break + default: + break loop + } + break + default: + if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this.pos; + } else { + break loop + } + } + } +}; + +// Called at the end of every token. Sets `end`, `val`, and +// maintains `context` and `exprAllowed`, and skips the space after +// the token, so that the next one's `start` will point at the +// right position. + +pp.finishToken = function(type, val) { + this.end = this.pos; + if (this.options.locations) { this.endLoc = this.curPosition(); } + var prevType = this.type; + this.type = type; + this.value = val; + + this.updateContext(prevType); +}; + +// ### Token reading + +// This is the function that is called to fetch the next token. It +// is somewhat obscure, because it works in character codes rather +// than characters, and because operator parsing has been inlined +// into it. +// +// All in the name of speed. +// +pp.readToken_dot = function() { + var next = this.input.charCodeAt(this.pos + 1); + if (next >= 48 && next <= 57) { return this.readNumber(true) } + var next2 = this.input.charCodeAt(this.pos + 2); + if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' + this.pos += 3; + return this.finishToken(types$1.ellipsis) + } else { + ++this.pos; + return this.finishToken(types$1.dot) + } +}; + +pp.readToken_slash = function() { // '/' + var next = this.input.charCodeAt(this.pos + 1); + if (this.exprAllowed) { ++this.pos; return this.readRegexp() } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.slash, 1) +}; + +pp.readToken_mult_modulo_exp = function(code) { // '%*' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + var tokentype = code === 42 ? types$1.star : types$1.modulo; + + // exponentiation operator ** and **= + if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { + ++size; + tokentype = types$1.starstar; + next = this.input.charCodeAt(this.pos + 2); + } + + if (next === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(tokentype, size) +}; + +pp.readToken_pipe_amp = function(code) { // '|&' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (this.options.ecmaVersion >= 12) { + var next2 = this.input.charCodeAt(this.pos + 2); + if (next2 === 61) { return this.finishOp(types$1.assign, 3) } + } + return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1) +}; + +pp.readToken_caret = function() { // '^' + var next = this.input.charCodeAt(this.pos + 1); + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.bitwiseXOR, 1) +}; + +pp.readToken_plus_min = function(code) { // '+-' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { + if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && + (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { + // A `-->` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken() + } + return this.finishOp(types$1.incDec, 2) + } + if (next === 61) { return this.finishOp(types$1.assign, 2) } + return this.finishOp(types$1.plusMin, 1) +}; + +pp.readToken_lt_gt = function(code) { // '<>' + var next = this.input.charCodeAt(this.pos + 1); + var size = 1; + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } + return this.finishOp(types$1.bitShift, size) + } + if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && + this.input.charCodeAt(this.pos + 3) === 45) { + // ` foo -> __import_foo__.default + // import { baz } from 'foo' --> baz -> __import_foo__.baz + // import * as ok from 'foo' --> ok -> __import_foo__ + if (node.type === 'ImportDeclaration') { + const importId = defineImport(node.source.value, { + importedNames: node.specifiers + .map((s) => { + if (s.type === 'ImportSpecifier') + return s.imported.name; + else if (s.type === 'ImportDefaultSpecifier') + return 'default'; + }) + .filter(isDefined), + }); + s.remove(node.start, node.end); + for (const spec of node.specifiers) { + if (spec.type === 'ImportSpecifier') { + idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`); + } + else if (spec.type === 'ImportDefaultSpecifier') { + idToImportMap.set(spec.local.name, `${importId}.default`); + } + else { + // namespace specifier + idToImportMap.set(spec.local.name, importId); + } + } + } + } + // 2. check all export statements and define exports + for (const node of ast.body) { + // named exports + if (node.type === 'ExportNamedDeclaration') { + if (node.declaration) { + if (node.declaration.type === 'FunctionDeclaration' || + node.declaration.type === 'ClassDeclaration') { + // export function foo() {} + defineExport(node.end, node.declaration.id.name); + } + else { + // export const foo = 1, bar = 2 + for (const declaration of node.declaration.declarations) { + const names = extract_names(declaration.id); + for (const name of names) { + defineExport(node.end, name); + } + } + } + s.remove(node.start, node.declaration.start); + } + else { + s.remove(node.start, node.end); + if (node.source) { + // export { foo, bar } from './foo' + const importId = defineImport(node.source.value, { + importedNames: node.specifiers.map((s) => s.local.name), + }); + // hoist re-exports near the defined import so they are immediately exported + for (const spec of node.specifiers) { + defineExport(hoistIndex, spec.exported.name, `${importId}.${spec.local.name}`); + } + } + else { + // export { foo, bar } + for (const spec of node.specifiers) { + const local = spec.local.name; + const binding = idToImportMap.get(local); + defineExport(node.end, spec.exported.name, binding || local); + } + } + } + } + // default export + if (node.type === 'ExportDefaultDeclaration') { + const expressionTypes = ['FunctionExpression', 'ClassExpression']; + if ('id' in node.declaration && + node.declaration.id && + !expressionTypes.includes(node.declaration.type)) { + // named hoistable/class exports + // export default function foo() {} + // export default class A {} + const { name } = node.declaration.id; + s.remove(node.start, node.start + 15 /* 'export default '.length */); + s.append(`\nObject.defineProperty(${ssrModuleExportsKey}, "default", ` + + `{ enumerable: true, configurable: true, value: ${name} });`); + } + else { + // anonymous default exports + s.update(node.start, node.start + 14 /* 'export default'.length */, `${ssrModuleExportsKey}.default =`); + } + } + // export * from './foo' + if (node.type === 'ExportAllDeclaration') { + s.remove(node.start, node.end); + const importId = defineImport(node.source.value); + // hoist re-exports near the defined import so they are immediately exported + if (node.exported) { + defineExport(hoistIndex, node.exported.name, `${importId}`); + } + else { + s.appendLeft(hoistIndex, `${ssrExportAllKey}(${importId});\n`); + } + } + } + // 3. convert references to import bindings & import.meta references + walk(ast, { + onIdentifier(id, parent, parentStack) { + const grandparent = parentStack[1]; + const binding = idToImportMap.get(id.name); + if (!binding) { + return; + } + if (isStaticProperty(parent) && parent.shorthand) { + // let binding used in a property shorthand + // { foo } -> { foo: __import_x__.foo } + // skip for destructuring patterns + if (!isNodeInPattern(parent) || + isInDestructuringAssignment(parent, parentStack)) { + s.appendLeft(id.end, `: ${binding}`); + } + } + else if ((parent.type === 'PropertyDefinition' && + grandparent?.type === 'ClassBody') || + (parent.type === 'ClassDeclaration' && id === parent.superClass)) { + if (!declaredConst.has(id.name)) { + declaredConst.add(id.name); + // locate the top-most node containing the class declaration + const topNode = parentStack[parentStack.length - 2]; + s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`); + } + } + else if ( + // don't transform class name identifier + !(parent.type === 'ClassExpression' && id === parent.id)) { + s.update(id.start, id.end, binding); + } + }, + onImportMeta(node) { + s.update(node.start, node.end, ssrImportMetaKey); + }, + onDynamicImport(node) { + s.update(node.start, node.start + 6, ssrDynamicImportKey); + if (node.type === 'ImportExpression' && node.source.type === 'Literal') { + dynamicDeps.add(node.source.value); + } + }, + }); + let map = s.generateMap({ hires: 'boundary' }); + if (inMap && + inMap.mappings && + 'sources' in inMap && + inMap.sources.length > 0) { + map = combineSourcemaps(url, [ + { + ...map, + sources: inMap.sources, + sourcesContent: inMap.sourcesContent, + }, + inMap, + ]); + } + else { + map.sources = [path$o.basename(url)]; + // needs to use originalCode instead of code + // because code might be already transformed even if map is null + map.sourcesContent = [originalCode]; + } + return { + code: s.toString(), + map, + deps: [...deps], + dynamicDeps: [...dynamicDeps], + }; +} +const isNodeInPatternWeakSet = new WeakSet(); +const setIsNodeInPattern = (node) => isNodeInPatternWeakSet.add(node); +const isNodeInPattern = (node) => isNodeInPatternWeakSet.has(node); +/** + * Same logic from \@vue/compiler-core & \@vue/compiler-sfc + * Except this is using acorn AST + */ +function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) { + const parentStack = []; + const varKindStack = []; + const scopeMap = new WeakMap(); + const identifiers = []; + const setScope = (node, name) => { + let scopeIds = scopeMap.get(node); + if (scopeIds && scopeIds.has(name)) { + return; + } + if (!scopeIds) { + scopeIds = new Set(); + scopeMap.set(node, scopeIds); + } + scopeIds.add(name); + }; + function isInScope(name, parents) { + return parents.some((node) => node && scopeMap.get(node)?.has(name)); + } + function handlePattern(p, parentScope) { + if (p.type === 'Identifier') { + setScope(parentScope, p.name); + } + else if (p.type === 'RestElement') { + handlePattern(p.argument, parentScope); + } + else if (p.type === 'ObjectPattern') { + p.properties.forEach((property) => { + if (property.type === 'RestElement') { + setScope(parentScope, property.argument.name); + } + else { + handlePattern(property.value, parentScope); + } + }); + } + else if (p.type === 'ArrayPattern') { + p.elements.forEach((element) => { + if (element) { + handlePattern(element, parentScope); + } + }); + } + else if (p.type === 'AssignmentPattern') { + handlePattern(p.left, parentScope); + } + else { + setScope(parentScope, p.name); + } + } + walk$1(root, { + enter(node, parent) { + if (node.type === 'ImportDeclaration') { + return this.skip(); + } + // track parent stack, skip for "else-if"/"else" branches as acorn nests + // the ast within "if" nodes instead of flattening them + if (parent && + !(parent.type === 'IfStatement' && node === parent.alternate)) { + parentStack.unshift(parent); + } + // track variable declaration kind stack used by VariableDeclarator + if (node.type === 'VariableDeclaration') { + varKindStack.unshift(node.kind); + } + if (node.type === 'MetaProperty' && node.meta.name === 'import') { + onImportMeta(node); + } + else if (node.type === 'ImportExpression') { + onDynamicImport(node); + } + if (node.type === 'Identifier') { + if (!isInScope(node.name, parentStack) && + isRefIdentifier(node, parent, parentStack)) { + // record the identifier, for DFS -> BFS + identifiers.push([node, parentStack.slice(0)]); + } + } + else if (isFunction(node)) { + // If it is a function declaration, it could be shadowing an import + // Add its name to the scope so it won't get replaced + if (node.type === 'FunctionDeclaration') { + const parentScope = findParentScope(parentStack); + if (parentScope) { + setScope(parentScope, node.id.name); + } + } + // walk function expressions and add its arguments to known identifiers + // so that we don't prefix them + node.params.forEach((p) => { + if (p.type === 'ObjectPattern' || p.type === 'ArrayPattern') { + handlePattern(p, node); + return; + } + walk$1(p.type === 'AssignmentPattern' ? p.left : p, { + enter(child, parent) { + // skip params default value of destructure + if (parent?.type === 'AssignmentPattern' && + parent?.right === child) { + return this.skip(); + } + if (child.type !== 'Identifier') + return; + // do not record as scope variable if is a destructuring keyword + if (isStaticPropertyKey(child, parent)) + return; + // do not record if this is a default value + // assignment of a destructuring variable + if ((parent?.type === 'TemplateLiteral' && + parent?.expressions.includes(child)) || + (parent?.type === 'CallExpression' && parent?.callee === child)) { + return; + } + setScope(node, child.name); + }, + }); + }); + } + else if (node.type === 'Property' && parent.type === 'ObjectPattern') { + // mark property in destructuring pattern + setIsNodeInPattern(node); + } + else if (node.type === 'VariableDeclarator') { + const parentFunction = findParentScope(parentStack, varKindStack[0] === 'var'); + if (parentFunction) { + handlePattern(node.id, parentFunction); + } + } + else if (node.type === 'CatchClause' && node.param) { + handlePattern(node.param, node); + } + }, + leave(node, parent) { + // untrack parent stack from above + if (parent && + !(parent.type === 'IfStatement' && node === parent.alternate)) { + parentStack.shift(); + } + if (node.type === 'VariableDeclaration') { + varKindStack.shift(); + } + }, + }); + // emit the identifier events in BFS so the hoisted declarations + // can be captured correctly + identifiers.forEach(([node, stack]) => { + if (!isInScope(node.name, stack)) + onIdentifier(node, stack[0], stack); + }); +} +function isRefIdentifier(id, parent, parentStack) { + // declaration id + if (parent.type === 'CatchClause' || + ((parent.type === 'VariableDeclarator' || + parent.type === 'ClassDeclaration') && + parent.id === id)) { + return false; + } + if (isFunction(parent)) { + // function declaration/expression id + if (parent.id === id) { + return false; + } + // params list + if (parent.params.includes(id)) { + return false; + } + } + // class method name + if (parent.type === 'MethodDefinition' && !parent.computed) { + return false; + } + // property key + if (isStaticPropertyKey(id, parent)) { + return false; + } + // object destructuring pattern + if (isNodeInPattern(parent) && parent.value === id) { + return false; + } + // non-assignment array destructuring pattern + if (parent.type === 'ArrayPattern' && + !isInDestructuringAssignment(parent, parentStack)) { + return false; + } + // member expression property + if (parent.type === 'MemberExpression' && + parent.property === id && + !parent.computed) { + return false; + } + if (parent.type === 'ExportSpecifier') { + return false; + } + // is a special keyword but parsed as identifier + if (id.name === 'arguments') { + return false; + } + return true; +} +const isStaticProperty = (node) => node && node.type === 'Property' && !node.computed; +const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node; +const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/; +function isFunction(node) { + return functionNodeTypeRE.test(node.type); +} +const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/; +function isBlock(node) { + return blockNodeTypeRE.test(node.type); +} +function findParentScope(parentStack, isVar = false) { + return parentStack.find(isVar ? isFunction : isBlock); +} +function isInDestructuringAssignment(parent, parentStack) { + if (parent && + (parent.type === 'Property' || parent.type === 'ArrayPattern')) { + return parentStack.some((i) => i.type === 'AssignmentExpression'); + } + return false; +} + +let offset; +function calculateOffsetOnce() { + if (offset !== undefined) { + return; + } + try { + new Function('throw new Error(1)')(); + } + catch (e) { + // in Node 12, stack traces account for the function wrapper. + // in Node 13 and later, the function wrapper adds two lines, + // which must be subtracted to generate a valid mapping + const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]); + offset = match ? +match[1] - 1 : 0; + } +} +function ssrRewriteStacktrace(stack, moduleGraph) { + calculateOffsetOnce(); + return stack + .split('\n') + .map((line) => { + return line.replace(/^ {4}at (?:(\S.*?)\s\()?(.+?):(\d+)(?::(\d+))?\)?/, (input, varName, id, line, column) => { + if (!id) + return input; + const mod = moduleGraph.idToModuleMap.get(id); + const rawSourceMap = mod?.ssrTransformResult?.map; + if (!rawSourceMap) { + return input; + } + const traced = new TraceMap(rawSourceMap); + const pos = originalPositionFor$1(traced, { + line: Number(line) - offset, + // stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed + column: Number(column) - 1, + }); + if (!pos.source || pos.line == null || pos.column == null) { + return input; + } + const trimmedVarName = varName.trim(); + const sourceFile = path$o.resolve(path$o.dirname(id), pos.source); + // stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed + const source = `${sourceFile}:${pos.line}:${pos.column + 1}`; + if (!trimmedVarName || trimmedVarName === 'eval') { + return ` at ${source}`; + } + else { + return ` at ${trimmedVarName} (${source})`; + } + }); + }) + .join('\n'); +} +function rebindErrorStacktrace(e, stacktrace) { + const { configurable, writable } = Object.getOwnPropertyDescriptor(e, 'stack'); + if (configurable) { + Object.defineProperty(e, 'stack', { + value: stacktrace, + enumerable: true, + configurable: true, + writable: true, + }); + } + else if (writable) { + e.stack = stacktrace; + } +} +const rewroteStacktraces = new WeakSet(); +function ssrFixStacktrace(e, moduleGraph) { + if (!e.stack) + return; + // stacktrace shouldn't be rewritten more than once + if (rewroteStacktraces.has(e)) + return; + const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph); + rebindErrorStacktrace(e, stacktrace); + rewroteStacktraces.add(e); +} + +// eslint-disable-next-line @typescript-eslint/no-empty-function +const AsyncFunction = async function () { }.constructor; +let fnDeclarationLineCount = 0; +{ + const body = '/*code*/'; + const source = new AsyncFunction('a', 'b', body).toString(); + fnDeclarationLineCount = + source.slice(0, source.indexOf(body)).split('\n').length - 1; +} +const pendingModules = new Map(); +const pendingImports = new Map(); +const importErrors = new WeakMap(); +async function ssrLoadModule(url, server, context = { global }, urlStack = [], fixStacktrace) { + url = unwrapId(url); + // when we instantiate multiple dependency modules in parallel, they may + // point to shared modules. We need to avoid duplicate instantiation attempts + // by register every module as pending synchronously so that all subsequent + // request to that module are simply waiting on the same promise. + const pending = pendingModules.get(url); + if (pending) { + return pending; + } + const modulePromise = instantiateModule(url, server, context, urlStack, fixStacktrace); + pendingModules.set(url, modulePromise); + modulePromise + .catch(() => { + pendingImports.delete(url); + }) + .finally(() => { + pendingModules.delete(url); + }); + return modulePromise; +} +async function instantiateModule(url, server, context = { global }, urlStack = [], fixStacktrace) { + const { moduleGraph } = server; + const mod = await moduleGraph.ensureEntryFromUrl(url, true); + if (mod.ssrError) { + throw mod.ssrError; + } + if (mod.ssrModule) { + return mod.ssrModule; + } + const result = mod.ssrTransformResult || + (await transformRequest(url, server, { ssr: true })); + if (!result) { + // TODO more info? is this even necessary? + throw new Error(`failed to load module for ssr: ${url}`); + } + const ssrModule = { + [Symbol.toStringTag]: 'Module', + }; + Object.defineProperty(ssrModule, '__esModule', { value: true }); + // Tolerate circular imports by ensuring the module can be + // referenced before it's been instantiated. + mod.ssrModule = ssrModule; + const ssrImportMeta = { + // The filesystem URL, matching native Node.js modules + url: pathToFileURL(mod.file).toString(), + }; + urlStack = urlStack.concat(url); + const isCircular = (url) => urlStack.includes(url); + const { isProduction, resolve: { dedupe, preserveSymlinks }, root, ssr, } = server.config; + const overrideConditions = ssr.resolve?.externalConditions || []; + const resolveOptions = { + mainFields: ['main'], + conditions: [], + overrideConditions: [...overrideConditions, 'production', 'development'], + extensions: ['.js', '.cjs', '.json'], + dedupe, + preserveSymlinks, + isBuild: false, + isProduction, + root, + ssrConfig: ssr, + legacyProxySsrExternalModules: server.config.legacy?.proxySsrExternalModules, + packageCache: server.config.packageCache, + }; + // Since dynamic imports can happen in parallel, we need to + // account for multiple pending deps and duplicate imports. + const pendingDeps = []; + const ssrImport = async (dep, metadata) => { + try { + if (dep[0] !== '.' && dep[0] !== '/') { + return await nodeImport(dep, mod.file, resolveOptions, metadata); + } + // convert to rollup URL because `pendingImports`, `moduleGraph.urlToModuleMap` requires that + dep = unwrapId(dep); + if (!isCircular(dep) && !pendingImports.get(dep)?.some(isCircular)) { + pendingDeps.push(dep); + if (pendingDeps.length === 1) { + pendingImports.set(url, pendingDeps); + } + const mod = await ssrLoadModule(dep, server, context, urlStack, fixStacktrace); + if (pendingDeps.length === 1) { + pendingImports.delete(url); + } + else { + pendingDeps.splice(pendingDeps.indexOf(dep), 1); + } + // return local module to avoid race condition #5470 + return mod; + } + return moduleGraph.urlToModuleMap.get(dep)?.ssrModule; + } + catch (err) { + // tell external error handler which mod was imported with error + importErrors.set(err, { importee: dep }); + throw err; + } + }; + const ssrDynamicImport = (dep) => { + // #3087 dynamic import vars is ignored at rewrite import path, + // so here need process relative path + if (dep[0] === '.') { + dep = path$o.posix.resolve(path$o.dirname(url), dep); + } + return ssrImport(dep, { isDynamicImport: true }); + }; + function ssrExportAll(sourceModule) { + for (const key in sourceModule) { + if (key !== 'default' && key !== '__esModule') { + Object.defineProperty(ssrModule, key, { + enumerable: true, + configurable: true, + get() { + return sourceModule[key]; + }, + }); + } + } + } + let sourceMapSuffix = ''; + if (result.map && 'version' in result.map) { + const moduleSourceMap = Object.assign({}, result.map, { + // currently we need to offset the line + // https://github.com/nodejs/node/issues/43047#issuecomment-1180632750 + mappings: ';'.repeat(fnDeclarationLineCount) + result.map.mappings, + }); + sourceMapSuffix = + '\n//# sourceMappingURL=' + genSourceMapUrl(moduleSourceMap); + } + try { + const initModule = new AsyncFunction(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, '"use strict";' + + result.code + + `\n//# sourceURL=${mod.id}${sourceMapSuffix}`); + await initModule(context.global, ssrModule, ssrImportMeta, ssrImport, ssrDynamicImport, ssrExportAll); + } + catch (e) { + mod.ssrError = e; + const errorData = importErrors.get(e); + if (e.stack && fixStacktrace) { + ssrFixStacktrace(e, moduleGraph); + } + server.config.logger.error(colors$1.red(`Error when evaluating SSR module ${url}:` + + (errorData?.importee + ? ` failed to import "${errorData.importee}"` + : '') + + `\n|- ${e.stack}\n`), { + timestamp: true, + clear: server.config.clearScreen, + error: e, + }); + throw e; + } + return Object.freeze(ssrModule); +} +// In node@12+ we can use dynamic import to load CJS and ESM +async function nodeImport(id, importer, resolveOptions, metadata) { + let url; + let filePath; + if (id.startsWith('data:') || isBuiltin(id)) { + url = id; + } + else { + const resolved = tryNodeResolve(id, importer, { ...resolveOptions, tryEsmOnly: true }, false, undefined, true); + if (!resolved) { + const err = new Error(`Cannot find module '${id}' imported from '${importer}'`); + err.code = 'ERR_MODULE_NOT_FOUND'; + throw err; + } + filePath = resolved.id; + url = pathToFileURL(resolved.id).toString(); + } + const mod = await import(url); + if (resolveOptions.legacyProxySsrExternalModules) { + return proxyESM(mod); + } + else if (filePath) { + analyzeImportedModDifference(mod, filePath, id, metadata, resolveOptions.packageCache); + return proxyGuardOnlyEsm(mod, id); + } + else { + return mod; + } +} +// rollup-style default import interop for cjs +function proxyESM(mod) { + // This is the only sensible option when the exports object is a primitive + if (isPrimitive(mod)) + return { default: mod }; + let defaultExport = 'default' in mod ? mod.default : mod; + if (!isPrimitive(defaultExport) && '__esModule' in defaultExport) { + mod = defaultExport; + if ('default' in defaultExport) { + defaultExport = defaultExport.default; + } + } + return new Proxy(mod, { + get(mod, prop) { + if (prop === 'default') + return defaultExport; + return mod[prop] ?? defaultExport?.[prop]; + }, + }); +} +function isPrimitive(value) { + return !value || (typeof value !== 'object' && typeof value !== 'function'); +} +/** + * Vite converts `import { } from 'foo'` to `const _ = __vite_ssr_import__('foo')`. + * Top-level imports and dynamic imports work slightly differently in Node.js. + * This function normalizes the differences so it matches prod behaviour. + */ +function analyzeImportedModDifference(mod, filePath, rawId, metadata, packageCache) { + // No normalization needed if the user already dynamic imports this module + if (metadata?.isDynamicImport) + return; + // If file path is ESM, everything should be fine + if (isFilePathESM(filePath, packageCache)) + return; + // For non-ESM, named imports is done via static analysis with cjs-module-lexer in Node.js. + // If the user named imports a specifier that can't be analyzed, error. + if (metadata?.importedNames?.length) { + const missingBindings = metadata.importedNames.filter((s) => !(s in mod)); + if (missingBindings.length) { + const lastBinding = missingBindings[missingBindings.length - 1]; + // Copied from Node.js + throw new SyntaxError(`\ +[vite] Named export '${lastBinding}' not found. The requested module '${rawId}' is a CommonJS module, which may not support all module.exports as named exports. +CommonJS modules can always be imported via the default export, for example using: + +import pkg from '${rawId}'; +const {${missingBindings.join(', ')}} = pkg; +`); + } + } +} +/** + * Guard invalid named exports only, similar to how Node.js errors for top-level imports. + * But since we transform as dynamic imports, we need to emulate the error manually. + */ +function proxyGuardOnlyEsm(mod, rawId, metadata) { + // If the module doesn't import anything explicitly, e.g. `import 'foo'` or + // `import * as foo from 'foo'`, we can skip the proxy guard. + if (!metadata?.importedNames?.length) + return mod; + return new Proxy(mod, { + get(mod, prop) { + if (prop !== 'then' && !(prop in mod)) { + throw new SyntaxError(`[vite] The requested module '${rawId}' does not provide an export named '${prop.toString()}'`); + } + return mod[prop]; + }, + }); +} + +var isWsl$2 = {exports: {}}; + +const fs$3 = require$$0__default; + +let isDocker$2; + +function hasDockerEnv() { + try { + fs$3.statSync('/.dockerenv'); + return true; + } catch (_) { + return false; + } +} + +function hasDockerCGroup() { + try { + return fs$3.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); + } catch (_) { + return false; + } +} + +var isDocker_1 = () => { + if (isDocker$2 === undefined) { + isDocker$2 = hasDockerEnv() || hasDockerCGroup(); + } + + return isDocker$2; +}; + +const os = require$$2; +const fs$2 = require$$0__default; +const isDocker$1 = isDocker_1; + +const isWsl$1 = () => { + if (process.platform !== 'linux') { + return false; + } + + if (os.release().toLowerCase().includes('microsoft')) { + if (isDocker$1()) { + return false; + } + + return true; + } + + try { + return fs$2.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ? + !isDocker$1() : false; + } catch (_) { + return false; + } +}; + +if (process.env.__IS_WSL_TEST__) { + isWsl$2.exports = isWsl$1; +} else { + isWsl$2.exports = isWsl$1(); +} + +var isWslExports = isWsl$2.exports; + +var defineLazyProp = (object, propertyName, fn) => { + const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true}); + + Object.defineProperty(object, propertyName, { + configurable: true, + enumerable: true, + get() { + const result = fn(); + define(result); + return result; + }, + set(value) { + define(value); + } + }); + + return object; +}; + +const path$3 = require$$0$4; +const childProcess = require$$2$1; +const {promises: fs$1, constants: fsConstants} = require$$0__default; +const isWsl = isWslExports; +const isDocker = isDocker_1; +const defineLazyProperty = defineLazyProp; + +// Path to included `xdg-open`. +const localXdgOpenPath = path$3.join(__dirname, 'xdg-open'); + +const {platform, arch} = process; + +// Podman detection +const hasContainerEnv = () => { + try { + fs$1.statSync('/run/.containerenv'); + return true; + } catch { + return false; + } +}; + +let cachedResult; +function isInsideContainer() { + if (cachedResult === undefined) { + cachedResult = hasContainerEnv() || isDocker(); + } + + return cachedResult; +} + +/** +Get the mount point for fixed drives in WSL. + +@inner +@returns {string} The mount point. +*/ +const getWslDrivesMountPoint = (() => { + // Default value for "root" param + // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config + const defaultMountPoint = '/mnt/'; + + let mountPoint; + + return async function () { + if (mountPoint) { + // Return memoized mount point value + return mountPoint; + } + + const configFilePath = '/etc/wsl.conf'; + + let isConfigFileExists = false; + try { + await fs$1.access(configFilePath, fsConstants.F_OK); + isConfigFileExists = true; + } catch {} + + if (!isConfigFileExists) { + return defaultMountPoint; + } + + const configContent = await fs$1.readFile(configFilePath, {encoding: 'utf8'}); + const configMountPoint = /(?.*)/g.exec(configContent); + + if (!configMountPoint) { + return defaultMountPoint; + } + + mountPoint = configMountPoint.groups.mountPoint.trim(); + mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`; + + return mountPoint; + }; +})(); + +const pTryEach = async (array, mapper) => { + let latestError; + + for (const item of array) { + try { + return await mapper(item); // eslint-disable-line no-await-in-loop + } catch (error) { + latestError = error; + } + } + + throw latestError; +}; + +const baseOpen = async options => { + options = { + wait: false, + background: false, + newInstance: false, + allowNonzeroExitCode: false, + ...options + }; + + if (Array.isArray(options.app)) { + return pTryEach(options.app, singleApp => baseOpen({ + ...options, + app: singleApp + })); + } + + let {name: app, arguments: appArguments = []} = options.app || {}; + appArguments = [...appArguments]; + + if (Array.isArray(app)) { + return pTryEach(app, appName => baseOpen({ + ...options, + app: { + name: appName, + arguments: appArguments + } + })); + } + + let command; + const cliArguments = []; + const childProcessOptions = {}; + + if (platform === 'darwin') { + command = 'open'; + + if (options.wait) { + cliArguments.push('--wait-apps'); + } + + if (options.background) { + cliArguments.push('--background'); + } + + if (options.newInstance) { + cliArguments.push('--new'); + } + + if (app) { + cliArguments.push('-a', app); + } + } else if (platform === 'win32' || (isWsl && !isInsideContainer() && !app)) { + const mountPoint = await getWslDrivesMountPoint(); + + command = isWsl ? + `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : + `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`; + + cliArguments.push( + '-NoProfile', + '-NonInteractive', + '–ExecutionPolicy', + 'Bypass', + '-EncodedCommand' + ); + + if (!isWsl) { + childProcessOptions.windowsVerbatimArguments = true; + } + + const encodedArguments = ['Start']; + + if (options.wait) { + encodedArguments.push('-Wait'); + } + + if (app) { + // Double quote with double quotes to ensure the inner quotes are passed through. + // Inner quotes are delimited for PowerShell interpretation with backticks. + encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList'); + if (options.target) { + appArguments.unshift(options.target); + } + } else if (options.target) { + encodedArguments.push(`"${options.target}"`); + } + + if (appArguments.length > 0) { + appArguments = appArguments.map(arg => `"\`"${arg}\`""`); + encodedArguments.push(appArguments.join(',')); + } + + // Using Base64-encoded command, accepted by PowerShell, to allow special characters. + options.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64'); + } else { + if (app) { + command = app; + } else { + // When bundled by Webpack, there's no actual package file path and no local `xdg-open`. + const isBundled = !__dirname || __dirname === '/'; + + // Check if local `xdg-open` exists and is executable. + let exeLocalXdgOpen = false; + try { + await fs$1.access(localXdgOpenPath, fsConstants.X_OK); + exeLocalXdgOpen = true; + } catch {} + + const useSystemXdgOpen = process.versions.electron || + platform === 'android' || isBundled || !exeLocalXdgOpen; + command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath; + } + + if (appArguments.length > 0) { + cliArguments.push(...appArguments); + } + + if (!options.wait) { + // `xdg-open` will block the process unless stdio is ignored + // and it's detached from the parent even if it's unref'd. + childProcessOptions.stdio = 'ignore'; + childProcessOptions.detached = true; + } + } + + if (options.target) { + cliArguments.push(options.target); + } + + if (platform === 'darwin' && appArguments.length > 0) { + cliArguments.push('--args', ...appArguments); + } + + const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions); + + if (options.wait) { + return new Promise((resolve, reject) => { + subprocess.once('error', reject); + + subprocess.once('close', exitCode => { + if (!options.allowNonzeroExitCode && exitCode > 0) { + reject(new Error(`Exited with code ${exitCode}`)); + return; + } + + resolve(subprocess); + }); + }); + } + + subprocess.unref(); + + return subprocess; +}; + +const open = (target, options) => { + if (typeof target !== 'string') { + throw new TypeError('Expected a `target`'); + } + + return baseOpen({ + ...options, + target + }); +}; + +const openApp = (name, options) => { + if (typeof name !== 'string') { + throw new TypeError('Expected a `name`'); + } + + const {arguments: appArguments = []} = options || {}; + if (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) { + throw new TypeError('Expected `appArguments` as Array type'); + } + + return baseOpen({ + ...options, + app: { + name, + arguments: appArguments + } + }); +}; + +function detectArchBinary(binary) { + if (typeof binary === 'string' || Array.isArray(binary)) { + return binary; + } + + const {[arch]: archBinary} = binary; + + if (!archBinary) { + throw new Error(`${arch} is not supported`); + } + + return archBinary; +} + +function detectPlatformBinary({[platform]: platformBinary}, {wsl}) { + if (wsl && isWsl) { + return detectArchBinary(wsl); + } + + if (!platformBinary) { + throw new Error(`${platform} is not supported`); + } + + return detectArchBinary(platformBinary); +} + +const apps = {}; + +defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({ + darwin: 'google chrome', + win32: 'chrome', + linux: ['google-chrome', 'google-chrome-stable', 'chromium'] +}, { + wsl: { + ia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe', + x64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'] + } +})); + +defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({ + darwin: 'firefox', + win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe', + linux: 'firefox' +}, { + wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe' +})); + +defineLazyProperty(apps, 'edge', () => detectPlatformBinary({ + darwin: 'microsoft edge', + win32: 'msedge', + linux: ['microsoft-edge', 'microsoft-edge-dev'] +}, { + wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe' +})); + +open.apps = apps; +open.openApp = openApp; + +var open_1 = open; + +var open$1 = /*@__PURE__*/getDefaultExportFromCjs(open_1); + +var crossSpawn = {exports: {}}; + +var mode; +var hasRequiredMode; + +function requireMode () { + if (hasRequiredMode) return mode; + hasRequiredMode = 1; + mode = isexe; + isexe.sync = sync; + + var fs = require$$0__default; + + function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)); + }); + } + + function sync (path, options) { + return checkStat(fs.statSync(path), options) + } + + function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) + } + + function checkMode (stat, options) { + var mod = stat.mode; + var uid = stat.uid; + var gid = stat.gid; + + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid(); + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid(); + + var u = parseInt('100', 8); + var g = parseInt('010', 8); + var o = parseInt('001', 8); + var ug = u | g; + + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0; + + return ret + } + return mode; +} + +var windows; +var hasRequiredWindows; + +function requireWindows () { + if (hasRequiredWindows) return windows; + hasRequiredWindows = 1; + windows = isexe; + isexe.sync = sync; + + var fs = require$$0__default; + + function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT; + + if (!pathext) { + return true + } + + pathext = pathext.split(';'); + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase(); + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } + } + return false + } + + function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) + } + + function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)); + }); + } + + function sync (path, options) { + return checkStat(fs.statSync(path), path, options) + } + return windows; +} + +var core; +if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) { + core = requireWindows(); +} else { + core = requireMode(); +} + +var isexe_1 = isexe$1; +isexe$1.sync = sync; + +function isexe$1 (path, options, cb) { + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') + } + + return new Promise(function (resolve, reject) { + isexe$1(path, options || {}, function (er, is) { + if (er) { + reject(er); + } else { + resolve(is); + } + }); + }) + } + + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null; + is = false; + } + } + cb(er, is); + }); +} + +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} + +const isWindows = process.platform === 'win32' || + process.env.OSTYPE === 'cygwin' || + process.env.OSTYPE === 'msys'; + +const path$2 = require$$0$4; +const COLON = isWindows ? ';' : ':'; +const isexe = isexe_1; + +const getNotFoundError = (cmd) => + Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); + +const getPathInfo = (cmd, opt) => { + const colon = opt.colon || COLON; + + // If it has a slash, then we don't bother searching the pathenv. + // just check the file itself, and that's it. + const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] + : ( + [ + // windows always checks the cwd first + ...(isWindows ? [process.cwd()] : []), + ...(opt.path || process.env.PATH || + /* istanbul ignore next: very unusual */ '').split(colon), + ] + ); + const pathExtExe = isWindows + ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' + : ''; + const pathExt = isWindows ? pathExtExe.split(colon) : ['']; + + if (isWindows) { + if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') + pathExt.unshift(''); + } + + return { + pathEnv, + pathExt, + pathExtExe, + } +}; + +const which$1 = (cmd, opt, cb) => { + if (typeof opt === 'function') { + cb = opt; + opt = {}; + } + if (!opt) + opt = {}; + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + + const step = i => new Promise((resolve, reject) => { + if (i === pathEnv.length) + return opt.all && found.length ? resolve(found) + : reject(getNotFoundError(cmd)) + + const ppRaw = pathEnv[i]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + + const pCmd = path$2.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd; + + resolve(subStep(p, i, 0)); + }); + + const subStep = (p, i, ii) => new Promise((resolve, reject) => { + if (ii === pathExt.length) + return resolve(step(i + 1)) + const ext = pathExt[ii]; + isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { + if (!er && is) { + if (opt.all) + found.push(p + ext); + else + return resolve(p + ext) + } + return resolve(subStep(p, i, ii + 1)) + }); + }); + + return cb ? step(0).then(res => cb(null, res), cb) : step(0) +}; + +const whichSync = (cmd, opt) => { + opt = opt || {}; + + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + + for (let i = 0; i < pathEnv.length; i ++) { + const ppRaw = pathEnv[i]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + + const pCmd = path$2.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd + : pCmd; + + for (let j = 0; j < pathExt.length; j ++) { + const cur = p + pathExt[j]; + try { + const is = isexe.sync(cur, { pathExt: pathExtExe }); + if (is) { + if (opt.all) + found.push(cur); + else + return cur + } + } catch (ex) {} + } + } + + if (opt.all && found.length) + return found + + if (opt.nothrow) + return null + + throw getNotFoundError(cmd) +}; + +var which_1 = which$1; +which$1.sync = whichSync; + +var pathKey$1 = {exports: {}}; + +const pathKey = (options = {}) => { + const environment = options.env || process.env; + const platform = options.platform || process.platform; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; +}; + +pathKey$1.exports = pathKey; +// TODO: Remove this for the next major release +pathKey$1.exports.default = pathKey; + +var pathKeyExports = pathKey$1.exports; + +const path$1 = require$$0$4; +const which = which_1; +const getPathKey = pathKeyExports; + +function resolveCommandAttempt(parsed, withoutPathExt) { + const env = parsed.options.env || process.env; + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + // Worker threads do not have process.chdir() + const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; + + // If a custom `cwd` was specified, we need to change the process cwd + // because `which` will do stat calls but does not support a custom cwd + if (shouldSwitchCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + /* Empty */ + } + } + + let resolved; + + try { + resolved = which.sync(parsed.command, { + path: env[getPathKey({ env })], + pathExt: withoutPathExt ? path$1.delimiter : undefined, + }); + } catch (e) { + /* Empty */ + } finally { + if (shouldSwitchCwd) { + process.chdir(cwd); + } + } + + // If we successfully resolved, ensure that an absolute path is returned + // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it + if (resolved) { + resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); + } + + return resolved; +} + +function resolveCommand$1(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +} + +var resolveCommand_1 = resolveCommand$1; + +var _escape = {}; + +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + return arg; +} + +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; + + // Algorithm below is based on https://qntm.org/cmd + + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(\\*)"/g, '$1$1\\"'); + + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(\\*)$/, '$1$1'); + + // All other backslashes occur literally + + // Quote the whole thing: + arg = `"${arg}"`; + + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); + } + + return arg; +} + +_escape.command = escapeCommand; +_escape.argument = escapeArgument; + +var shebangRegex$1 = /^#!(.*)/; + +const shebangRegex = shebangRegex$1; + +var shebangCommand$1 = (string = '') => { + const match = string.match(shebangRegex); + + if (!match) { + return null; + } + + const [path, argument] = match[0].replace(/#! ?/, '').split(' '); + const binary = path.split('/').pop(); + + if (binary === 'env') { + return argument; + } + + return argument ? `${binary} ${argument}` : binary; +}; + +const fs = require$$0__default; +const shebangCommand = shebangCommand$1; + +function readShebang$1(command) { + // Read the first 150 bytes from the file + const size = 150; + const buffer = Buffer.alloc(size); + + let fd; + + try { + fd = fs.openSync(command, 'r'); + fs.readSync(fd, buffer, 0, size, 0); + fs.closeSync(fd); + } catch (e) { /* Empty */ } + + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); +} + +var readShebang_1 = readShebang$1; + +const path = require$$0$4; +const resolveCommand = resolveCommand_1; +const escape$1 = _escape; +const readShebang = readShebang_1; + +const isWin$1 = process.platform === 'win32'; +const isExecutableRegExp = /\.(?:com|exe)$/i; +const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + +function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + + const shebang = parsed.file && readShebang(parsed.file); + + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + + return resolveCommand(parsed); + } + + return parsed.file; +} + +function parseNonShell(parsed) { + if (!isWin$1) { + return parsed; + } + + // Detect & add support for shebangs + const commandFile = detectShebang(parsed); + + // We don't need a shell if the command filename is an executable + const needsShell = !isExecutableRegExp.test(commandFile); + + // If a shell is required, use cmd.exe and take care of escaping everything correctly + // Note that `forceShell` is an hidden option used only in tests + if (parsed.options.forceShell || needsShell) { + // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` + // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument + // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, + // we need to double escape them + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + + // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) + // This is necessary otherwise it will always fail with ENOENT in those cases + parsed.command = path.normalize(parsed.command); + + // Escape command & arguments + parsed.command = escape$1.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape$1.argument(arg, needsDoubleEscapeMetaChars)); + + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.command = process.env.comspec || 'cmd.exe'; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } + + return parsed; +} + +function parse$4(command, args, options) { + // Normalize arguments, similar to nodejs + if (args && !Array.isArray(args)) { + options = args; + args = null; + } + + args = args ? args.slice(0) : []; // Clone array to avoid changing the original + options = Object.assign({}, options); // Clone object to avoid changing the original + + // Build our parsed object + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args, + }, + }; + + // Delegate further parsing to shell or non-shell + return options.shell ? parsed : parseNonShell(parsed); +} + +var parse_1 = parse$4; + +const isWin = process.platform === 'win32'; + +function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: 'ENOENT', + errno: 'ENOENT', + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args, + }); +} + +function hookChildProcess(cp, parsed) { + if (!isWin) { + return; + } + + const originalEmit = cp.emit; + + cp.emit = function (name, arg1) { + // If emitting "exit" event and exit code is 1, we need to check if + // the command exists and emit an "error" instead + // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 + if (name === 'exit') { + const err = verifyENOENT(arg1, parsed); + + if (err) { + return originalEmit.call(cp, 'error', err); + } + } + + return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params + }; +} + +function verifyENOENT(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawn'); + } + + return null; +} + +function verifyENOENTSync(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawnSync'); + } + + return null; +} + +var enoent$1 = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError, +}; + +const cp = require$$2$1; +const parse$3 = parse_1; +const enoent = enoent$1; + +function spawn(command, args, options) { + // Parse the arguments + const parsed = parse$3(command, args, options); + + // Spawn the child process + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + + // Hook into child process "exit" event to emit an error if the command + // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + enoent.hookChildProcess(spawned, parsed); + + return spawned; +} + +function spawnSync(command, args, options) { + // Parse the arguments + const parsed = parse$3(command, args, options); + + // Spawn the child process + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + + // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + + return result; +} + +crossSpawn.exports = spawn; +crossSpawn.exports.spawn = spawn; +crossSpawn.exports.sync = spawnSync; + +crossSpawn.exports._parse = parse$3; +crossSpawn.exports._enoent = enoent; + +var crossSpawnExports = crossSpawn.exports; +var spawn$1 = /*@__PURE__*/getDefaultExportFromCjs(crossSpawnExports); + +/** + * The following is modified based on source found in + * https://github.com/facebook/create-react-app + * + * MIT Licensed + * Copyright (c) 2015-present, Facebook, Inc. + * https://github.com/facebook/create-react-app/blob/master/LICENSE + * + */ +/** + * Reads the BROWSER environment variable and decides what to do with it. + */ +function openBrowser(url, opt, logger) { + // The browser executable to open. + // See https://github.com/sindresorhus/open#app for documentation. + const browser = typeof opt === 'string' ? opt : process.env.BROWSER || ''; + if (browser.toLowerCase().endsWith('.js')) { + executeNodeScript(browser, url, logger); + } + else if (browser.toLowerCase() !== 'none') { + const browserArgs = process.env.BROWSER_ARGS + ? process.env.BROWSER_ARGS.split(' ') + : []; + startBrowserProcess(browser, browserArgs, url); + } +} +function executeNodeScript(scriptPath, url, logger) { + const extraArgs = process.argv.slice(2); + const child = spawn$1(process.execPath, [scriptPath, ...extraArgs, url], { + stdio: 'inherit', + }); + child.on('close', (code) => { + if (code !== 0) { + logger.error(colors$1.red(`\nThe script specified as BROWSER environment variable failed.\n\n${colors$1.cyan(scriptPath)} exited with code ${code}.`), { error: null }); + } + }); +} +const supportedChromiumBrowsers = [ + 'Google Chrome Canary', + 'Google Chrome Dev', + 'Google Chrome Beta', + 'Google Chrome', + 'Microsoft Edge', + 'Brave Browser', + 'Vivaldi', + 'Chromium', +]; +async function startBrowserProcess(browser, browserArgs, url) { + // If we're on OS X, the user hasn't specifically + // requested a different browser, we can try opening + // a Chromium browser with AppleScript. This lets us reuse an + // existing tab when possible instead of creating a new one. + const preferredOSXBrowser = browser === 'google chrome' ? 'Google Chrome' : browser; + const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' && + (!preferredOSXBrowser || + supportedChromiumBrowsers.includes(preferredOSXBrowser)); + if (shouldTryOpenChromeWithAppleScript) { + try { + const ps = await execAsync('ps cax'); + const openedBrowser = preferredOSXBrowser && ps.includes(preferredOSXBrowser) + ? preferredOSXBrowser + : supportedChromiumBrowsers.find((b) => ps.includes(b)); + if (openedBrowser) { + // Try our best to reuse existing tab with AppleScript + await execAsync(`osascript openChrome.applescript "${encodeURI(url)}" "${openedBrowser}"`, { + cwd: join$2(VITE_PACKAGE_DIR, 'bin'), + }); + return true; + } + } + catch (err) { + // Ignore errors + } + } + // Another special case: on OS X, check if BROWSER has been set to "open". + // In this case, instead of passing the string `open` to `open` function (which won't work), + // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser): + // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768 + if (process.platform === 'darwin' && browser === 'open') { + browser = undefined; + } + // Fallback to open + // (It will always open new tab) + try { + const options = browser + ? { app: { name: browser, arguments: browserArgs } } + : {}; + open$1(url, options).catch(() => { }); // Prevent `unhandledRejection` error. + return true; + } + catch (err) { + return false; + } +} +function execAsync(command, options) { + return new Promise((resolve, reject) => { + exec(command, options, (error, stdout) => { + if (error) { + reject(error); + } + else { + resolve(stdout.toString()); + } + }); + }); +} + +function bindCLIShortcuts(server, opts) { + if (!server.httpServer || !process.stdin.isTTY || process.env.CI) { + return; + } + const isDev = isDevServer(server); + if (isDev) { + server._shortcutsOptions = opts; + } + if (opts?.print) { + server.config.logger.info(colors$1.dim(colors$1.green(' ➜')) + + colors$1.dim(' press ') + + colors$1.bold('h + enter') + + colors$1.dim(' to show help')); + } + const shortcuts = (opts?.customShortcuts ?? []).concat((isDev + ? BASE_DEV_SHORTCUTS + : BASE_PREVIEW_SHORTCUTS)); + let actionRunning = false; + const onInput = async (input) => { + if (actionRunning) + return; + if (input === 'h') { + const loggedKeys = new Set(); + server.config.logger.info('\n Shortcuts'); + for (const shortcut of shortcuts) { + if (loggedKeys.has(shortcut.key)) + continue; + loggedKeys.add(shortcut.key); + if (shortcut.action == null) + continue; + server.config.logger.info(colors$1.dim(' press ') + + colors$1.bold(`${shortcut.key} + enter`) + + colors$1.dim(` to ${shortcut.description}`)); + } + return; + } + const shortcut = shortcuts.find((shortcut) => shortcut.key === input); + if (!shortcut || shortcut.action == null) + return; + actionRunning = true; + await shortcut.action(server); + actionRunning = false; + }; + const rl = readline.createInterface({ input: process.stdin }); + rl.on('line', onInput); + server.httpServer.on('close', () => rl.close()); +} +const BASE_DEV_SHORTCUTS = [ + { + key: 'r', + description: 'restart the server', + async action(server) { + await restartServerWithUrls(server); + }, + }, + { + key: 'u', + description: 'show server url', + action(server) { + server.config.logger.info(''); + server.printUrls(); + }, + }, + { + key: 'o', + description: 'open in browser', + action(server) { + server.openBrowser(); + }, + }, + { + key: 'c', + description: 'clear console', + action(server) { + server.config.logger.clearScreen('error'); + }, + }, + { + key: 'q', + description: 'quit', + async action(server) { + await server.close().finally(() => process.exit()); + }, + }, +]; +const BASE_PREVIEW_SHORTCUTS = [ + { + key: 'o', + description: 'open in browser', + action(server) { + const url = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0]; + if (url) { + openBrowser(url, true, server.config.logger); + } + else { + server.config.logger.warn('No URL available to open in browser'); + } + }, + }, + { + key: 'q', + description: 'quit', + action(server) { + try { + server.httpServer.close(); + } + finally { + process.exit(); + } + }, + }, +]; + +function resolveChokidarOptions(config, options) { + const { ignored = [], ...otherOptions } = options ?? {}; + const resolvedWatchOptions = { + ignored: [ + '**/.git/**', + '**/node_modules/**', + '**/test-results/**', + glob.escapePath(config.cacheDir) + '/**', + ...(Array.isArray(ignored) ? ignored : [ignored]), + ], + ignoreInitial: true, + ignorePermissionErrors: true, + ...otherOptions, + }; + return resolvedWatchOptions; +} +class NoopWatcher extends EventEmitter$4 { + options; + constructor(options) { + super(); + this.options = options; + } + add() { + return this; + } + unwatch() { + return this; + } + getWatched() { + return {}; + } + async close() { + // noop + } +} +function createNoopWatcher(options) { + return new NoopWatcher(options); +} + +var bufferUtil$1 = {exports: {}}; + +var constants = { + BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], + EMPTY_BUFFER: Buffer.alloc(0), + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), + kListener: Symbol('kListener'), + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + NOOP: () => {} +}; + +const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants; + +const FastBuffer$2 = Buffer[Symbol.species]; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +function concat$1(list, totalLength) { + if (list.length === 0) return EMPTY_BUFFER$3; + if (list.length === 1) return list[0]; + + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + + if (offset < totalLength) { + return new FastBuffer$2(target.buffer, target.byteOffset, offset); + } + + return target; +} + +/** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ +function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } +} + +/** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ +function _unmask(buffer, mask) { + for (let i = 0; i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} buf The buffer to convert + * @return {ArrayBuffer} Converted buffer + * @public + */ +function toArrayBuffer$1(buf) { + if (buf.length === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); +} + +/** + * Converts `data` to a `Buffer`. + * + * @param {*} data The data to convert + * @return {Buffer} The buffer + * @throws {TypeError} + * @public + */ +function toBuffer$2(data) { + toBuffer$2.readOnly = true; + + if (Buffer.isBuffer(data)) return data; + + let buf; + + if (data instanceof ArrayBuffer) { + buf = new FastBuffer$2(data); + } else if (ArrayBuffer.isView(data)) { + buf = new FastBuffer$2(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer$2.readOnly = false; + } + + return buf; +} + +bufferUtil$1.exports = { + concat: concat$1, + mask: _mask, + toArrayBuffer: toArrayBuffer$1, + toBuffer: toBuffer$2, + unmask: _unmask +}; + +/* istanbul ignore else */ +if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = require('bufferutil'); + + bufferUtil$1.exports.mask = function (source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bufferUtil.mask(source, mask, output, offset, length); + }; + + bufferUtil$1.exports.unmask = function (buffer, mask) { + if (buffer.length < 32) _unmask(buffer, mask); + else bufferUtil.unmask(buffer, mask); + }; + } catch (e) { + // Continue regardless of the error. + } +} + +var bufferUtilExports = bufferUtil$1.exports; + +const kDone = Symbol('kDone'); +const kRun = Symbol('kRun'); + +/** + * A very simple job queue with adjustable concurrency. Adapted from + * https://github.com/STRML/async-limiter + */ +let Limiter$1 = class Limiter { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + + if (this.jobs.length) { + const job = this.jobs.shift(); + + this.pending++; + job(this[kDone]); + } + } +}; + +var limiter = Limiter$1; + +const zlib = require$$0$b; + +const bufferUtil = bufferUtilExports; +const Limiter = limiter; +const { kStatusCode: kStatusCode$2 } = constants; + +const FastBuffer$1 = Buffer[Symbol.species]; +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError$1 = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +let PerMessageDeflate$4 = class PerMessageDeflate { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed if context takeover is disabled + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + * @param {Boolean} [isServer=false] Create the instance in either server or + * client mode + * @param {Number} [maxPayload=0] The maximum allowed message length + */ + constructor(options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = + this._options.threshold !== undefined ? this._options.threshold : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = + this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter(concurrency); + } + } + + /** + * @type {String} + */ + static get extensionName() { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + + if (this._deflate) { + const callback = this._deflate[kCallback]; + + this._deflate.close(); + this._deflate = null; + + if (callback) { + callback( + new Error( + 'The deflate stream was closed while data was being processed' + ) + ); + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + !params.client_max_window_bits) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError$1]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data, fin, callback) { + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + this._deflate.on('data', deflateOnData); + } + + this._deflate[kCallback] = callback; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + // + // The deflate stream was closed while data was being processed. + // + return; + } + + let data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) { + data = new FastBuffer$1(data.buffer, data.byteOffset, data.length - 4); + } + + // + // Ensure that the callback will not be called again in + // `PerMessageDeflate#cleanup()`. + // + this._deflate[kCallback] = null; + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + + callback(null, data); + }); + } +}; + +var permessageDeflate = PerMessageDeflate$4; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError$1] = new RangeError('Max payload size exceeded'); + this[kError$1].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; + this[kError$1][kStatusCode$2] = 1009; + this.removeListener('data', inflateOnData); + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError(err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + err[kStatusCode$2] = 1007; + this[kCallback](err); +} + +var validation = {exports: {}}; + +const { isUtf8 } = require$$0$c; + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +// prettier-ignore +const tokenChars$2 = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +function isValidStatusCode$2(code) { + return ( + (code >= 1000 && + code <= 1014 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +} + +/** + * Checks if a given buffer contains only correct UTF-8. + * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by + * Markus Kuhn. + * + * @param {Buffer} buf The buffer to check + * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` + * @public + */ +function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + + while (i < len) { + if ((buf[i] & 0x80) === 0) { + // 0xxxxxxx + i++; + } else if ((buf[i] & 0xe0) === 0xc0) { + // 110xxxxx 10xxxxxx + if ( + i + 1 === len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i] & 0xfe) === 0xc0 // Overlong + ) { + return false; + } + + i += 2; + } else if ((buf[i] & 0xf0) === 0xe0) { + // 1110xxxx 10xxxxxx 10xxxxxx + if ( + i + 2 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong + (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) + ) { + return false; + } + + i += 3; + } else if ((buf[i] & 0xf8) === 0xf0) { + // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + if ( + i + 3 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i + 3] & 0xc0) !== 0x80 || + (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong + (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || + buf[i] > 0xf4 // > U+10FFFF + ) { + return false; + } + + i += 4; + } else { + return false; + } + } + + return true; +} + +validation.exports = { + isValidStatusCode: isValidStatusCode$2, + isValidUTF8: _isValidUTF8, + tokenChars: tokenChars$2 +}; + +if (isUtf8) { + validation.exports.isValidUTF8 = function (buf) { + return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); + }; +} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = require('utf-8-validate'); + + validation.exports.isValidUTF8 = function (buf) { + return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e) { + // Continue regardless of the error. + } +} + +var validationExports = validation.exports; + +const { Writable: Writable$1 } = require$$0$7; + +const PerMessageDeflate$3 = permessageDeflate; +const { + BINARY_TYPES: BINARY_TYPES$1, + EMPTY_BUFFER: EMPTY_BUFFER$2, + kStatusCode: kStatusCode$1, + kWebSocket: kWebSocket$2 +} = constants; +const { concat, toArrayBuffer, unmask } = bufferUtilExports; +const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validationExports; + +const FastBuffer = Buffer[Symbol.species]; +const promise = Promise.resolve(); + +// +// `queueMicrotask()` is not available in Node.js < 11. +// +const queueTask = + typeof queueMicrotask === 'function' ? queueMicrotask : queueMicrotaskShim; + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; +const WAIT_MICROTASK = 6; + +/** + * HyBi Receiver implementation. + * + * @extends Writable + */ +let Receiver$1 = class Receiver extends Writable$1 { + /** + * Creates a Receiver instance. + * + * @param {Object} [options] Options object + * @param {Boolean} [options.allowMultipleEventsPerMicrotask=false] Specifies + * whether or not to process more than one of the `'message'`, `'ping'`, + * and `'pong'` events per microtask + * @param {String} [options.binaryType=nodebuffer] The type for binary data + * @param {Object} [options.extensions] An object containing the negotiated + * extensions + * @param {Boolean} [options.isServer=false] Specifies whether to operate in + * client or server mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + */ + constructor(options = {}) { + super(); + + this._allowMultipleEventsPerMicrotask = + !!options.allowMultipleEventsPerMicrotask; + this._binaryType = options.binaryType || BINARY_TYPES$1[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket$2] = undefined; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + + this._state = GET_INFO; + this._loop = false; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + + return new FastBuffer(buf.buffer, buf.byteOffset, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + let err; + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + err = this.getInfo(); + break; + case GET_PAYLOAD_LENGTH_16: + err = this.getPayloadLength16(); + break; + case GET_PAYLOAD_LENGTH_64: + err = this.getPayloadLength64(); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + err = this.getData(cb); + break; + case INFLATING: + this._loop = false; + return; + default: + // + // `WAIT_MICROTASK`. + // + this._loop = false; + + queueTask(() => { + this._state = GET_INFO; + this.startLoop(cb); + }); + return; + } + } while (this._loop); + + cb(err); + } + + /** + * Reads the first two bytes of a frame. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getInfo() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + this._loop = false; + return error$1( + RangeError, + 'RSV2 and RSV3 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_2_3' + ); + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) { + this._loop = false; + return error$1( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + this._loop = false; + return error$1( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if (!this._fragmented) { + this._loop = false; + return error$1( + RangeError, + 'invalid opcode 0', + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + this._loop = false; + return error$1( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + this._loop = false; + return error$1( + RangeError, + 'FIN must be set', + true, + 1002, + 'WS_ERR_EXPECTED_FIN' + ); + } + + if (compressed) { + this._loop = false; + return error$1( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if ( + this._payloadLength > 0x7d || + (this._opcode === 0x08 && this._payloadLength === 1) + ) { + this._loop = false; + return error$1( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + } + } else { + this._loop = false; + return error$1( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._isServer) { + if (!this._masked) { + this._loop = false; + return error$1( + RangeError, + 'MASK must be set', + true, + 1002, + 'WS_ERR_EXPECTED_MASK' + ); + } + } else if (this._masked) { + this._loop = false; + return error$1( + RangeError, + 'MASK must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_MASK' + ); + } + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else return this.haveLength(); + } + + /** + * Gets extended payload length (7+16). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength16() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0); + return this.haveLength(); + } + + /** + * Gets extended payload length (7+64). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength64() { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + this._loop = false; + return error$1( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009, + 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' + ); + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + return this.haveLength(); + } + + /** + * Payload length has been read. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + haveLength() { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + this._loop = false; + return error$1( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + getData(cb) { + let data = EMPTY_BUFFER$2; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + + if ( + this._masked && + (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 + ) { + unmask(data, this._mask); + } + } + + if (this._opcode > 0x07) return this.controlMessage(data); + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + // + // This message is not compressed so its length is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + return this.dataMessage(); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate$3.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + return cb( + error$1( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ) + ); + } + + this._fragments.push(buf); + } + + const er = this.dataMessage(); + if (er) return cb(er); + + this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @return {(Error|undefined)} A possible error + * @private + */ + dataMessage() { + if (this._fin) { + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + + if (this._opcode === 2) { + let data; + + if (this._binaryType === 'nodebuffer') { + data = concat(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(concat(fragments, messageLength)); + } else { + data = fragments; + } + + this.emit('message', data, true); + } else { + const buf = concat(fragments, messageLength); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + this._loop = false; + return error$1( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('message', buf, false); + } + } + + this._state = this._allowMultipleEventsPerMicrotask + ? GET_INFO + : WAIT_MICROTASK; + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data) { + if (this._opcode === 0x08) { + this._loop = false; + + if (data.length === 0) { + this.emit('conclude', 1005, EMPTY_BUFFER$2); + this.end(); + } else { + const code = data.readUInt16BE(0); + + if (!isValidStatusCode$1(code)) { + return error$1( + RangeError, + `invalid status code ${code}`, + true, + 1002, + 'WS_ERR_INVALID_CLOSE_CODE' + ); + } + + const buf = new FastBuffer( + data.buffer, + data.byteOffset + 2, + data.length - 2 + ); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + return error$1( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('conclude', code, buf); + this.end(); + } + + this._state = GET_INFO; + return; + } + + this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); + this._state = this._allowMultipleEventsPerMicrotask + ? GET_INFO + : WAIT_MICROTASK; + } +}; + +var receiver = Receiver$1; + +/** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ +function error$1(ErrorCtor, message, prefix, statusCode, errorCode) { + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, error$1); + err.code = errorCode; + err[kStatusCode$1] = statusCode; + return err; +} + +/** + * A shim for `queueMicrotask()`. + * + * @param {Function} cb Callback + */ +function queueMicrotaskShim(cb) { + promise.then(cb).catch(throwErrorNextTick); +} + +/** + * Throws an error. + * + * @param {Error} err The error to throw + * @private + */ +function throwError(err) { + throw err; +} + +/** + * Throws an error in the next tick. + * + * @param {Error} err The error to throw + * @private + */ +function throwErrorNextTick(err) { + process.nextTick(throwError, err); +} + +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */ +const { randomFillSync } = require$$0$a; + +const PerMessageDeflate$2 = permessageDeflate; +const { EMPTY_BUFFER: EMPTY_BUFFER$1 } = constants; +const { isValidStatusCode } = validationExports; +const { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtilExports; + +const kByteLength = Symbol('kByteLength'); +const maskBuffer = Buffer.alloc(4); + +/** + * HyBi Sender implementation. + */ +let Sender$1 = class Sender { + /** + * Creates a Sender instance. + * + * @param {Duplex} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + * @param {Function} [generateMask] The function used to generate the masking + * key + */ + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); + } + + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._deflating = false; + this._queue = []; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {(Buffer|String)} data The data to frame + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {(Buffer|String)[]} The framed data + * @public + */ + static frame(data, options) { + let mask; + let merge = false; + let offset = 2; + let skipMasking = false; + + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + + if (options.generateMask) { + options.generateMask(mask); + } else { + randomFillSync(mask, 0, 4); + } + + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; + } + + let dataLength; + + if (typeof data === 'string') { + if ( + (!options.mask || skipMasking) && + options[kByteLength] !== undefined + ) { + dataLength = options[kByteLength]; + } else { + data = Buffer.from(data); + dataLength = data.length; + } + } else { + dataLength = data.length; + merge = options.mask && options.readOnly && !skipMasking; + } + + let payloadLength = dataLength; + + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + target[1] = payloadLength; + + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); + } + + if (!options.mask) return [target, data]; + + target[1] |= 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (skipMasking) return [target, data]; + + if (merge) { + applyMask(data, mask, target, offset, dataLength); + return [target]; + } + + applyMask(data, mask, data, 0, dataLength); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {(String|Buffer)} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data, mask, cb) { + let buf; + + if (code === undefined) { + buf = EMPTY_BUFFER$1; + } else if (typeof code !== 'number' || !isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + + if (length > 123) { + throw new RangeError('The message must not be greater than 123 bytes'); + } + + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + + if (typeof data === 'string') { + buf.write(data, 2); + } else { + buf.set(data, 2); + } + } + + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x08, + readOnly: false, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(Sender.frame(buf, options), cb); + } + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer$1(data); + byteLength = data.length; + readOnly = toBuffer$1.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x09, + readOnly, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer$1(data); + byteLength = data.length; + readOnly = toBuffer$1.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x0a, + readOnly, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer$1(data); + byteLength = data.length; + readOnly = toBuffer$1.readOnly; + } + + if (this._firstFragment) { + this._firstFragment = false; + if ( + rsv1 && + perMessageDeflate && + perMessageDeflate.params[ + perMessageDeflate._isServer + ? 'server_no_context_takeover' + : 'client_no_context_takeover' + ] + ) { + rsv1 = byteLength >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + if (perMessageDeflate) { + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } else { + this.sendFrame( + Sender.frame(data, { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1: false + }), + cb + ); + } + } + + /** + * Dispatches a message. + * + * @param {(Buffer|String)} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName]; + + this._bufferedBytes += options[kByteLength]; + this._deflating = true; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while data was being compressed' + ); + + if (typeof cb === 'function') cb(err); + + for (let i = 0; i < this._queue.length; i++) { + const params = this._queue[i]; + const callback = params[params.length - 1]; + + if (typeof callback === 'function') callback(err); + } + + return; + } + + this._bufferedBytes -= options[kByteLength]; + this._deflating = false; + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (!this._deflating && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {Buffer[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } +}; + +var sender = Sender$1; + +const { kForOnEventAttribute: kForOnEventAttribute$1, kListener: kListener$1 } = constants; + +const kCode = Symbol('kCode'); +const kData = Symbol('kData'); +const kError = Symbol('kError'); +const kMessage = Symbol('kMessage'); +const kReason = Symbol('kReason'); +const kTarget = Symbol('kTarget'); +const kType = Symbol('kType'); +const kWasClean = Symbol('kWasClean'); + +/** + * Class representing an event. + */ +let Event$1 = class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @throws {TypeError} If the `type` argument is not specified + */ + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + + /** + * @type {*} + */ + get target() { + return this[kTarget]; + } + + /** + * @type {String} + */ + get type() { + return this[kType]; + } +}; + +Object.defineProperty(Event$1.prototype, 'target', { enumerable: true }); +Object.defineProperty(Event$1.prototype, 'type', { enumerable: true }); + +/** + * Class representing a close event. + * + * @extends Event + */ +class CloseEvent extends Event$1 { + /** + * Create a new `CloseEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {Number} [options.code=0] The status code explaining why the + * connection was closed + * @param {String} [options.reason=''] A human-readable string explaining why + * the connection was closed + * @param {Boolean} [options.wasClean=false] Indicates whether or not the + * connection was cleanly closed + */ + constructor(type, options = {}) { + super(type); + + this[kCode] = options.code === undefined ? 0 : options.code; + this[kReason] = options.reason === undefined ? '' : options.reason; + this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; + } + + /** + * @type {Number} + */ + get code() { + return this[kCode]; + } + + /** + * @type {String} + */ + get reason() { + return this[kReason]; + } + + /** + * @type {Boolean} + */ + get wasClean() { + return this[kWasClean]; + } +} + +Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); + +/** + * Class representing an error event. + * + * @extends Event + */ +class ErrorEvent extends Event$1 { + /** + * Create a new `ErrorEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.error=null] The error that generated this event + * @param {String} [options.message=''] The error message + */ + constructor(type, options = {}) { + super(type); + + this[kError] = options.error === undefined ? null : options.error; + this[kMessage] = options.message === undefined ? '' : options.message; + } + + /** + * @type {*} + */ + get error() { + return this[kError]; + } + + /** + * @type {String} + */ + get message() { + return this[kMessage]; + } +} + +Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); +Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); + +/** + * Class representing a message event. + * + * @extends Event + */ +class MessageEvent extends Event$1 { + /** + * Create a new `MessageEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.data=null] The message content + */ + constructor(type, options = {}) { + super(type); + + this[kData] = options.data === undefined ? null : options.data; + } + + /** + * @type {*} + */ + get data() { + return this[kData]; + } +} + +Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {(Function|Object)} handler The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if ( + !options[kForOnEventAttribute$1] && + listener[kListener$1] === handler && + !listener[kForOnEventAttribute$1] + ) { + return; + } + } + + let wrapper; + + if (type === 'message') { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent('message', { + data: isBinary ? data : data.toString() + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'close') { + wrapper = function onClose(code, message) { + const event = new CloseEvent('close', { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'error') { + wrapper = function onError(error) { + const event = new ErrorEvent('error', { + error, + message: error.message + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'open') { + wrapper = function onOpen() { + const event = new Event$1('open'); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; + } + + wrapper[kForOnEventAttribute$1] = !!options[kForOnEventAttribute$1]; + wrapper[kListener$1] = handler; + + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {(Function|Object)} handler The listener to remove + * @public + */ + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener$1] === handler && !listener[kForOnEventAttribute$1]) { + this.removeListener(type, listener); + break; + } + } + } +}; + +var eventTarget = { + CloseEvent, + ErrorEvent, + Event: Event$1, + EventTarget, + MessageEvent +}; + +/** + * Call an event listener + * + * @param {(Function|Object)} listener The listener to call + * @param {*} thisArg The value to use as `this`` when calling the listener + * @param {Event} event The event to pass to the listener + * @private + */ +function callListener(listener, thisArg, event) { + if (typeof listener === 'object' && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } +} + +const { tokenChars: tokenChars$1 } = validationExports; + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push(dest, name, elem) { + if (dest[name] === undefined) dest[name] = [elem]; + else dest[name].push(elem); +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse$2(header) { + const offers = Object.create(null); + let params = Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + + for (; i < header.length; i++) { + code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars$1[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = Object.create(null); + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars$1[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars$1[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars$1[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22 /* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c /* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars$1[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, params); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format$1(extensions) { + return Object.keys(extensions) + .map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations + .map((params) => { + return [extension] + .concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values + .map((v) => (v === true ? k : `${k}=${v}`)) + .join('; '); + }) + ) + .join('; '); + }) + .join(', '); + }) + .join(', '); +} + +var extension$1 = { format: format$1, parse: parse$2 }; + +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$" }] */ + +const EventEmitter$1 = require$$0$5; +const https$2 = require$$1$2; +const http$3 = require$$1$1; +const net = require$$4$1; +const tls = require$$4$2; +const { randomBytes, createHash: createHash$1 } = require$$0$a; +const { URL: URL$2 } = require$$0$9; + +const PerMessageDeflate$1 = permessageDeflate; +const Receiver = receiver; +const Sender = sender; +const { + BINARY_TYPES, + EMPTY_BUFFER, + GUID: GUID$1, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket: kWebSocket$1, + NOOP +} = constants; +const { + EventTarget: { addEventListener, removeEventListener } +} = eventTarget; +const { format, parse: parse$1 } = extension$1; +const { toBuffer } = bufferUtilExports; + +const closeTimeout = 30 * 1000; +const kAborted = Symbol('kAborted'); +const protocolVersions = [8, 13]; +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +let WebSocket$1 = class WebSocket extends EventEmitter$1 { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._extensions = {}; + this._paused = false; + this._protocol = ''; + this._readyState = WebSocket.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + + if (protocols === undefined) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === 'object' && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } + } + + initAsClient(this, address, protocols, options); + } else { + this._isServer = true; + } + } + + /** + * This deviates from the WHATWG interface since ws doesn't support the + * required default "blob" type (instead we define a custom "nodebuffer" + * type). + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + + return this._socket._writableState.length + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + + /** + * @type {Boolean} + */ + get isPaused() { + return this._paused; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return null; + } + + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + + /** + * @type {String} + */ + get url() { + return this._url; + } + + /** + * Set up the socket and the internal resources. + * + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options Options object + * @param {Boolean} [options.allowMultipleEventsPerMicrotask=false] Specifies + * whether or not to process more than one of the `'message'`, `'ping'`, + * and `'pong'` events per microtask + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.maxPayload=0] The maximum allowed message size + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ + setSocket(socket, head, options) { + const receiver = new Receiver({ + allowMultipleEventsPerMicrotask: options.allowMultipleEventsPerMicrotask, + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + + this._sender = new Sender(socket, this._extensions, options.generateMask); + this._receiver = receiver; + this._socket = socket; + + receiver[kWebSocket$1] = this; + socket[kWebSocket$1] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + // + // These methods may not be available if `socket` is just a `Duplex`. + // + if (socket.setTimeout) socket.setTimeout(0); + if (socket.setNoDelay) socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError$1); + + this._readyState = WebSocket.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate$1.extensionName]) { + this._extensions[PerMessageDeflate$1.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake$1(this, this._req, msg); + return; + } + + if (this.readyState === WebSocket.CLOSING) { + if ( + this._closeFrameSent && + (this._closeFrameReceived || this._receiver._writableState.errorEmitted) + ) { + this._socket.end(); + } + + return; + } + + this._readyState = WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if ( + this._closeFrameReceived || + this._receiver._writableState.errorEmitted + ) { + this._socket.end(); + } + }); + + // + // Specify a timeout for the closing handshake to complete. + // + this._closeTimer = setTimeout( + this._socket.destroy.bind(this._socket), + closeTimeout + ); + } + + /** + * Pause the socket. + * + * @public + */ + pause() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = true; + this._socket.pause(); + } + + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Resume the socket. + * + * @public + */ + resume() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = false; + if (!this._receiver._writableState.needDrain) this._socket.resume(); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + const opts = { + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + + if (!this._extensions[PerMessageDeflate$1.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake$1(this, this._req, msg); + return; + } + + if (this._socket) { + this._readyState = WebSocket.CLOSING; + this._socket.destroy(); + } + } +}; + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket$1, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket$1.prototype, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket + */ +Object.defineProperty(WebSocket$1, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket$1.prototype, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket$1, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket$1.prototype, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket + */ +Object.defineProperty(WebSocket$1, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket$1.prototype, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +[ + 'binaryType', + 'bufferedAmount', + 'extensions', + 'isPaused', + 'protocol', + 'readyState', + 'url' +].forEach((property) => { + Object.defineProperty(WebSocket$1.prototype, property, { enumerable: true }); +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket$1.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + + if (typeof handler !== 'function') return; + + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); +}); + +WebSocket$1.prototype.addEventListener = addEventListener; +WebSocket$1.prototype.removeEventListener = removeEventListener; + +var websocket = WebSocket$1; + +/** + * Initialize a WebSocket client. + * + * @param {WebSocket} websocket The client to initialize + * @param {(String|URL)} address The URL to which to connect + * @param {Array} protocols The subprotocols + * @param {Object} [options] Connection options + * @param {Boolean} [options.allowMultipleEventsPerMicrotask=false] Specifies + * whether or not to process more than one of the `'message'`, `'ping'`, + * and `'pong'` events per microtask + * @param {Function} [options.finishRequest] A function which can be used to + * customize the headers of each http request before it is sent + * @param {Boolean} [options.followRedirects=false] Whether or not to follow + * redirects + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the + * handshake request + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Number} [options.maxRedirects=10] The maximum number of redirects + * allowed + * @param {String} [options.origin] Value of the `Origin` or + * `Sec-WebSocket-Origin` header + * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable + * permessage-deflate + * @param {Number} [options.protocolVersion=13] Value of the + * `Sec-WebSocket-Version` header + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ +function initAsClient(websocket, address, protocols, options) { + const opts = { + allowMultipleEventsPerMicrotask: false, + protocolVersion: protocolVersions[1], + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + createConnection: undefined, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + timeout: undefined, + method: 'GET', + host: undefined, + path: undefined, + port: undefined + }; + + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + let parsedUrl; + + if (address instanceof URL$2) { + parsedUrl = address; + } else { + try { + parsedUrl = new URL$2(address); + } catch (e) { + throw new SyntaxError(`Invalid URL: ${address}`); + } + } + + if (parsedUrl.protocol === 'http:') { + parsedUrl.protocol = 'ws:'; + } else if (parsedUrl.protocol === 'https:') { + parsedUrl.protocol = 'wss:'; + } + + websocket._url = parsedUrl.href; + + const isSecure = parsedUrl.protocol === 'wss:'; + const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; + let invalidUrlMessage; + + if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { + invalidUrlMessage = + 'The URL\'s protocol must be one of "ws:", "wss:", ' + + '"http:", "https", or "ws+unix:"'; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = 'The URL contains a fragment identifier'; + } + + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString('base64'); + const request = isSecure ? https$2.request : http$3.request; + const protocolSet = new Set(); + let perMessageDeflate; + + opts.createConnection = isSecure ? tlsConnect : netConnect; + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith('[') + ? parsedUrl.hostname.slice(1, -1) + : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + 'Sec-WebSocket-Version': opts.protocolVersion, + 'Sec-WebSocket-Key': key, + Connection: 'Upgrade', + Upgrade: 'websocket' + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate$1( + opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, + false, + opts.maxPayload + ); + opts.headers['Sec-WebSocket-Extensions'] = format({ + [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if ( + typeof protocol !== 'string' || + !subprotocolRegex.test(protocol) || + protocolSet.has(protocol) + ) { + throw new SyntaxError( + 'An invalid or duplicated subprotocol was specified' + ); + } + + protocolSet.add(protocol); + } + + opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers['Sec-WebSocket-Origin'] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + + if (isIpcUrl) { + const parts = opts.path.split(':'); + + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + + let req; + + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl + ? opts.socketPath + : parsedUrl.host; + + const headers = options && options.headers; + + // + // Shallow copy the user provided options so that headers can be changed + // without mutating the original object. + // + options = { ...options, headers: {} }; + + if (headers) { + for (const [key, value] of Object.entries(headers)) { + options.headers[key.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount('redirect') === 0) { + const isSameHost = isIpcUrl + ? websocket._originalIpc + ? opts.socketPath === websocket._originalHostOrSocketPath + : false + : websocket._originalIpc + ? false + : parsedUrl.host === websocket._originalHostOrSocketPath; + + if (!isSameHost || (websocket._originalSecure && !isSecure)) { + // + // Match curl 7.77.0 behavior and drop the following headers. These + // headers are also dropped when following a redirect to a subdomain. + // + delete opts.headers.authorization; + delete opts.headers.cookie; + + if (!isSameHost) delete opts.headers.host; + + opts.auth = undefined; + } + } + + // + // Match curl 7.77.0 behavior and make the first `Authorization` header win. + // If the `Authorization` header is set, then there is nothing to do as it + // will take precedence. + // + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = + 'Basic ' + Buffer.from(opts.auth).toString('base64'); + } + + req = websocket._req = request(opts); + + if (websocket._redirects) { + // + // Unlike what is done for the `'upgrade'` event, no early exit is + // triggered here if the user calls `websocket.close()` or + // `websocket.terminate()` from a listener of the `'redirect'` event. This + // is because the user can also call `request.destroy()` with an error + // before calling `websocket.close()` or `websocket.terminate()` and this + // would result in an error being emitted on the `request` object with no + // `'error'` event listeners attached. + // + websocket.emit('redirect', websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + + if (opts.timeout) { + req.on('timeout', () => { + abortHandshake$1(websocket, req, 'Opening handshake has timed out'); + }); + } + + req.on('error', (err) => { + if (req === null || req[kAborted]) return; + + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + + req.on('response', (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + + if ( + location && + opts.followRedirects && + statusCode >= 300 && + statusCode < 400 + ) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake$1(websocket, req, 'Maximum redirects exceeded'); + return; + } + + req.abort(); + + let addr; + + try { + addr = new URL$2(location, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location}`); + emitErrorAndClose(websocket, err); + return; + } + + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit('unexpected-response', req, res)) { + abortHandshake$1( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + + req.on('upgrade', (res, socket, head) => { + websocket.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the + // `'upgrade'` event. + // + if (websocket.readyState !== WebSocket$1.CONNECTING) return; + + req = websocket._req = null; + + if (res.headers.upgrade.toLowerCase() !== 'websocket') { + abortHandshake$1(websocket, socket, 'Invalid Upgrade header'); + return; + } + + const digest = createHash$1('sha1') + .update(key + GUID$1) + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + let protError; + + if (serverProt !== undefined) { + if (!protocolSet.size) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (!protocolSet.has(serverProt)) { + protError = 'Server sent an invalid subprotocol'; + } + } else if (protocolSet.size) { + protError = 'Server sent no subprotocol'; + } + + if (protError) { + abortHandshake$1(websocket, socket, protError); + return; + } + + if (serverProt) websocket._protocol = serverProt; + + const secWebSocketExtensions = res.headers['sec-websocket-extensions']; + + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = + 'Server sent a Sec-WebSocket-Extensions header but no extension ' + + 'was requested'; + abortHandshake$1(websocket, socket, message); + return; + } + + let extensions; + + try { + extensions = parse$1(secWebSocketExtensions); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake$1(websocket, socket, message); + return; + } + + const extensionNames = Object.keys(extensions); + + if ( + extensionNames.length !== 1 || + extensionNames[0] !== PerMessageDeflate$1.extensionName + ) { + const message = 'Server indicated an extension that was not requested'; + abortHandshake$1(websocket, socket, message); + return; + } + + try { + perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake$1(websocket, socket, message); + return; + } + + websocket._extensions[PerMessageDeflate$1.extensionName] = + perMessageDeflate; + } + + websocket.setSocket(socket, head, { + allowMultipleEventsPerMicrotask: opts.allowMultipleEventsPerMicrotask, + generateMask: opts.generateMask, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + + if (opts.finishRequest) { + opts.finishRequest(req, websocket); + } else { + req.end(); + } +} + +/** + * Emit the `'error'` and `'close'` events. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {Error} The error to emit + * @private + */ +function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket$1.CLOSING; + websocket.emit('error', err); + websocket.emitClose(); +} + +/** + * Create a `net.Socket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {net.Socket} The newly created socket used to start the connection + * @private + */ +function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); +} + +/** + * Create a `tls.TLSSocket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {tls.TLSSocket} The newly created socket used to start the connection + * @private + */ +function tlsConnect(options) { + options.path = undefined; + + if (!options.servername && options.servername !== '') { + options.servername = net.isIP(options.host) ? '' : options.host; + } + + return tls.connect(options); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to + * abort or the socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake$1(websocket, stream, message) { + websocket._readyState = WebSocket$1.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake$1); + + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + + if (stream.socket && !stream.socket.destroyed) { + // + // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if + // called after the request completed. See + // https://github.com/websockets/ws/issues/1869. + // + stream.socket.destroy(); + } + + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * Handle cases where the `ping()`, `pong()`, or `send()` methods are called + * when the `readyState` attribute is `CLOSING` or `CLOSED`. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {*} [data] The data to send + * @param {Function} [cb] Callback + * @private + */ +function sendAfterClose(websocket, data, cb) { + if (data) { + const length = toBuffer(data).length; + + // + // The `_bufferedAmount` property is used only when the peer is a client and + // the opening handshake fails. Under these circumstances, in fact, the + // `setSocket()` method is not called, so the `_socket` and `_sender` + // properties are set to `null`. + // + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} ` + + `(${readyStates[websocket.readyState]})` + ); + process.nextTick(cb, err); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {Buffer} reason The reason for closing + * @private + */ +function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket$1]; + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (websocket._socket[kWebSocket$1] === undefined) return; + + websocket._socket.removeListener('data', socketOnData); + process.nextTick(resume, websocket._socket); + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain() { + const websocket = this[kWebSocket$1]; + + if (!websocket.isPaused) websocket._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError(err) { + const websocket = this[kWebSocket$1]; + + if (websocket._socket[kWebSocket$1] !== undefined) { + websocket._socket.removeListener('data', socketOnData); + + // + // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See + // https://github.com/websockets/ws/issues/1940. + // + process.nextTick(resume, websocket._socket); + + websocket.close(err[kStatusCode]); + } + + websocket.emit('error', err); +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish() { + this[kWebSocket$1].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {Buffer|ArrayBuffer|Buffer[])} data The message + * @param {Boolean} isBinary Specifies whether the message is binary or not + * @private + */ +function receiverOnMessage(data, isBinary) { + this[kWebSocket$1].emit('message', data, isBinary); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing(data) { + const websocket = this[kWebSocket$1]; + + websocket.pong(data, !websocket._isServer, NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong(data) { + this[kWebSocket$1].emit('pong', data); +} + +/** + * Resume a readable stream + * + * @param {Readable} stream The readable stream + * @private + */ +function resume(stream) { + stream.resume(); +} + +/** + * The listener of the socket `'close'` event. + * + * @private + */ +function socketOnClose() { + const websocket = this[kWebSocket$1]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + + websocket._readyState = WebSocket$1.CLOSING; + + let chunk; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. If the readable side of the socket is in flowing mode then there is no + // buffered data as everything has been already written and `readable.read()` + // will return `null`. If instead, the socket is paused, any possible buffered + // data will be read as a single chunk. + // + if ( + !this._readableState.endEmitted && + !websocket._closeFrameReceived && + !websocket._receiver._writableState.errorEmitted && + (chunk = websocket._socket.read()) !== null + ) { + websocket._receiver.write(chunk); + } + + websocket._receiver.end(); + + this[kWebSocket$1] = undefined; + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the socket `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData(chunk) { + if (!this[kWebSocket$1]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the socket `'end'` event. + * + * @private + */ +function socketOnEnd() { + const websocket = this[kWebSocket$1]; + + websocket._readyState = WebSocket$1.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the socket `'error'` event. + * + * @private + */ +function socketOnError$1() { + const websocket = this[kWebSocket$1]; + + this.removeListener('error', socketOnError$1); + this.on('error', NOOP); + + if (websocket) { + websocket._readyState = WebSocket$1.CLOSING; + this.destroy(); + } +} + +const { tokenChars } = validationExports; + +/** + * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. + * + * @param {String} header The field value of the header + * @return {Set} The subprotocol names + * @public + */ +function parse(header) { + const protocols = new Set(); + let start = -1; + let end = -1; + let i = 0; + + for (i; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + + const protocol = header.slice(start, end); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + + if (start === -1 || end !== -1) { + throw new SyntaxError('Unexpected end of input'); + } + + const protocol = header.slice(start, i); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + return protocols; +} + +var subprotocol$1 = { parse }; + +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$" }] */ + +const EventEmitter = require$$0$5; +const http$2 = require$$1$1; +const { createHash } = require$$0$a; + +const extension = extension$1; +const PerMessageDeflate = permessageDeflate; +const subprotocol = subprotocol$1; +const WebSocket = websocket; +const { GUID, kWebSocket } = constants; + +const keyRegex = /^[+/0-9A-Za-z]{22}==$/; + +const RUNNING = 0; +const CLOSING = 1; +const CLOSED = 2; + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Boolean} [options.allowMultipleEventsPerMicrotask=false] Specifies + * whether or not to process more than one of the `'message'`, `'ping'`, + * and `'pong'` events per microtask + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` + * class to use. It must be the `WebSocket` class or class that extends it + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + + options = { + allowMultipleEventsPerMicrotask: false, + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + WebSocket, + ...options + }; + + if ( + (options.port == null && !options.server && !options.noServer) || + (options.port != null && (options.server || options.noServer)) || + (options.server && options.noServer) + ) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options ' + + 'must be specified' + ); + } + + if (options.port != null) { + this._server = http$2.createServer((req, res) => { + const body = http$2.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + const emitConnection = this.emit.bind(this, 'connection'); + + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = new Set(); + this._shouldEmitClose = false; + } + + this.options = options; + this._state = RUNNING; + } + + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Stop the server from accepting new connections and emit the `'close'` event + * when all existing connections are closed. + * + * @param {Function} [cb] A one-time listener for the `'close'` event + * @public + */ + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once('close', () => { + cb(new Error('The server is not running')); + }); + } + + process.nextTick(emitClose, this); + return; + } + + if (cb) this.once('close', cb); + + if (this._state === CLOSING) return; + this._state = CLOSING; + + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server = this._server; + + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // The HTTP/S server was created internally. Close it, and rely on its + // `'close'` event. + // + server.close(() => { + emitClose(this); + }); + } + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf('?'); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + + if (pathname !== this.options.path) return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on('error', socketOnError); + + const key = req.headers['sec-websocket-key']; + const version = +req.headers['sec-websocket-version']; + + if (req.method !== 'GET') { + const message = 'Invalid HTTP method'; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); + return; + } + + if (req.headers.upgrade.toLowerCase() !== 'websocket') { + const message = 'Invalid Upgrade header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (!key || !keyRegex.test(key)) { + const message = 'Missing or invalid Sec-WebSocket-Key header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (version !== 8 && version !== 13) { + const message = 'Missing or invalid Sec-WebSocket-Version header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); + return; + } + + const secWebSocketProtocol = req.headers['sec-websocket-protocol']; + let protocols = new Set(); + + if (secWebSocketProtocol !== undefined) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Protocol header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + const secWebSocketExtensions = req.headers['sec-websocket-extensions']; + const extensions = {}; + + if ( + this.options.perMessageDeflate && + secWebSocketExtensions !== undefined + ) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + + try { + const offers = extension.parse(secWebSocketExtensions); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + const message = + 'Invalid or unacceptable Sec-WebSocket-Extensions header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: + req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Set} protocols The subprotocols + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + if (socket[kWebSocket]) { + throw new Error( + 'server.handleUpgrade() was called more than once with the same ' + + 'socket, possibly due to a misconfiguration' + ); + } + + if (this._state > RUNNING) return abortHandshake(socket, 503); + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${digest}` + ]; + + const ws = new this.options.WebSocket(null); + + if (protocols.size) { + // + // Optionally call external protocol selection handler. + // + const protocol = this.options.handleProtocols + ? this.options.handleProtocols(protocols, req) + : protocols.values().next().value; + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, { + allowMultipleEventsPerMicrotask: + this.options.allowMultipleEventsPerMicrotask, + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => { + this.clients.delete(ws); + + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + + cb(ws, req); + } +} + +var websocketServer = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.} map The listeners to add + * @return {Function} A function that will remove the added listeners when + * called + * @private + */ +function addListeners(server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners() { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Emit a `'close'` event on an `EventEmitter`. + * + * @param {EventEmitter} server The event emitter + * @private + */ +function emitClose(server) { + server._state = CLOSED; + server.emit('close'); +} + +/** + * Handle socket errors. + * + * @private + */ +function socketOnError() { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @param {Object} [headers] Additional HTTP response headers + * @private + */ +function abortHandshake(socket, code, message, headers) { + // + // The socket is writable unless the user destroyed or ended it before calling + // `server.handleUpgrade()` or in the `verifyClient` function, which is a user + // error. Handling this does not make much sense as the worst that can happen + // is that some of the data written by the user might be discarded due to the + // call to `socket.end()` below, which triggers an `'error'` event that in + // turn causes the socket to be destroyed. + // + message = message || http$2.STATUS_CODES[code]; + headers = { + Connection: 'close', + 'Content-Type': 'text/html', + 'Content-Length': Buffer.byteLength(message), + ...headers + }; + + socket.once('finish', socket.destroy); + + socket.end( + `HTTP/1.1 ${code} ${http$2.STATUS_CODES[code]}\r\n` + + Object.keys(headers) + .map((h) => `${h}: ${headers[h]}`) + .join('\r\n') + + '\r\n\r\n' + + message + ); +} + +/** + * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least + * one listener for it, otherwise call `abortHandshake()`. + * + * @param {WebSocketServer} server The WebSocket server + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} message The HTTP response body + * @private + */ +function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { + if (server.listenerCount('wsClientError')) { + const err = new Error(message); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + + server.emit('wsClientError', err, socket, req); + } else { + abortHandshake(socket, code, message); + } +} + +var WebSocketServerRaw_ = /*@__PURE__*/getDefaultExportFromCjs(websocketServer); + +/* In Bun, the `ws` module is overridden to hook into the native code. Using the bundled `js` version + * of `ws` will not work as Bun's req.socket does not allow reading/writing to the underlying socket. + */ +const WebSocketServerRaw = process.versions.bun + ? // @ts-expect-error: Bun defines `import.meta.require` + import.meta.require('ws').WebSocketServer + : WebSocketServerRaw_; +const HMR_HEADER = 'vite-hmr'; +const wsServerEvents = [ + 'connection', + 'error', + 'headers', + 'listening', + 'message', +]; +function createWebSocketServer(server, config, httpsOptions) { + let wss; + let wsHttpServer = undefined; + const hmr = isObject$1(config.server.hmr) && config.server.hmr; + const hmrServer = hmr && hmr.server; + const hmrPort = hmr && hmr.port; + // TODO: the main server port may not have been chosen yet as it may use the next available + const portsAreCompatible = !hmrPort || hmrPort === config.server.port; + const wsServer = hmrServer || (portsAreCompatible && server); + let hmrServerWsListener; + const customListeners = new Map(); + const clientsMap = new WeakMap(); + const port = hmrPort || 24678; + const host = (hmr && hmr.host) || undefined; + if (wsServer) { + let hmrBase = config.base; + const hmrPath = hmr ? hmr.path : undefined; + if (hmrPath) { + hmrBase = path$o.posix.join(hmrBase, hmrPath); + } + wss = new WebSocketServerRaw({ noServer: true }); + hmrServerWsListener = (req, socket, head) => { + if (req.headers['sec-websocket-protocol'] === HMR_HEADER && + req.url === hmrBase) { + wss.handleUpgrade(req, socket, head, (ws) => { + wss.emit('connection', ws, req); + }); + } + }; + wsServer.on('upgrade', hmrServerWsListener); + } + else { + // http server request handler keeps the same with + // https://github.com/websockets/ws/blob/45e17acea791d865df6b255a55182e9c42e5877a/lib/websocket-server.js#L88-L96 + const route = ((_, res) => { + const statusCode = 426; + const body = STATUS_CODES[statusCode]; + if (!body) + throw new Error(`No body text found for the ${statusCode} status code`); + res.writeHead(statusCode, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain', + }); + res.end(body); + }); + if (httpsOptions) { + wsHttpServer = createServer$2(httpsOptions, route); + } + else { + wsHttpServer = createServer$3(route); + } + // vite dev server in middleware mode + // need to call ws listen manually + wss = new WebSocketServerRaw({ server: wsHttpServer }); + } + wss.on('connection', (socket) => { + socket.on('message', (raw) => { + if (!customListeners.size) + return; + let parsed; + try { + parsed = JSON.parse(String(raw)); + } + catch { } + if (!parsed || parsed.type !== 'custom' || !parsed.event) + return; + const listeners = customListeners.get(parsed.event); + if (!listeners?.size) + return; + const client = getSocketClient(socket); + listeners.forEach((listener) => listener(parsed.data, client)); + }); + socket.on('error', (err) => { + config.logger.error(`${colors$1.red(`ws error:`)}\n${err.stack}`, { + timestamp: true, + error: err, + }); + }); + socket.send(JSON.stringify({ type: 'connected' })); + if (bufferedError) { + socket.send(JSON.stringify(bufferedError)); + bufferedError = null; + } + }); + wss.on('error', (e) => { + if (e.code === 'EADDRINUSE') { + config.logger.error(colors$1.red(`WebSocket server error: Port is already in use`), { error: e }); + } + else { + config.logger.error(colors$1.red(`WebSocket server error:\n${e.stack || e.message}`), { error: e }); + } + }); + // Provide a wrapper to the ws client so we can send messages in JSON format + // To be consistent with server.ws.send + function getSocketClient(socket) { + if (!clientsMap.has(socket)) { + clientsMap.set(socket, { + send: (...args) => { + let payload; + if (typeof args[0] === 'string') { + payload = { + type: 'custom', + event: args[0], + data: args[1], + }; + } + else { + payload = args[0]; + } + socket.send(JSON.stringify(payload)); + }, + socket, + }); + } + return clientsMap.get(socket); + } + // On page reloads, if a file fails to compile and returns 500, the server + // sends the error payload before the client connection is established. + // If we have no open clients, buffer the error and send it to the next + // connected client. + let bufferedError = null; + return { + listen: () => { + wsHttpServer?.listen(port, host); + }, + on: ((event, fn) => { + if (wsServerEvents.includes(event)) + wss.on(event, fn); + else { + if (!customListeners.has(event)) { + customListeners.set(event, new Set()); + } + customListeners.get(event).add(fn); + } + }), + off: ((event, fn) => { + if (wsServerEvents.includes(event)) { + wss.off(event, fn); + } + else { + customListeners.get(event)?.delete(fn); + } + }), + get clients() { + return new Set(Array.from(wss.clients).map(getSocketClient)); + }, + send(...args) { + let payload; + if (typeof args[0] === 'string') { + payload = { + type: 'custom', + event: args[0], + data: args[1], + }; + } + else { + payload = args[0]; + } + if (payload.type === 'error' && !wss.clients.size) { + bufferedError = payload; + return; + } + const stringified = JSON.stringify(payload); + wss.clients.forEach((client) => { + // readyState 1 means the connection is open + if (client.readyState === 1) { + client.send(stringified); + } + }); + }, + close() { + // should remove listener if hmr.server is set + // otherwise the old listener swallows all WebSocket connections + if (hmrServerWsListener && wsServer) { + wsServer.off('upgrade', hmrServerWsListener); + } + return new Promise((resolve, reject) => { + wss.clients.forEach((client) => { + client.terminate(); + }); + wss.close((err) => { + if (err) { + reject(err); + } + else { + if (wsHttpServer) { + wsHttpServer.close((err) => { + if (err) { + reject(err); + } + else { + resolve(); + } + }); + } + else { + resolve(); + } + } + }); + }); + }, + }; +} + +// this middleware is only active when (base !== '/') +function baseMiddleware(rawBase, middlewareMode) { + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteBaseMiddleware(req, res, next) { + const url = req.url; + const pathname = cleanUrl(url); + const base = rawBase; + if (pathname.startsWith(base)) { + // rewrite url to remove base. this ensures that other middleware does + // not need to consider base being prepended or not + req.url = stripBase(url, base); + return next(); + } + // skip redirect and error fallback on middleware mode, #4057 + if (middlewareMode) { + return next(); + } + if (pathname === '/' || pathname === '/index.html') { + // redirect root visit to based url with search and hash + res.writeHead(302, { + Location: base + url.slice(pathname.length), + }); + res.end(); + return; + } + // non-based page visit + const redirectPath = withTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base; + if (req.headers.accept?.includes('text/html')) { + res.writeHead(404, { + 'Content-Type': 'text/html', + }); + res.end(`The server is configured with a public base URL of ${base} - ` + + `did you mean to visit
${redirectPath} instead?`); + return; + } + else { + // not found for resources + res.writeHead(404, { + 'Content-Type': 'text/plain', + }); + res.end(`The server is configured with a public base URL of ${base} - ` + + `did you mean to visit ${redirectPath} instead?`); + return; + } + }; +} + +var httpProxy$3 = {exports: {}}; + +var eventemitter3 = {exports: {}}; + +(function (module) { + + var has = Object.prototype.hasOwnProperty + , prefix = '~'; + + /** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ + function Events() {} + + // + // We try to not inherit from `Object.prototype`. In some engines creating an + // instance in this way is faster than calling `Object.create(null)` directly. + // If `Object.create(null)` is not supported we prefix the event names with a + // character to make sure that the built-in object properties are not + // overridden or used as an attack vector. + // + if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; + } + + /** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + + /** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ + function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } + + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + + return emitter; + } + + /** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; + } + + /** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } + + /** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ + EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; + }; + + /** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; + + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + + return ee; + }; + + /** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; + + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; + }; + + /** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; + }; + + /** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); + }; + + /** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); + }; + + /** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + + return this; + }; + + /** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; + }; + + // + // Alias methods names because people roll like that. + // + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + + // + // Expose the prefix. + // + EventEmitter.prefixed = prefix; + + // + // Allow `EventEmitter` to be imported as module namespace. + // + EventEmitter.EventEmitter = EventEmitter; + + // + // Expose the module. + // + { + module.exports = EventEmitter; + } +} (eventemitter3)); + +var eventemitter3Exports = eventemitter3.exports; + +var common$3 = {}; + +/** + * Check if we're required to add a port number. + * + * @see https://url.spec.whatwg.org/#default-port + * @param {Number|String} port Port number we need to check + * @param {String} protocol Protocol we need to check against. + * @returns {Boolean} Is it a default port for the given protocol + * @api private + */ +var requiresPort = function required(port, protocol) { + protocol = protocol.split(':')[0]; + port = +port; + + if (!port) return false; + + switch (protocol) { + case 'http': + case 'ws': + return port !== 80; + + case 'https': + case 'wss': + return port !== 443; + + case 'ftp': + return port !== 21; + + case 'gopher': + return port !== 70; + + case 'file': + return false; + } + + return port !== 0; +}; + +(function (exports) { + var common = exports, + url = require$$0$9, + extend = require$$0$6._extend, + required = requiresPort; + + var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i, + isSSL = /^https|wss/; + + /** + * Simple Regex for testing if protocol is https + */ + common.isSSL = isSSL; + /** + * Copies the right headers from `options` and `req` to + * `outgoing` which is then used to fire the proxied + * request. + * + * Examples: + * + * common.setupOutgoing(outgoing, options, req) + * // => { host: ..., hostname: ...} + * + * @param {Object} Outgoing Base object to be filled with required properties + * @param {Object} Options Config object passed to the proxy + * @param {ClientRequest} Req Request Object + * @param {String} Forward String to select forward or target + *  + * @return {Object} Outgoing Object with all required properties set + * + * @api private + */ + + common.setupOutgoing = function(outgoing, options, req, forward) { + outgoing.port = options[forward || 'target'].port || + (isSSL.test(options[forward || 'target'].protocol) ? 443 : 80); + + ['host', 'hostname', 'socketPath', 'pfx', 'key', + 'passphrase', 'cert', 'ca', 'ciphers', 'secureProtocol'].forEach( + function(e) { outgoing[e] = options[forward || 'target'][e]; } + ); + + outgoing.method = options.method || req.method; + outgoing.headers = extend({}, req.headers); + + if (options.headers){ + extend(outgoing.headers, options.headers); + } + + if (options.auth) { + outgoing.auth = options.auth; + } + + if (options.ca) { + outgoing.ca = options.ca; + } + + if (isSSL.test(options[forward || 'target'].protocol)) { + outgoing.rejectUnauthorized = (typeof options.secure === "undefined") ? true : options.secure; + } + + + outgoing.agent = options.agent || false; + outgoing.localAddress = options.localAddress; + + // + // Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do + // as node core doesn't handle this COMPLETELY properly yet. + // + if (!outgoing.agent) { + outgoing.headers = outgoing.headers || {}; + if (typeof outgoing.headers.connection !== 'string' + || !upgradeHeader.test(outgoing.headers.connection) + ) { outgoing.headers.connection = 'close'; } + } + + + // the final path is target path + relative path requested by user: + var target = options[forward || 'target']; + var targetPath = target && options.prependPath !== false + ? (target.path || '') + : ''; + + // + // Remark: Can we somehow not use url.parse as a perf optimization? + // + var outgoingPath = !options.toProxy + ? (url.parse(req.url).path || '') + : req.url; + + // + // Remark: ignorePath will just straight up ignore whatever the request's + // path is. This can be labeled as FOOT-GUN material if you do not know what + // you are doing and are using conflicting options. + // + outgoingPath = !options.ignorePath ? outgoingPath : ''; + + outgoing.path = common.urlJoin(targetPath, outgoingPath); + + if (options.changeOrigin) { + outgoing.headers.host = + required(outgoing.port, options[forward || 'target'].protocol) && !hasPort(outgoing.host) + ? outgoing.host + ':' + outgoing.port + : outgoing.host; + } + return outgoing; + }; + + /** + * Set the proper configuration for sockets, + * set no delay and set keep alive, also set + * the timeout to 0. + * + * Examples: + * + * common.setupSocket(socket) + * // => Socket + * + * @param {Socket} Socket instance to setup + *  + * @return {Socket} Return the configured socket. + * + * @api private + */ + + common.setupSocket = function(socket) { + socket.setTimeout(0); + socket.setNoDelay(true); + + socket.setKeepAlive(true, 0); + + return socket; + }; + + /** + * Get the port number from the host. Or guess it based on the connection type. + * + * @param {Request} req Incoming HTTP request. + * + * @return {String} The port number. + * + * @api private + */ + common.getPort = function(req) { + var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : ''; + + return res ? + res[1] : + common.hasEncryptedConnection(req) ? '443' : '80'; + }; + + /** + * Check if the request has an encrypted connection. + * + * @param {Request} req Incoming HTTP request. + * + * @return {Boolean} Whether the connection is encrypted or not. + * + * @api private + */ + common.hasEncryptedConnection = function(req) { + return Boolean(req.connection.encrypted || req.connection.pair); + }; + + /** + * OS-agnostic join (doesn't break on URLs like path.join does on Windows)> + * + * @return {String} The generated path. + * + * @api private + */ + + common.urlJoin = function() { + // + // We do not want to mess with the query string. All we want to touch is the path. + // + var args = Array.prototype.slice.call(arguments), + lastIndex = args.length - 1, + last = args[lastIndex], + lastSegs = last.split('?'), + retSegs; + + args[lastIndex] = lastSegs.shift(); + + // + // Join all strings, but remove empty strings so we don't get extra slashes from + // joining e.g. ['', 'am'] + // + retSegs = [ + args.filter(Boolean).join('/') + .replace(/\/+/g, '/') + .replace('http:/', 'http://') + .replace('https:/', 'https://') + ]; + + // Only join the query string if it exists so we don't have trailing a '?' + // on every request + + // Handle case where there could be multiple ? in the URL. + retSegs.push.apply(retSegs, lastSegs); + + return retSegs.join('?') + }; + + /** + * Rewrites or removes the domain of a cookie header + * + * @param {String|Array} Header + * @param {Object} Config, mapping of domain to rewritten domain. + * '*' key to match any domain, null value to remove the domain. + * + * @api private + */ + common.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) { + if (Array.isArray(header)) { + return header.map(function (headerElement) { + return rewriteCookieProperty(headerElement, config, property); + }); + } + return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", 'i'), function(match, prefix, previousValue) { + var newValue; + if (previousValue in config) { + newValue = config[previousValue]; + } else if ('*' in config) { + newValue = config['*']; + } else { + //no match, return previous value + return match; + } + if (newValue) { + //replace value + return prefix + newValue; + } else { + //remove value + return ''; + } + }); + }; + + /** + * Check the host and see if it potentially has a port in it (keep it simple) + * + * @returns {Boolean} Whether we have one or not + * + * @api private + */ + function hasPort(host) { + return !!~host.indexOf(':'); + }} (common$3)); + +var url$1 = require$$0$9, + common$2 = common$3; + + +var redirectRegex = /^201|30(1|2|7|8)$/; + +/*! + * Array of passes. + * + * A `pass` is just a function that is executed on `req, res, options` + * so that you can easily add new checks while still keeping the base + * flexible. + */ + +var webOutgoing = { // <-- + + /** + * If is a HTTP 1.0 request, remove chunk headers + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {proxyResponse} Res Response object from the proxy request + * + * @api private + */ + removeChunked: function removeChunked(req, res, proxyRes) { + if (req.httpVersion === '1.0') { + delete proxyRes.headers['transfer-encoding']; + } + }, + + /** + * If is a HTTP 1.0 request, set the correct connection header + * or if connection header not present, then use `keep-alive` + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {proxyResponse} Res Response object from the proxy request + * + * @api private + */ + setConnection: function setConnection(req, res, proxyRes) { + if (req.httpVersion === '1.0') { + proxyRes.headers.connection = req.headers.connection || 'close'; + } else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) { + proxyRes.headers.connection = req.headers.connection || 'keep-alive'; + } + }, + + setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) { + if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite) + && proxyRes.headers['location'] + && redirectRegex.test(proxyRes.statusCode)) { + var target = url$1.parse(options.target); + var u = url$1.parse(proxyRes.headers['location']); + + // make sure the redirected host matches the target host before rewriting + if (target.host != u.host) { + return; + } + + if (options.hostRewrite) { + u.host = options.hostRewrite; + } else if (options.autoRewrite) { + u.host = req.headers['host']; + } + if (options.protocolRewrite) { + u.protocol = options.protocolRewrite; + } + + proxyRes.headers['location'] = u.format(); + } + }, + /** + * Copy headers from proxyResponse to response + * set each header in response object. + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {proxyResponse} Res Response object from the proxy request + * @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain + * + * @api private + */ + writeHeaders: function writeHeaders(req, res, proxyRes, options) { + var rewriteCookieDomainConfig = options.cookieDomainRewrite, + rewriteCookiePathConfig = options.cookiePathRewrite, + preserveHeaderKeyCase = options.preserveHeaderKeyCase, + rawHeaderKeyMap, + setHeader = function(key, header) { + if (header == undefined) return; + if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') { + header = common$2.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain'); + } + if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') { + header = common$2.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path'); + } + res.setHeader(String(key).trim(), header); + }; + + if (typeof rewriteCookieDomainConfig === 'string') { //also test for '' + rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig }; + } + + if (typeof rewriteCookiePathConfig === 'string') { //also test for '' + rewriteCookiePathConfig = { '*': rewriteCookiePathConfig }; + } + + // message.rawHeaders is added in: v0.11.6 + // https://nodejs.org/api/http.html#http_message_rawheaders + if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) { + rawHeaderKeyMap = {}; + for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) { + var key = proxyRes.rawHeaders[i]; + rawHeaderKeyMap[key.toLowerCase()] = key; + } + } + + Object.keys(proxyRes.headers).forEach(function(key) { + var header = proxyRes.headers[key]; + if (preserveHeaderKeyCase && rawHeaderKeyMap) { + key = rawHeaderKeyMap[key] || key; + } + setHeader(key, header); + }); + }, + + /** + * Set the statusCode from the proxyResponse + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {proxyResponse} Res Response object from the proxy request + * + * @api private + */ + writeStatusCode: function writeStatusCode(req, res, proxyRes) { + // From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers]) + if(proxyRes.statusMessage) { + res.statusCode = proxyRes.statusCode; + res.statusMessage = proxyRes.statusMessage; + } else { + res.statusCode = proxyRes.statusCode; + } + } + +}; + +var followRedirects$1 = {exports: {}}; + +var debug$9; + +var debug_1 = function () { + if (!debug$9) { + try { + /* eslint global-require: off */ + debug$9 = srcExports$1("follow-redirects"); + } + catch (error) { /* */ } + if (typeof debug$9 !== "function") { + debug$9 = function () { /* */ }; + } + } + debug$9.apply(null, arguments); +}; + +var url = require$$0$9; +var URL$1 = url.URL; +var http$1 = require$$1$1; +var https$1 = require$$1$2; +var Writable = require$$0$7.Writable; +var assert = require$$5; +var debug$8 = debug_1; + +// Create handlers that pass events from native requests +var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; +var eventHandlers = Object.create(null); +events.forEach(function (event) { + eventHandlers[event] = function (arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); + }; +}); + +// Error types with codes +var RedirectionError = createErrorType( + "ERR_FR_REDIRECTION_FAILURE", + "Redirected request failed" +); +var TooManyRedirectsError = createErrorType( + "ERR_FR_TOO_MANY_REDIRECTS", + "Maximum number of redirects exceeded" +); +var MaxBodyLengthExceededError = createErrorType( + "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", + "Request body larger than maxBodyLength limit" +); +var WriteAfterEndError = createErrorType( + "ERR_STREAM_WRITE_AFTER_END", + "write after end" +); + +// An HTTP(S) request that can be redirected +function RedirectableRequest(options, responseCallback) { + // Initialize the request + Writable.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; + + // Attach a callback if passed + if (responseCallback) { + this.on("response", responseCallback); + } + + // React to responses of native requests + var self = this; + this._onNativeResponse = function (response) { + self._processResponse(response); + }; + + // Perform the first request + this._performRequest(); +} +RedirectableRequest.prototype = Object.create(Writable.prototype); + +RedirectableRequest.prototype.abort = function () { + abortRequest(this._currentRequest); + this.emit("abort"); +}; + +// Writes buffered data to the current native request +RedirectableRequest.prototype.write = function (data, encoding, callback) { + // Writing is not allowed if end has been called + if (this._ending) { + throw new WriteAfterEndError(); + } + + // Validate input and shift parameters if necessary + if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); + } + if (typeof encoding === "function") { + callback = encoding; + encoding = null; + } + + // Ignore empty buffers, since writing them doesn't invoke the callback + // https://github.com/nodejs/node/issues/22066 + if (data.length === 0) { + if (callback) { + callback(); + } + return; + } + // Only write when we don't exceed the maximum body length + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data: data, encoding: encoding }); + this._currentRequest.write(data, encoding, callback); + } + // Error when we exceed the maximum body length + else { + this.emit("error", new MaxBodyLengthExceededError()); + this.abort(); + } +}; + +// Ends the current native request +RedirectableRequest.prototype.end = function (data, encoding, callback) { + // Shift parameters if necessary + if (typeof data === "function") { + callback = data; + data = encoding = null; + } + else if (typeof encoding === "function") { + callback = encoding; + encoding = null; + } + + // Write data if needed and end + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); + } + else { + var self = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function () { + self._ended = true; + currentRequest.end(null, null, callback); + }); + this._ending = true; + } +}; + +// Sets a header value on the current native request +RedirectableRequest.prototype.setHeader = function (name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); +}; + +// Clears a header value on the current native request +RedirectableRequest.prototype.removeHeader = function (name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); +}; + +// Global timeout for all underlying requests +RedirectableRequest.prototype.setTimeout = function (msecs, callback) { + var self = this; + + // Destroys the socket on timeout + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); + } + + // Sets up a timer to trigger a timeout event + function startTimer(socket) { + if (self._timeout) { + clearTimeout(self._timeout); + } + self._timeout = setTimeout(function () { + self.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } + + // Stops a timeout from triggering + function clearTimer() { + // Clear the timeout + if (self._timeout) { + clearTimeout(self._timeout); + self._timeout = null; + } + + // Clean up all attached listeners + self.removeListener("abort", clearTimer); + self.removeListener("error", clearTimer); + self.removeListener("response", clearTimer); + if (callback) { + self.removeListener("timeout", callback); + } + if (!self.socket) { + self._currentRequest.removeListener("socket", startTimer); + } + } + + // Attach callback if passed + if (callback) { + this.on("timeout", callback); + } + + // Start the timer if or when the socket is opened + if (this.socket) { + startTimer(this.socket); + } + else { + this._currentRequest.once("socket", startTimer); + } + + // Clean up on events + this.on("socket", destroyOnTimeout); + this.on("abort", clearTimer); + this.on("error", clearTimer); + this.on("response", clearTimer); + + return this; +}; + +// Proxy all other public ClientRequest methods +[ + "flushHeaders", "getHeader", + "setNoDelay", "setSocketKeepAlive", +].forEach(function (method) { + RedirectableRequest.prototype[method] = function (a, b) { + return this._currentRequest[method](a, b); + }; +}); + +// Proxy all public ClientRequest properties +["aborted", "connection", "socket"].forEach(function (property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function () { return this._currentRequest[property]; }, + }); +}); + +RedirectableRequest.prototype._sanitizeOptions = function (options) { + // Ensure headers are always present + if (!options.headers) { + options.headers = {}; + } + + // Since http.request treats host as an alias of hostname, + // but the url module interprets host as hostname plus port, + // eliminate the host property to avoid confusion. + if (options.host) { + // Use hostname if set, because it has precedence + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } + + // Complete the URL object when necessary + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } + else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } +}; + + +// Executes the next native request (initial or redirect) +RedirectableRequest.prototype._performRequest = function () { + // Load the native protocol + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + this.emit("error", new TypeError("Unsupported protocol " + protocol)); + return; + } + + // If specified, use the agent corresponding to the protocol + // (HTTP and HTTPS use different types of agents) + if (this._options.agents) { + var scheme = protocol.slice(0, -1); + this._options.agent = this._options.agents[scheme]; + } + + // Create the native request + var request = this._currentRequest = + nativeProtocol.request(this._options, this._onNativeResponse); + this._currentUrl = url.format(this._options); + + // Set up event handlers + request._redirectable = this; + for (var e = 0; e < events.length; e++) { + request.on(events[e], eventHandlers[events[e]]); + } + + // End a redirected request + // (The first request must be ended explicitly with RedirectableRequest#end) + if (this._isRedirect) { + // Write the request entity and end. + var i = 0; + var self = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + // Only write if this request has not been redirected yet + /* istanbul ignore else */ + if (request === self._currentRequest) { + // Report any write errors + /* istanbul ignore if */ + if (error) { + self.emit("error", error); + } + // Write the next buffer if there are still left + else if (i < buffers.length) { + var buffer = buffers[i++]; + /* istanbul ignore else */ + if (!request.finished) { + request.write(buffer.data, buffer.encoding, writeNext); + } + } + // End the request if `end` has been called on us + else if (self._ended) { + request.end(); + } + } + }()); + } +}; + +// Processes a response from the current native request +RedirectableRequest.prototype._processResponse = function (response) { + // Store the redirected response + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode: statusCode, + }); + } + + // RFC7231§6.4: The 3xx (Redirection) class of status code indicates + // that further action needs to be taken by the user agent in order to + // fulfill the request. If a Location header field is provided, + // the user agent MAY automatically redirect its request to the URI + // referenced by the Location field value, + // even if the specific status code is not understood. + + // If the response is not a redirect; return it as-is + var location = response.headers.location; + if (!location || this._options.followRedirects === false || + statusCode < 300 || statusCode >= 400) { + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); + + // Clean up + this._requestBodyBuffers = []; + return; + } + + // The response is a redirect, so abort the current request + abortRequest(this._currentRequest); + // Discard the remainder of the response to avoid waiting for data + response.destroy(); + + // RFC7231§6.4: A client SHOULD detect and intervene + // in cyclical redirections (i.e., "infinite" redirection loops). + if (++this._redirectCount > this._options.maxRedirects) { + this.emit("error", new TooManyRedirectsError()); + return; + } + + // Store the request headers if applicable + var requestHeaders; + var beforeRedirect = this._options.beforeRedirect; + if (beforeRedirect) { + requestHeaders = Object.assign({ + // The Host header was set by nativeProtocol.request + Host: response.req.getHeader("host"), + }, this._options.headers); + } + + // RFC7231§6.4: Automatic redirection needs to done with + // care for methods not known to be safe, […] + // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change + // the request method from POST to GET for the subsequent request. + var method = this._options.method; + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || + // RFC7231§6.4.4: The 303 (See Other) status code indicates that + // the server is redirecting the user agent to a different resource […] + // A user agent can perform a retrieval request targeting that URI + // (a GET or HEAD request if using HTTP) […] + (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + // Drop a possible entity and headers related to it + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); + } + + // Drop the Host header, as the redirect might lead to a different host + var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); + + // If the redirect is relative, carry over the host of the last request + var currentUrlParts = url.parse(this._currentUrl); + var currentHost = currentHostHeader || currentUrlParts.host; + var currentUrl = /^\w+:/.test(location) ? this._currentUrl : + url.format(Object.assign(currentUrlParts, { host: currentHost })); + + // Determine the URL of the redirection + var redirectUrl; + try { + redirectUrl = url.resolve(currentUrl, location); + } + catch (cause) { + this.emit("error", new RedirectionError(cause)); + return; + } + + // Create the redirected request + debug$8("redirecting to", redirectUrl); + this._isRedirect = true; + var redirectUrlParts = url.parse(redirectUrl); + Object.assign(this._options, redirectUrlParts); + + // Drop confidential headers when redirecting to a less secure protocol + // or to a different domain that is not a superdomain + if (redirectUrlParts.protocol !== currentUrlParts.protocol && + redirectUrlParts.protocol !== "https:" || + redirectUrlParts.host !== currentHost && + !isSubdomain(redirectUrlParts.host, currentHost)) { + removeMatchingHeaders(/^(?:authorization|cookie)$/i, this._options.headers); + } + + // Evaluate the beforeRedirect callback + if (typeof beforeRedirect === "function") { + var responseDetails = { + headers: response.headers, + statusCode: statusCode, + }; + var requestDetails = { + url: currentUrl, + method: method, + headers: requestHeaders, + }; + try { + beforeRedirect(this._options, responseDetails, requestDetails); + } + catch (err) { + this.emit("error", err); + return; + } + this._sanitizeOptions(this._options); + } + + // Perform the redirected request + try { + this._performRequest(); + } + catch (cause) { + this.emit("error", new RedirectionError(cause)); + } +}; + +// Wraps the key/value object of protocols with redirect functionality +function wrap(protocols) { + // Default settings + var exports = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024, + }; + + // Wrap each protocol + var nativeProtocols = {}; + Object.keys(protocols).forEach(function (scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); + + // Executes a request, following redirects + function request(input, options, callback) { + // Parse parameters + if (typeof input === "string") { + var urlStr = input; + try { + input = urlToOptions(new URL$1(urlStr)); + } + catch (err) { + /* istanbul ignore next */ + input = url.parse(urlStr); + } + } + else if (URL$1 && (input instanceof URL$1)) { + input = urlToOptions(input); + } + else { + callback = options; + options = input; + input = { protocol: protocol }; + } + if (typeof options === "function") { + callback = options; + options = null; + } + + // Set defaults + options = Object.assign({ + maxRedirects: exports.maxRedirects, + maxBodyLength: exports.maxBodyLength, + }, input, options); + options.nativeProtocols = nativeProtocols; + + assert.equal(options.protocol, protocol, "protocol mismatch"); + debug$8("options", options); + return new RedirectableRequest(options, callback); + } + + // Executes a GET request, following redirects + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } + + // Expose the properties on the wrapped protocol + Object.defineProperties(wrappedProtocol, { + request: { value: request, configurable: true, enumerable: true, writable: true }, + get: { value: get, configurable: true, enumerable: true, writable: true }, + }); + }); + return exports; +} + +/* istanbul ignore next */ +function noop$2() { /* empty */ } + +// from https://github.com/nodejs/node/blob/master/lib/internal/url.js +function urlToOptions(urlObject) { + var options = { + protocol: urlObject.protocol, + hostname: urlObject.hostname.startsWith("[") ? + /* istanbul ignore next */ + urlObject.hostname.slice(1, -1) : + urlObject.hostname, + hash: urlObject.hash, + search: urlObject.search, + pathname: urlObject.pathname, + path: urlObject.pathname + urlObject.search, + href: urlObject.href, + }; + if (urlObject.port !== "") { + options.port = Number(urlObject.port); + } + return options; +} + +function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; + } + } + return (lastValue === null || typeof lastValue === "undefined") ? + undefined : String(lastValue).trim(); +} + +function createErrorType(code, defaultMessage) { + function CustomError(cause) { + Error.captureStackTrace(this, this.constructor); + if (!cause) { + this.message = defaultMessage; + } + else { + this.message = defaultMessage + ": " + cause.message; + this.cause = cause; + } + } + CustomError.prototype = new Error(); + CustomError.prototype.constructor = CustomError; + CustomError.prototype.name = "Error [" + code + "]"; + CustomError.prototype.code = code; + return CustomError; +} + +function abortRequest(request) { + for (var e = 0; e < events.length; e++) { + request.removeListener(events[e], eventHandlers[events[e]]); + } + request.on("error", noop$2); + request.abort(); +} + +function isSubdomain(subdomain, domain) { + const dot = subdomain.length - domain.length - 1; + return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); +} + +// Exports +followRedirects$1.exports = wrap({ http: http$1, https: https$1 }); +followRedirects$1.exports.wrap = wrap; + +var followRedirectsExports = followRedirects$1.exports; + +var httpNative = require$$1$1, + httpsNative = require$$1$2, + web_o = webOutgoing, + common$1 = common$3, + followRedirects = followRedirectsExports; + +web_o = Object.keys(web_o).map(function(pass) { + return web_o[pass]; +}); + +var nativeAgents = { http: httpNative, https: httpsNative }; + +/*! + * Array of passes. + * + * A `pass` is just a function that is executed on `req, res, options` + * so that you can easily add new checks while still keeping the base + * flexible. + */ + + +var webIncoming = { + + /** + * Sets `content-length` to '0' if request is of DELETE type. + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {Object} Options Config object passed to the proxy + * + * @api private + */ + + deleteLength: function deleteLength(req, res, options) { + if((req.method === 'DELETE' || req.method === 'OPTIONS') + && !req.headers['content-length']) { + req.headers['content-length'] = '0'; + delete req.headers['transfer-encoding']; + } + }, + + /** + * Sets timeout in request socket if it was specified in options. + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {Object} Options Config object passed to the proxy + * + * @api private + */ + + timeout: function timeout(req, res, options) { + if(options.timeout) { + req.socket.setTimeout(options.timeout); + } + }, + + /** + * Sets `x-forwarded-*` headers if specified in config. + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {Object} Options Config object passed to the proxy + * + * @api private + */ + + XHeaders: function XHeaders(req, res, options) { + if(!options.xfwd) return; + + var encrypted = req.isSpdy || common$1.hasEncryptedConnection(req); + var values = { + for : req.connection.remoteAddress || req.socket.remoteAddress, + port : common$1.getPort(req), + proto: encrypted ? 'https' : 'http' + }; + + ['for', 'port', 'proto'].forEach(function(header) { + req.headers['x-forwarded-' + header] = + (req.headers['x-forwarded-' + header] || '') + + (req.headers['x-forwarded-' + header] ? ',' : '') + + values[header]; + }); + + req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || ''; + }, + + /** + * Does the actual proxying. If `forward` is enabled fires up + * a ForwardStream, same happens for ProxyStream. The request + * just dies otherwise. + * + * @param {ClientRequest} Req Request object + * @param {IncomingMessage} Res Response object + * @param {Object} Options Config object passed to the proxy + * + * @api private + */ + + stream: function stream(req, res, options, _, server, clb) { + + // And we begin! + server.emit('start', req, res, options.target || options.forward); + + var agents = options.followRedirects ? followRedirects : nativeAgents; + var http = agents.http; + var https = agents.https; + + if(options.forward) { + // If forward enable, so just pipe the request + var forwardReq = (options.forward.protocol === 'https:' ? https : http).request( + common$1.setupOutgoing(options.ssl || {}, options, req, 'forward') + ); + + // error handler (e.g. ECONNRESET, ECONNREFUSED) + // Handle errors on incoming request as well as it makes sense to + var forwardError = createErrorHandler(forwardReq, options.forward); + req.on('error', forwardError); + forwardReq.on('error', forwardError); + + (options.buffer || req).pipe(forwardReq); + if(!options.target) { return res.end(); } + } + + // Request initalization + var proxyReq = (options.target.protocol === 'https:' ? https : http).request( + common$1.setupOutgoing(options.ssl || {}, options, req) + ); + + // Enable developers to modify the proxyReq before headers are sent + proxyReq.on('socket', function(socket) { + if(server && !proxyReq.getHeader('expect')) { + server.emit('proxyReq', proxyReq, req, res, options); + } + }); + + // allow outgoing socket to timeout so that we could + // show an error page at the initial request + if(options.proxyTimeout) { + proxyReq.setTimeout(options.proxyTimeout, function() { + proxyReq.abort(); + }); + } + + // Ensure we abort proxy if request is aborted + req.on('aborted', function () { + proxyReq.abort(); + }); + + // handle errors in proxy and incoming request, just like for forward proxy + var proxyError = createErrorHandler(proxyReq, options.target); + req.on('error', proxyError); + proxyReq.on('error', proxyError); + + function createErrorHandler(proxyReq, url) { + return function proxyError(err) { + if (req.socket.destroyed && err.code === 'ECONNRESET') { + server.emit('econnreset', err, req, res, url); + return proxyReq.abort(); + } + + if (clb) { + clb(err, req, res, url); + } else { + server.emit('error', err, req, res, url); + } + } + } + + (options.buffer || req).pipe(proxyReq); + + proxyReq.on('response', function(proxyRes) { + if(server) { server.emit('proxyRes', proxyRes, req, res); } + + if(!res.headersSent && !options.selfHandleResponse) { + for(var i=0; i < web_o.length; i++) { + if(web_o[i](req, res, proxyRes, options)) { break; } + } + } + + if (!res.finished) { + // Allow us to listen when the proxy has completed + proxyRes.on('end', function () { + if (server) server.emit('end', req, res, proxyRes); + }); + // We pipe to the response unless its expected to be handled by the user + if (!options.selfHandleResponse) proxyRes.pipe(res); + } else { + if (server) server.emit('end', req, res, proxyRes); + } + }); + } + +}; + +var http = require$$1$1, + https = require$$1$2, + common = common$3; + +/*! + * Array of passes. + * + * A `pass` is just a function that is executed on `req, socket, options` + * so that you can easily add new checks while still keeping the base + * flexible. + */ + +/* + * Websockets Passes + * + */ + + +var wsIncoming = { + /** + * WebSocket requests must have the `GET` method and + * the `upgrade:websocket` header + * + * @param {ClientRequest} Req Request object + * @param {Socket} Websocket + * + * @api private + */ + + checkMethodAndHeader : function checkMethodAndHeader(req, socket) { + if (req.method !== 'GET' || !req.headers.upgrade) { + socket.destroy(); + return true; + } + + if (req.headers.upgrade.toLowerCase() !== 'websocket') { + socket.destroy(); + return true; + } + }, + + /** + * Sets `x-forwarded-*` headers if specified in config. + * + * @param {ClientRequest} Req Request object + * @param {Socket} Websocket + * @param {Object} Options Config object passed to the proxy + * + * @api private + */ + + XHeaders : function XHeaders(req, socket, options) { + if(!options.xfwd) return; + + var values = { + for : req.connection.remoteAddress || req.socket.remoteAddress, + port : common.getPort(req), + proto: common.hasEncryptedConnection(req) ? 'wss' : 'ws' + }; + + ['for', 'port', 'proto'].forEach(function(header) { + req.headers['x-forwarded-' + header] = + (req.headers['x-forwarded-' + header] || '') + + (req.headers['x-forwarded-' + header] ? ',' : '') + + values[header]; + }); + }, + + /** + * Does the actual proxying. Make the request and upgrade it + * send the Switching Protocols request and pipe the sockets. + * + * @param {ClientRequest} Req Request object + * @param {Socket} Websocket + * @param {Object} Options Config object passed to the proxy + * + * @api private + */ + stream : function stream(req, socket, options, head, server, clb) { + + var createHttpHeader = function(line, headers) { + return Object.keys(headers).reduce(function (head, key) { + var value = headers[key]; + + if (!Array.isArray(value)) { + head.push(key + ': ' + value); + return head; + } + + for (var i = 0; i < value.length; i++) { + head.push(key + ': ' + value[i]); + } + return head; + }, [line]) + .join('\r\n') + '\r\n\r\n'; + }; + + common.setupSocket(socket); + + if (head && head.length) socket.unshift(head); + + + var proxyReq = (common.isSSL.test(options.target.protocol) ? https : http).request( + common.setupOutgoing(options.ssl || {}, options, req) + ); + + // Enable developers to modify the proxyReq before headers are sent + if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); } + + // Error Handler + proxyReq.on('error', onOutgoingError); + proxyReq.on('response', function (res) { + // if upgrade event isn't going to happen, close the socket + if (!res.upgrade) { + socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers)); + res.pipe(socket); + } + }); + + proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) { + proxySocket.on('error', onOutgoingError); + + // Allow us to listen when the websocket has completed + proxySocket.on('end', function () { + server.emit('close', proxyRes, proxySocket, proxyHead); + }); + + // The pipe below will end proxySocket if socket closes cleanly, but not + // if it errors (eg, vanishes from the net and starts returning + // EHOSTUNREACH). We need to do that explicitly. + socket.on('error', function () { + proxySocket.end(); + }); + + common.setupSocket(proxySocket); + + if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead); + + // + // Remark: Handle writing the headers to the socket when switching protocols + // Also handles when a header is an array + // + socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers)); + + proxySocket.pipe(socket).pipe(proxySocket); + + server.emit('open', proxySocket); + server.emit('proxySocket', proxySocket); //DEPRECATED. + }); + + return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT + + function onOutgoingError(err) { + if (clb) { + clb(err, req, socket); + } else { + server.emit('error', err, req, socket); + } + socket.end(); + } + } +}; + +(function (module) { + var httpProxy = module.exports, + extend = require$$0$6._extend, + parse_url = require$$0$9.parse, + EE3 = eventemitter3Exports, + http = require$$1$1, + https = require$$1$2, + web = webIncoming, + ws = wsIncoming; + + httpProxy.Server = ProxyServer; + + /** + * Returns a function that creates the loader for + * either `ws` or `web`'s passes. + * + * Examples: + * + * httpProxy.createRightProxy('ws') + * // => [Function] + * + * @param {String} Type Either 'ws' or 'web' + *  + * @return {Function} Loader Function that when called returns an iterator for the right passes + * + * @api private + */ + + function createRightProxy(type) { + + return function(options) { + return function(req, res /*, [head], [opts] */) { + var passes = (type === 'ws') ? this.wsPasses : this.webPasses, + args = [].slice.call(arguments), + cntr = args.length - 1, + head, cbl; + + /* optional args parse begin */ + if(typeof args[cntr] === 'function') { + cbl = args[cntr]; + + cntr--; + } + + var requestOptions = options; + if( + !(args[cntr] instanceof Buffer) && + args[cntr] !== res + ) { + //Copy global options + requestOptions = extend({}, options); + //Overwrite with request options + extend(requestOptions, args[cntr]); + + cntr--; + } + + if(args[cntr] instanceof Buffer) { + head = args[cntr]; + } + + /* optional args parse end */ + + ['target', 'forward'].forEach(function(e) { + if (typeof requestOptions[e] === 'string') + requestOptions[e] = parse_url(requestOptions[e]); + }); + + if (!requestOptions.target && !requestOptions.forward) { + return this.emit('error', new Error('Must provide a proper URL as target')); + } + + for(var i=0; i < passes.length; i++) { + /** + * Call of passes functions + * pass(req, res, options, head) + * + * In WebSockets case the `res` variable + * refer to the connection socket + * pass(req, socket, options, head) + */ + if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop + break; + } + } + }; + }; + } + httpProxy.createRightProxy = createRightProxy; + + function ProxyServer(options) { + EE3.call(this); + + options = options || {}; + options.prependPath = options.prependPath === false ? false : true; + + this.web = this.proxyRequest = createRightProxy('web')(options); + this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options); + this.options = options; + + this.webPasses = Object.keys(web).map(function(pass) { + return web[pass]; + }); + + this.wsPasses = Object.keys(ws).map(function(pass) { + return ws[pass]; + }); + + this.on('error', this.onError, this); + + } + + require$$0$6.inherits(ProxyServer, EE3); + + ProxyServer.prototype.onError = function (err) { + // + // Remark: Replicate node core behavior using EE3 + // so we force people to handle their own errors + // + if(this.listeners('error').length === 1) { + throw err; + } + }; + + ProxyServer.prototype.listen = function(port, hostname) { + var self = this, + closure = function(req, res) { self.web(req, res); }; + + this._server = this.options.ssl ? + https.createServer(this.options.ssl, closure) : + http.createServer(closure); + + if(this.options.ws) { + this._server.on('upgrade', function(req, socket, head) { self.ws(req, socket, head); }); + } + + this._server.listen(port, hostname); + + return this; + }; + + ProxyServer.prototype.close = function(callback) { + var self = this; + if (this._server) { + this._server.close(done); + } + + // Wrap callback to nullify server after all open connections are closed. + function done() { + self._server = null; + if (callback) { + callback.apply(null, arguments); + } + } }; + + ProxyServer.prototype.before = function(type, passName, callback) { + if (type !== 'ws' && type !== 'web') { + throw new Error('type must be `web` or `ws`'); + } + var passes = (type === 'ws') ? this.wsPasses : this.webPasses, + i = false; + + passes.forEach(function(v, idx) { + if(v.name === passName) i = idx; + }); + + if(i === false) throw new Error('No such pass'); + + passes.splice(i, 0, callback); + }; + ProxyServer.prototype.after = function(type, passName, callback) { + if (type !== 'ws' && type !== 'web') { + throw new Error('type must be `web` or `ws`'); + } + var passes = (type === 'ws') ? this.wsPasses : this.webPasses, + i = false; + + passes.forEach(function(v, idx) { + if(v.name === passName) i = idx; + }); + + if(i === false) throw new Error('No such pass'); + + passes.splice(i++, 0, callback); + }; +} (httpProxy$3)); + +var httpProxyExports = httpProxy$3.exports; + +// Use explicit /index.js to help browserify negociation in require '/lib/http-proxy' (!) +var ProxyServer = httpProxyExports.Server; + + +/** + * Creates the proxy server. + * + * Examples: + * + * httpProxy.createProxyServer({ .. }, 8000) + * // => '{ web: [Function], ws: [Function] ... }' + * + * @param {Object} Options Config object passed to the proxy + * + * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests + * + * @api public + */ + + +function createProxyServer(options) { + /* + * `options` is needed and it must have the following layout: + * + * { + * target : + * forward: + * agent : + * ssl : + * ws : + * xfwd : + * secure : + * toProxy: + * prependPath: + * ignorePath: + * localAddress : + * changeOrigin: + * preserveHeaderKeyCase: + * auth : Basic authentication i.e. 'user:password' to compute an Authorization header. + * hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null. + * autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false. + * protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null. + * } + * + * NOTE: `options.ws` and `options.ssl` are optional. + * `options.target and `options.forward` cannot be + * both missing + * } + */ + + return new ProxyServer(options); +} + + +ProxyServer.createProxyServer = createProxyServer; +ProxyServer.createServer = createProxyServer; +ProxyServer.createProxy = createProxyServer; + + + + +/** + * Export the proxy "Server" as the main export. + */ +var httpProxy$2 = ProxyServer; + +/*! + * Caron dimonio, con occhi di bragia + * loro accennando, tutte le raccoglie; + * batte col remo qualunque s’adagia + * + * Charon the demon, with the eyes of glede, + * Beckoning to them, collects them all together, + * Beats with his oar whoever lags behind + * + * Dante - The Divine Comedy (Canto III) + */ + +var httpProxy = httpProxy$2; + +var httpProxy$1 = /*@__PURE__*/getDefaultExportFromCjs(httpProxy); + +const debug$7 = createDebugger('vite:proxy'); +function proxyMiddleware(httpServer, options, config) { + // lazy require only when proxy is used + const proxies = {}; + Object.keys(options).forEach((context) => { + let opts = options[context]; + if (!opts) { + return; + } + if (typeof opts === 'string') { + opts = { target: opts, changeOrigin: true }; + } + const proxy = httpProxy$1.createProxyServer(opts); + if (opts.configure) { + opts.configure(proxy, opts); + } + proxy.on('error', (err, req, originalRes) => { + // When it is ws proxy, res is net.Socket + // originalRes can be falsy if the proxy itself errored + const res = originalRes; + if (!res) { + config.logger.error(`${colors$1.red(`http proxy error: ${err.message}`)}\n${err.stack}`, { + timestamp: true, + error: err, + }); + } + else if ('req' in res) { + config.logger.error(`${colors$1.red(`http proxy error at ${originalRes.req.url}:`)}\n${err.stack}`, { + timestamp: true, + error: err, + }); + if (!res.headersSent && !res.writableEnded) { + res + .writeHead(500, { + 'Content-Type': 'text/plain', + }) + .end(); + } + } + else { + config.logger.error(`${colors$1.red(`ws proxy error:`)}\n${err.stack}`, { + timestamp: true, + error: err, + }); + res.end(); + } + }); + proxy.on('proxyReqWs', (proxyReq, req, socket, options, head) => { + socket.on('error', (err) => { + config.logger.error(`${colors$1.red(`ws proxy socket error:`)}\n${err.stack}`, { + timestamp: true, + error: err, + }); + }); + }); + // https://github.com/http-party/node-http-proxy/issues/1520#issue-877626125 + // https://github.com/chimurai/http-proxy-middleware/blob/cd58f962aec22c925b7df5140502978da8f87d5f/src/plugins/default/debug-proxy-errors-plugin.ts#L25-L37 + proxy.on('proxyRes', (proxyRes, req, res) => { + res.on('close', () => { + if (!res.writableEnded) { + debug$7?.('destroying proxyRes in proxyRes close event'); + proxyRes.destroy(); + } + }); + }); + // clone before saving because http-proxy mutates the options + proxies[context] = [proxy, { ...opts }]; + }); + if (httpServer) { + httpServer.on('upgrade', (req, socket, head) => { + const url = req.url; + for (const context in proxies) { + if (doesProxyContextMatchUrl(context, url)) { + const [proxy, opts] = proxies[context]; + if (opts.ws || + opts.target?.toString().startsWith('ws:') || + opts.target?.toString().startsWith('wss:')) { + if (opts.rewrite) { + req.url = opts.rewrite(url); + } + debug$7?.(`${req.url} -> ws ${opts.target}`); + proxy.ws(req, socket, head); + return; + } + } + } + }); + } + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteProxyMiddleware(req, res, next) { + const url = req.url; + for (const context in proxies) { + if (doesProxyContextMatchUrl(context, url)) { + const [proxy, opts] = proxies[context]; + const options = {}; + if (opts.bypass) { + const bypassResult = opts.bypass(req, res, opts); + if (typeof bypassResult === 'string') { + req.url = bypassResult; + debug$7?.(`bypass: ${req.url} -> ${bypassResult}`); + return next(); + } + else if (bypassResult === false) { + debug$7?.(`bypass: ${req.url} -> 404`); + res.statusCode = 404; + return res.end(); + } + } + debug$7?.(`${req.url} -> ${opts.target || opts.forward}`); + if (opts.rewrite) { + req.url = opts.rewrite(req.url); + } + proxy.web(req, res, options); + return; + } + } + next(); + }; +} +function doesProxyContextMatchUrl(context, url) { + return ((context[0] === '^' && new RegExp(context).test(url)) || + url.startsWith(context)); +} + +const debug$6 = createDebugger('vite:html-fallback'); +function htmlFallbackMiddleware(root, spaFallback, fsUtils = commonFsUtils) { + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteHtmlFallbackMiddleware(req, res, next) { + if ( + // Only accept GET or HEAD + (req.method !== 'GET' && req.method !== 'HEAD') || + // Exclude default favicon requests + req.url === '/favicon.ico' || + // Require Accept: text/html or */* + !(req.headers.accept === undefined || // equivalent to `Accept: */*` + req.headers.accept === '' || // equivalent to `Accept: */*` + req.headers.accept.includes('text/html') || + req.headers.accept.includes('*/*'))) { + return next(); + } + const url = cleanUrl(req.url); + const pathname = decodeURIComponent(url); + // .html files are not handled by serveStaticMiddleware + // so we need to check if the file exists + if (pathname.endsWith('.html')) { + const filePath = path$o.join(root, pathname); + if (fsUtils.existsSync(filePath)) { + debug$6?.(`Rewriting ${req.method} ${req.url} to ${url}`); + req.url = url; + return next(); + } + } + // trailing slash should check for fallback index.html + else if (pathname[pathname.length - 1] === '/') { + const filePath = path$o.join(root, pathname, 'index.html'); + if (fsUtils.existsSync(filePath)) { + const newUrl = url + 'index.html'; + debug$6?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`); + req.url = newUrl; + return next(); + } + } + // non-trailing slash should check for fallback .html + else { + const filePath = path$o.join(root, pathname + '.html'); + if (fsUtils.existsSync(filePath)) { + const newUrl = url + '.html'; + debug$6?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`); + req.url = newUrl; + return next(); + } + } + if (spaFallback) { + debug$6?.(`Rewriting ${req.method} ${req.url} to /index.html`); + req.url = '/index.html'; + } + next(); + }; +} + +const debug$5 = createDebugger('vite:send', { + onlyWhenFocused: true, +}); +const alias = { + js: 'application/javascript', + css: 'text/css', + html: 'text/html', + json: 'application/json', +}; +function send(req, res, content, type, options) { + const { etag = getEtag(content, { weak: true }), cacheControl = 'no-cache', headers, map, } = options; + if (res.writableEnded) { + return; + } + if (req.headers['if-none-match'] === etag) { + res.statusCode = 304; + res.end(); + return; + } + res.setHeader('Content-Type', alias[type] || type); + res.setHeader('Cache-Control', cacheControl); + res.setHeader('Etag', etag); + if (headers) { + for (const name in headers) { + res.setHeader(name, headers[name]); + } + } + // inject source map reference + if (map && 'version' in map && map.mappings) { + if (type === 'js' || type === 'css') { + content = getCodeWithSourcemap(type, content.toString(), map); + } + } + // inject fallback sourcemap for js for improved debugging + // https://github.com/vitejs/vite/pull/13514#issuecomment-1592431496 + else if (type === 'js' && (!map || map.mappings !== '')) { + const code = content.toString(); + // if the code has existing inline sourcemap, assume it's correct and skip + if (convertSourceMap.mapFileCommentRegex.test(code)) { + debug$5?.(`Skipped injecting fallback sourcemap for ${req.url}`); + } + else { + const urlWithoutTimestamp = removeTimestampQuery(req.url); + const ms = new MagicString(code); + content = getCodeWithSourcemap(type, code, ms.generateMap({ + source: path$o.basename(urlWithoutTimestamp), + hires: 'boundary', + includeContent: true, + })); + } + } + res.statusCode = 200; + res.end(content); + return; +} + +const debugCache = createDebugger('vite:cache'); +const knownIgnoreList = new Set(['/', '/favicon.ico']); +function transformMiddleware(server) { + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + // check if public dir is inside root dir + const { root } = server.config; + const publicDir = normalizePath$3(server.config.publicDir); + const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root)); + const publicPath = `${publicDir.slice(root.length)}/`; + return async function viteTransformMiddleware(req, res, next) { + if (req.method !== 'GET' || knownIgnoreList.has(req.url)) { + return next(); + } + let url; + try { + url = decodeURI(removeTimestampQuery(req.url)).replace(NULL_BYTE_PLACEHOLDER, '\0'); + } + catch (e) { + return next(e); + } + const withoutQuery = cleanUrl(url); + try { + const isSourceMap = withoutQuery.endsWith('.map'); + // since we generate source map references, handle those requests here + if (isSourceMap) { + const depsOptimizer = getDepsOptimizer(server.config, false); // non-ssr + if (depsOptimizer?.isOptimizedDepUrl(url)) { + // If the browser is requesting a source map for an optimized dep, it + // means that the dependency has already been pre-bundled and loaded + const sourcemapPath = url.startsWith(FS_PREFIX) + ? fsPathFromId(url) + : normalizePath$3(path$o.resolve(server.config.root, url.slice(1))); + try { + const map = JSON.parse(await fsp.readFile(sourcemapPath, 'utf-8')); + applySourcemapIgnoreList(map, sourcemapPath, server.config.server.sourcemapIgnoreList, server.config.logger); + return send(req, res, JSON.stringify(map), 'json', { + headers: server.config.server.headers, + }); + } + catch (e) { + // Outdated source map request for optimized deps, this isn't an error + // but part of the normal flow when re-optimizing after missing deps + // Send back an empty source map so the browser doesn't issue warnings + const dummySourceMap = { + version: 3, + file: sourcemapPath.replace(/\.map$/, ''), + sources: [], + sourcesContent: [], + names: [], + mappings: ';;;;;;;;;', + }; + return send(req, res, JSON.stringify(dummySourceMap), 'json', { + cacheControl: 'no-cache', + headers: server.config.server.headers, + }); + } + } + else { + const originalUrl = url.replace(/\.map($|\?)/, '$1'); + const map = (await server.moduleGraph.getModuleByUrl(originalUrl, false))?.transformResult?.map; + if (map) { + return send(req, res, JSON.stringify(map), 'json', { + headers: server.config.server.headers, + }); + } + else { + return next(); + } + } + } + if (publicDirInRoot && url.startsWith(publicPath)) { + warnAboutExplicitPublicPathInUrl(url); + } + if (isJSRequest(url) || + isImportRequest(url) || + isCSSRequest(url) || + isHTMLProxy(url)) { + // strip ?import + url = removeImportQuery(url); + // Strip valid id prefix. This is prepended to resolved Ids that are + // not valid browser import specifiers by the importAnalysis plugin. + url = unwrapId(url); + // for CSS, we need to differentiate between normal CSS requests and + // imports + if (isCSSRequest(url) && + !isDirectRequest(url) && + req.headers.accept?.includes('text/css')) { + url = injectQuery(url, 'direct'); + } + // check if we can return 304 early + const ifNoneMatch = req.headers['if-none-match']; + if (ifNoneMatch && + (await server.moduleGraph.getModuleByUrl(url, false))?.transformResult + ?.etag === ifNoneMatch) { + debugCache?.(`[304] ${prettifyUrl(url, server.config.root)}`); + res.statusCode = 304; + return res.end(); + } + // resolve, load and transform using the plugin container + const result = await transformRequest(url, server, { + html: req.headers.accept?.includes('text/html'), + }); + if (result) { + const depsOptimizer = getDepsOptimizer(server.config, false); // non-ssr + const type = isDirectCSSRequest(url) ? 'css' : 'js'; + const isDep = DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url); + return send(req, res, result.code, type, { + etag: result.etag, + // allow browser to cache npm deps! + cacheControl: isDep ? 'max-age=31536000,immutable' : 'no-cache', + headers: server.config.server.headers, + map: result.map, + }); + } + } + } + catch (e) { + if (e?.code === ERR_OPTIMIZE_DEPS_PROCESSING_ERROR) { + // Skip if response has already been sent + if (!res.writableEnded) { + res.statusCode = 504; // status code request timeout + res.statusMessage = 'Optimize Deps Processing Error'; + res.end(); + } + // This timeout is unexpected + server.config.logger.error(e.message); + return; + } + if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP) { + // Skip if response has already been sent + if (!res.writableEnded) { + res.statusCode = 504; // status code request timeout + res.statusMessage = 'Outdated Optimize Dep'; + res.end(); + } + // We don't need to log an error in this case, the request + // is outdated because new dependencies were discovered and + // the new pre-bundle dependencies have changed. + // A full-page reload has been issued, and these old requests + // can't be properly fulfilled. This isn't an unexpected + // error but a normal part of the missing deps discovery flow + return; + } + if (e?.code === ERR_CLOSED_SERVER) { + // Skip if response has already been sent + if (!res.writableEnded) { + res.statusCode = 504; // status code request timeout + res.statusMessage = 'Outdated Request'; + res.end(); + } + // We don't need to log an error in this case, the request + // is outdated because new dependencies were discovered and + // the new pre-bundle dependencies have changed. + // A full-page reload has been issued, and these old requests + // can't be properly fulfilled. This isn't an unexpected + // error but a normal part of the missing deps discovery flow + return; + } + if (e?.code === ERR_LOAD_URL) { + // Let other middleware handle if we can't load the url via transformRequest + return next(); + } + return next(e); + } + next(); + }; + function warnAboutExplicitPublicPathInUrl(url) { + let warning; + if (isImportRequest(url)) { + const rawUrl = removeImportQuery(url); + if (urlRE.test(url)) { + warning = + `Assets in the public directory are served at the root path.\n` + + `Instead of ${colors$1.cyan(rawUrl)}, use ${colors$1.cyan(rawUrl.replace(publicPath, '/'))}.`; + } + else { + warning = + 'Assets in public directory cannot be imported from JavaScript.\n' + + `If you intend to import that asset, put the file in the src directory, and use ${colors$1.cyan(rawUrl.replace(publicPath, '/src/'))} instead of ${colors$1.cyan(rawUrl)}.\n` + + `If you intend to use the URL of that asset, use ${colors$1.cyan(injectQuery(rawUrl.replace(publicPath, '/'), 'url'))}.`; + } + } + else { + warning = + `Files in the public directory are served at the root path.\n` + + `Instead of ${colors$1.cyan(url)}, use ${colors$1.cyan(url.replace(publicPath, '/'))}.`; + } + server.config.logger.warn(colors$1.yellow(warning)); + } +} + +function createDevHtmlTransformFn(config) { + const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms(config.plugins, config.logger); + return (server, url, html, originalUrl) => { + return applyHtmlTransforms(html, [ + preImportMapHook(config), + ...preHooks, + htmlEnvHook(config), + devHtmlHook, + ...normalHooks, + ...postHooks, + postImportMapHook(), + ], { + path: url, + filename: getHtmlFilename(url, server), + server, + originalUrl, + }); + }; +} +function getHtmlFilename(url, server) { + if (url.startsWith(FS_PREFIX)) { + return decodeURIComponent(fsPathFromId(url)); + } + else { + return decodeURIComponent(normalizePath$3(path$o.join(server.config.root, url.slice(1)))); + } +} +function shouldPreTransform(url, config) { + return (!checkPublicFile(url, config) && (isJSRequest(url) || isCSSRequest(url))); +} +const wordCharRE = /\w/; +function isBareRelative(url) { + return wordCharRE.test(url[0]) && !url.includes(':'); +} +const isSrcSet = (attr) => attr.name === 'srcset' && attr.prefix === undefined; +const processNodeUrl = (url, useSrcSetReplacer, config, htmlPath, originalUrl, server, isClassicScriptLink) => { + // prefix with base (dev only, base is never relative) + const replacer = (url) => { + if (server?.moduleGraph) { + const mod = server.moduleGraph.urlToModuleMap.get(url); + if (mod && mod.lastHMRTimestamp > 0) { + url = injectQuery(url, `t=${mod.lastHMRTimestamp}`); + } + } + if ((url[0] === '/' && url[1] !== '/') || + // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets + // path will add `/a/` prefix, it will caused 404. + // + // skip if url contains `:` as it implies a url protocol or Windows path that we don't want to replace. + // + // rewrite `./index.js` -> `localhost:5173/a/index.js`. + // rewrite `../index.js` -> `localhost:5173/index.js`. + // rewrite `relative/index.js` -> `localhost:5173/a/relative/index.js`. + ((url[0] === '.' || isBareRelative(url)) && + originalUrl && + originalUrl !== '/' && + htmlPath === '/index.html')) { + url = path$o.posix.join(config.base, url); + } + if (server && !isClassicScriptLink && shouldPreTransform(url, config)) { + let preTransformUrl; + if (url[0] === '/' && url[1] !== '/') { + preTransformUrl = url; + } + else if (url[0] === '.' || isBareRelative(url)) { + preTransformUrl = path$o.posix.join(config.base, path$o.posix.dirname(htmlPath), url); + } + if (preTransformUrl) { + preTransformRequest(server, preTransformUrl, config.base); + } + } + return url; + }; + const processedUrl = useSrcSetReplacer + ? processSrcSetSync(url, ({ url }) => replacer(url)) + : replacer(url); + return processedUrl; +}; +const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl }) => { + const { config, moduleGraph, watcher } = server; + const base = config.base || '/'; + let proxyModulePath; + let proxyModuleUrl; + const trailingSlash = htmlPath.endsWith('/'); + if (!trailingSlash && getFsUtils(config).existsSync(filename)) { + proxyModulePath = htmlPath; + proxyModuleUrl = joinUrlSegments(base, htmlPath); + } + else { + // There are users of vite.transformIndexHtml calling it with url '/' + // for SSR integrations #7993, filename is root for this case + // A user may also use a valid name for a virtual html file + // Mark the path as virtual in both cases so sourcemaps aren't processed + // and ids are properly handled + const validPath = `${htmlPath}${trailingSlash ? 'index.html' : ''}`; + proxyModulePath = `\0${validPath}`; + proxyModuleUrl = wrapId(proxyModulePath); + } + const s = new MagicString(html); + let inlineModuleIndex = -1; + // The key to the proxyHtml cache is decoded, as it will be compared + // against decoded URLs by the HTML plugins. + const proxyCacheUrl = decodeURI(cleanUrl(proxyModulePath).replace(normalizePath$3(config.root), '')); + const styleUrl = []; + const inlineStyles = []; + const addInlineModule = (node, ext) => { + inlineModuleIndex++; + const contentNode = node.childNodes[0]; + const code = contentNode.value; + let map; + if (proxyModulePath[0] !== '\0') { + map = new MagicString(html) + .snip(contentNode.sourceCodeLocation.startOffset, contentNode.sourceCodeLocation.endOffset) + .generateMap({ hires: 'boundary' }); + map.sources = [filename]; + map.file = filename; + } + // add HTML Proxy to Map + addToHTMLProxyCache(config, proxyCacheUrl, inlineModuleIndex, { code, map }); + // inline js module. convert to src="proxy" (dev only, base is never relative) + const modulePath = `${proxyModuleUrl}?html-proxy&index=${inlineModuleIndex}.${ext}`; + // invalidate the module so the newly cached contents will be served + const module = server?.moduleGraph.getModuleById(modulePath); + if (module) { + server?.moduleGraph.invalidateModule(module); + } + s.update(node.sourceCodeLocation.startOffset, node.sourceCodeLocation.endOffset, ``); + preTransformRequest(server, modulePath, base); + }; + await traverseHtml(html, filename, (node) => { + if (!nodeIsElement(node)) { + return; + } + // script tags + if (node.nodeName === 'script') { + const { src, sourceCodeLocation, isModule } = getScriptInfo(node); + if (src) { + const processedUrl = processNodeUrl(src.value, isSrcSet(src), config, htmlPath, originalUrl, server, !isModule); + if (processedUrl !== src.value) { + overwriteAttrValue(s, sourceCodeLocation, processedUrl); + } + } + else if (isModule && node.childNodes.length) { + addInlineModule(node, 'js'); + } + else if (node.childNodes.length) { + const scriptNode = node.childNodes[node.childNodes.length - 1]; + for (const { url, start, end, } of extractImportExpressionFromClassicScript(scriptNode)) { + const processedUrl = processNodeUrl(url, false, config, htmlPath, originalUrl); + if (processedUrl !== url) { + s.update(start, end, processedUrl); + } + } + } + } + const inlineStyle = findNeedTransformStyleAttribute(node); + if (inlineStyle) { + inlineModuleIndex++; + inlineStyles.push({ + index: inlineModuleIndex, + location: inlineStyle.location, + code: inlineStyle.attr.value, + }); + } + if (node.nodeName === 'style' && node.childNodes.length) { + const children = node.childNodes[0]; + styleUrl.push({ + start: children.sourceCodeLocation.startOffset, + end: children.sourceCodeLocation.endOffset, + code: children.value, + }); + } + // elements with [href/src] attrs + const assetAttrs = assetAttrsConfig[node.nodeName]; + if (assetAttrs) { + for (const p of node.attrs) { + const attrKey = getAttrKey(p); + if (p.value && assetAttrs.includes(attrKey)) { + const processedUrl = processNodeUrl(p.value, isSrcSet(p), config, htmlPath, originalUrl); + if (processedUrl !== p.value) { + overwriteAttrValue(s, node.sourceCodeLocation.attrs[attrKey], processedUrl); + } + } + } + } + }); + await Promise.all([ + ...styleUrl.map(async ({ start, end, code }, index) => { + const url = `${proxyModulePath}?html-proxy&direct&index=${index}.css`; + // ensure module in graph after successful load + const mod = await moduleGraph.ensureEntryFromUrl(url, false); + ensureWatchedFile(watcher, mod.file, config.root); + const result = await server.pluginContainer.transform(code, mod.id); + let content = ''; + if (result) { + if (result.map && 'version' in result.map) { + if (result.map.mappings) { + await injectSourcesContent(result.map, proxyModulePath, config.logger); + } + content = getCodeWithSourcemap('css', result.code, result.map); + } + else { + content = result.code; + } + } + s.overwrite(start, end, content); + }), + ...inlineStyles.map(async ({ index, location, code }) => { + // will transform with css plugin and cache result with css-post plugin + const url = `${proxyModulePath}?html-proxy&inline-css&style-attr&index=${index}.css`; + const mod = await moduleGraph.ensureEntryFromUrl(url, false); + ensureWatchedFile(watcher, mod.file, config.root); + await server?.pluginContainer.transform(code, mod.id); + const hash = getHash(cleanUrl(mod.id)); + const result = htmlProxyResult.get(`${hash}_${index}`); + overwriteAttrValue(s, location, result ?? ''); + }), + ]); + html = s.toString(); + return { + html, + tags: [ + { + tag: 'script', + attrs: { + type: 'module', + src: path$o.posix.join(base, CLIENT_PUBLIC_PATH), + }, + injectTo: 'head-prepend', + }, + ], + }; +}; +function indexHtmlMiddleware(root, server) { + const isDev = isDevServer(server); + const fsUtils = getFsUtils(server.config); + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return async function viteIndexHtmlMiddleware(req, res, next) { + if (res.writableEnded) { + return next(); + } + const url = req.url && cleanUrl(req.url); + // htmlFallbackMiddleware appends '.html' to URLs + if (url?.endsWith('.html') && req.headers['sec-fetch-dest'] !== 'script') { + let filePath; + if (isDev && url.startsWith(FS_PREFIX)) { + filePath = decodeURIComponent(fsPathFromId(url)); + } + else { + filePath = path$o.join(root, decodeURIComponent(url)); + } + if (fsUtils.existsSync(filePath)) { + const headers = isDev + ? server.config.server.headers + : server.config.preview.headers; + try { + let html = await fsp.readFile(filePath, 'utf-8'); + if (isDev) { + html = await server.transformIndexHtml(url, html, req.originalUrl); + } + return send(req, res, html, 'html', { headers }); + } + catch (e) { + return next(e); + } + } + } + next(); + }; +} +function preTransformRequest(server, url, base) { + if (!server.config.server.preTransformRequests) + return; + // transform all url as non-ssr as html includes client-side assets only + try { + url = unwrapId(stripBase(decodeURI(url), base)); + } + catch { + // ignore + return; + } + server.warmupRequest(url); +} + +const logTime = createDebugger('vite:time'); +function timeMiddleware(root) { + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteTimeMiddleware(req, res, next) { + const start = performance.now(); + const end = res.end; + res.end = (...args) => { + logTime?.(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`); + return end.call(res, ...args); + }; + next(); + }; +} + +class ModuleNode { + /** + * Public served url path, starts with / + */ + url; + /** + * Resolved file system path + query + */ + id = null; + file = null; + type; + info; + meta; + importers = new Set(); + clientImportedModules = new Set(); + ssrImportedModules = new Set(); + acceptedHmrDeps = new Set(); + acceptedHmrExports = null; + importedBindings = null; + isSelfAccepting; + transformResult = null; + ssrTransformResult = null; + ssrModule = null; + ssrError = null; + lastHMRTimestamp = 0; + lastInvalidationTimestamp = 0; + /** + * If the module only needs to update its imports timestamp (e.g. within an HMR chain), + * it is considered soft-invalidated. In this state, its `transformResult` should exist, + * and the next `transformRequest` for this module will replace the timestamps. + * + * By default the value is `undefined` if it's not soft/hard-invalidated. If it gets + * soft-invalidated, this will contain the previous `transformResult` value. If it gets + * hard-invalidated, this will be set to `'HARD_INVALIDATED'`. + * @internal + */ + invalidationState; + /** + * @internal + */ + ssrInvalidationState; + /** + * The module urls that are statically imported in the code. This information is separated + * out from `importedModules` as only importers that statically import the module can be + * soft invalidated. Other imports (e.g. watched files) needs the importer to be hard invalidated. + * @internal + */ + staticImportedUrls; + /** + * @param setIsSelfAccepting - set `false` to set `isSelfAccepting` later. e.g. #7870 + */ + constructor(url, setIsSelfAccepting = true) { + this.url = url; + this.type = isDirectCSSRequest(url) ? 'css' : 'js'; + if (setIsSelfAccepting) { + this.isSelfAccepting = false; + } + } + get importedModules() { + const importedModules = new Set(this.clientImportedModules); + for (const module of this.ssrImportedModules) { + importedModules.add(module); + } + return importedModules; + } +} +class ModuleGraph { + resolveId; + urlToModuleMap = new Map(); + idToModuleMap = new Map(); + // a single file may corresponds to multiple modules with different queries + fileToModulesMap = new Map(); + safeModulesPath = new Set(); + /** + * @internal + */ + _unresolvedUrlToModuleMap = new Map(); + /** + * @internal + */ + _ssrUnresolvedUrlToModuleMap = new Map(); + constructor(resolveId) { + this.resolveId = resolveId; + } + async getModuleByUrl(rawUrl, ssr) { + // Quick path, if we already have a module for this rawUrl (even without extension) + rawUrl = removeImportQuery(removeTimestampQuery(rawUrl)); + const mod = this._getUnresolvedUrlToModule(rawUrl, ssr); + if (mod) { + return mod; + } + const [url] = await this._resolveUrl(rawUrl, ssr); + return this.urlToModuleMap.get(url); + } + getModuleById(id) { + return this.idToModuleMap.get(removeTimestampQuery(id)); + } + getModulesByFile(file) { + return this.fileToModulesMap.get(file); + } + onFileChange(file) { + const mods = this.getModulesByFile(file); + if (mods) { + const seen = new Set(); + mods.forEach((mod) => { + this.invalidateModule(mod, seen); + }); + } + } + invalidateModule(mod, seen = new Set(), timestamp = Date.now(), isHmr = false, + /** @internal */ + softInvalidate = false) { + const prevInvalidationState = mod.invalidationState; + const prevSsrInvalidationState = mod.ssrInvalidationState; + // Handle soft invalidation before the `seen` check, as consecutive soft/hard invalidations can + // cause the final soft invalidation state to be different. + // If soft invalidated, save the previous `transformResult` so that we can reuse and transform the + // import timestamps only in `transformRequest`. If there's no previous `transformResult`, hard invalidate it. + if (softInvalidate) { + mod.invalidationState ??= mod.transformResult ?? 'HARD_INVALIDATED'; + mod.ssrInvalidationState ??= mod.ssrTransformResult ?? 'HARD_INVALIDATED'; + } + // If hard invalidated, further soft invalidations have no effect until it's reset to `undefined` + else { + mod.invalidationState = 'HARD_INVALIDATED'; + mod.ssrInvalidationState = 'HARD_INVALIDATED'; + } + // Skip updating the module if it was already invalidated before and the invalidation state has not changed + if (seen.has(mod) && + prevInvalidationState === mod.invalidationState && + prevSsrInvalidationState === mod.ssrInvalidationState) { + return; + } + seen.add(mod); + if (isHmr) { + mod.lastHMRTimestamp = timestamp; + } + else { + // Save the timestamp for this invalidation, so we can avoid caching the result of possible already started + // processing being done for this module + mod.lastInvalidationTimestamp = timestamp; + } + // Don't invalidate mod.info and mod.meta, as they are part of the processing pipeline + // Invalidating the transform result is enough to ensure this module is re-processed next time it is requested + mod.transformResult = null; + mod.ssrTransformResult = null; + mod.ssrModule = null; + mod.ssrError = null; + mod.importers.forEach((importer) => { + if (!importer.acceptedHmrDeps.has(mod)) { + // If the importer statically imports the current module, we can soft-invalidate the importer + // to only update the import timestamps. If it's not statically imported, e.g. watched/glob file, + // we can only soft invalidate if the current module was also soft-invalidated. A soft-invalidation + // doesn't need to trigger a re-load and re-transform of the importer. + const shouldSoftInvalidateImporter = importer.staticImportedUrls?.has(mod.url) || softInvalidate; + this.invalidateModule(importer, seen, timestamp, isHmr, shouldSoftInvalidateImporter); + } + }); + } + invalidateAll() { + const timestamp = Date.now(); + const seen = new Set(); + this.idToModuleMap.forEach((mod) => { + this.invalidateModule(mod, seen, timestamp); + }); + } + /** + * Update the module graph based on a module's updated imports information + * If there are dependencies that no longer have any importers, they are + * returned as a Set. + * + * @param staticImportedUrls Subset of `importedModules` where they're statically imported in code. + * This is only used for soft invalidations so `undefined` is fine but may cause more runtime processing. + */ + async updateModuleInfo(mod, importedModules, importedBindings, acceptedModules, acceptedExports, isSelfAccepting, ssr, + /** @internal */ + staticImportedUrls) { + mod.isSelfAccepting = isSelfAccepting; + const prevImports = ssr ? mod.ssrImportedModules : mod.clientImportedModules; + let noLongerImported; + let resolvePromises = []; + let resolveResults = new Array(importedModules.size); + let index = 0; + // update import graph + for (const imported of importedModules) { + const nextIndex = index++; + if (typeof imported === 'string') { + resolvePromises.push(this.ensureEntryFromUrl(imported, ssr).then((dep) => { + dep.importers.add(mod); + resolveResults[nextIndex] = dep; + })); + } + else { + imported.importers.add(mod); + resolveResults[nextIndex] = imported; + } + } + if (resolvePromises.length) { + await Promise.all(resolvePromises); + } + const nextImports = new Set(resolveResults); + if (ssr) { + mod.ssrImportedModules = nextImports; + } + else { + mod.clientImportedModules = nextImports; + } + // remove the importer from deps that were imported but no longer are. + prevImports.forEach((dep) => { + if (!mod.clientImportedModules.has(dep) && + !mod.ssrImportedModules.has(dep)) { + dep.importers.delete(mod); + if (!dep.importers.size) { + (noLongerImported || (noLongerImported = new Set())).add(dep); + } + } + }); + // update accepted hmr deps + resolvePromises = []; + resolveResults = new Array(acceptedModules.size); + index = 0; + for (const accepted of acceptedModules) { + const nextIndex = index++; + if (typeof accepted === 'string') { + resolvePromises.push(this.ensureEntryFromUrl(accepted, ssr).then((dep) => { + resolveResults[nextIndex] = dep; + })); + } + else { + resolveResults[nextIndex] = accepted; + } + } + if (resolvePromises.length) { + await Promise.all(resolvePromises); + } + mod.acceptedHmrDeps = new Set(resolveResults); + mod.staticImportedUrls = staticImportedUrls; + // update accepted hmr exports + mod.acceptedHmrExports = acceptedExports; + mod.importedBindings = importedBindings; + return noLongerImported; + } + async ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true) { + return this._ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting); + } + /** + * @internal + */ + async _ensureEntryFromUrl(rawUrl, ssr, setIsSelfAccepting = true, + // Optimization, avoid resolving the same url twice if the caller already did it + resolved) { + // Quick path, if we already have a module for this rawUrl (even without extension) + rawUrl = removeImportQuery(removeTimestampQuery(rawUrl)); + let mod = this._getUnresolvedUrlToModule(rawUrl, ssr); + if (mod) { + return mod; + } + const modPromise = (async () => { + const [url, resolvedId, meta] = await this._resolveUrl(rawUrl, ssr, resolved); + mod = this.idToModuleMap.get(resolvedId); + if (!mod) { + mod = new ModuleNode(url, setIsSelfAccepting); + if (meta) + mod.meta = meta; + this.urlToModuleMap.set(url, mod); + mod.id = resolvedId; + this.idToModuleMap.set(resolvedId, mod); + const file = (mod.file = cleanUrl(resolvedId)); + let fileMappedModules = this.fileToModulesMap.get(file); + if (!fileMappedModules) { + fileMappedModules = new Set(); + this.fileToModulesMap.set(file, fileMappedModules); + } + fileMappedModules.add(mod); + } + // multiple urls can map to the same module and id, make sure we register + // the url to the existing module in that case + else if (!this.urlToModuleMap.has(url)) { + this.urlToModuleMap.set(url, mod); + } + this._setUnresolvedUrlToModule(rawUrl, mod, ssr); + return mod; + })(); + // Also register the clean url to the module, so that we can short-circuit + // resolving the same url twice + this._setUnresolvedUrlToModule(rawUrl, modPromise, ssr); + return modPromise; + } + // some deps, like a css file referenced via @import, don't have its own + // url because they are inlined into the main css import. But they still + // need to be represented in the module graph so that they can trigger + // hmr in the importing css file. + createFileOnlyEntry(file) { + file = normalizePath$3(file); + let fileMappedModules = this.fileToModulesMap.get(file); + if (!fileMappedModules) { + fileMappedModules = new Set(); + this.fileToModulesMap.set(file, fileMappedModules); + } + const url = `${FS_PREFIX}${file}`; + for (const m of fileMappedModules) { + if (m.url === url || m.id === file) { + return m; + } + } + const mod = new ModuleNode(url); + mod.file = file; + fileMappedModules.add(mod); + return mod; + } + // for incoming urls, it is important to: + // 1. remove the HMR timestamp query (?t=xxxx) and the ?import query + // 2. resolve its extension so that urls with or without extension all map to + // the same module + async resolveUrl(url, ssr) { + url = removeImportQuery(removeTimestampQuery(url)); + const mod = await this._getUnresolvedUrlToModule(url, ssr); + if (mod?.id) { + return [mod.url, mod.id, mod.meta]; + } + return this._resolveUrl(url, ssr); + } + /** + * @internal + */ + _getUnresolvedUrlToModule(url, ssr) { + return (ssr ? this._ssrUnresolvedUrlToModuleMap : this._unresolvedUrlToModuleMap).get(url); + } + /** + * @internal + */ + _setUnresolvedUrlToModule(url, mod, ssr) { + (ssr + ? this._ssrUnresolvedUrlToModuleMap + : this._unresolvedUrlToModuleMap).set(url, mod); + } + /** + * @internal + */ + async _resolveUrl(url, ssr, alreadyResolved) { + const resolved = alreadyResolved ?? (await this.resolveId(url, !!ssr)); + const resolvedId = resolved?.id || url; + if (url !== resolvedId && + !url.includes('\0') && + !url.startsWith(`virtual:`)) { + const ext = extname$1(cleanUrl(resolvedId)); + if (ext) { + const pathname = cleanUrl(url); + if (!pathname.endsWith(ext)) { + url = pathname + ext + url.slice(pathname.length); + } + } + } + return [url, resolvedId, resolved?.meta]; + } +} + +function notFoundMiddleware() { + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function vite404Middleware(_, res) { + res.statusCode = 404; + res.end(); + }; +} + +function ansiRegex({onlyFirst = false} = {}) { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +} + +const regex = ansiRegex(); + +function stripAnsi(string) { + if (typeof string !== 'string') { + throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``); + } + + // Even though the regex is global, we don't need to reset the `.lastIndex` + // because unlike `.exec()` and `.test()`, `.replace()` does it automatically + // and doing it manually has a performance penalty. + return string.replace(regex, ''); +} + +function prepareError(err) { + // only copy the information we need and avoid serializing unnecessary + // properties, since some errors may attach full objects (e.g. PostCSS) + return { + message: stripAnsi(err.message), + stack: stripAnsi(cleanStack(err.stack || '')), + id: err.id, + frame: stripAnsi(err.frame || ''), + plugin: err.plugin, + pluginCode: err.pluginCode?.toString(), + loc: err.loc, + }; +} +function buildErrorMessage(err, args = [], includeStack = true) { + if (err.plugin) + args.push(` Plugin: ${colors$1.magenta(err.plugin)}`); + const loc = err.loc ? `:${err.loc.line}:${err.loc.column}` : ''; + if (err.id) + args.push(` File: ${colors$1.cyan(err.id)}${loc}`); + if (err.frame) + args.push(colors$1.yellow(pad$1(err.frame))); + if (includeStack && err.stack) + args.push(pad$1(cleanStack(err.stack))); + return args.join('\n'); +} +function cleanStack(stack) { + return stack + .split(/\n/g) + .filter((l) => /^\s*at/.test(l)) + .join('\n'); +} +function logError(server, err) { + const msg = buildErrorMessage(err, [ + colors$1.red(`Internal server error: ${err.message}`), + ]); + server.config.logger.error(msg, { + clear: true, + timestamp: true, + error: err, + }); + server.ws.send({ + type: 'error', + err: prepareError(err), + }); +} +function errorMiddleware(server, allowNext = false) { + // note the 4 args must be kept for connect to treat this as error middleware + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + return function viteErrorMiddleware(err, _req, res, next) { + logError(server, err); + if (allowNext) { + next(); + } + else { + res.statusCode = 500; + res.end(` + + + + + Error + + + + + + `); + } + }; +} + +// https://github.com/vitejs/vite/issues/2820#issuecomment-812495079 +const ROOT_FILES = [ + // '.git', + // https://pnpm.io/workspaces/ + 'pnpm-workspace.yaml', + // https://rushjs.io/pages/advanced/config_files/ + // 'rush.json', + // https://nx.dev/latest/react/getting-started/nx-setup + // 'workspace.json', + // 'nx.json', + // https://github.com/lerna/lerna#lernajson + 'lerna.json', +]; +// npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces +// yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it +function hasWorkspacePackageJSON(root) { + const path = join$2(root, 'package.json'); + if (!isFileReadable(path)) { + return false; + } + try { + const content = JSON.parse(fs$l.readFileSync(path, 'utf-8')) || {}; + return !!content.workspaces; + } + catch { + return false; + } +} +function hasRootFile(root) { + return ROOT_FILES.some((file) => fs$l.existsSync(join$2(root, file))); +} +function hasPackageJSON(root) { + const path = join$2(root, 'package.json'); + return fs$l.existsSync(path); +} +/** + * Search up for the nearest `package.json` + */ +function searchForPackageRoot(current, root = current) { + if (hasPackageJSON(current)) + return current; + const dir = dirname$2(current); + // reach the fs root + if (!dir || dir === current) + return root; + return searchForPackageRoot(dir, root); +} +/** + * Search up for the nearest workspace root + */ +function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) { + if (hasRootFile(current)) + return current; + if (hasWorkspacePackageJSON(current)) + return current; + const dir = dirname$2(current); + // reach the fs root + if (!dir || dir === current) + return root; + return searchForWorkspaceRoot(dir, root); +} + +function warmupFiles(server) { + const options = server.config.server.warmup; + const root = server.config.root; + if (options?.clientFiles?.length) { + mapFiles(options.clientFiles, root).then((files) => { + for (const file of files) { + warmupFile(server, file, false); + } + }); + } + if (options?.ssrFiles?.length) { + mapFiles(options.ssrFiles, root).then((files) => { + for (const file of files) { + warmupFile(server, file, true); + } + }); + } +} +async function warmupFile(server, file, ssr) { + // transform html with the `transformIndexHtml` hook as Vite internals would + // pre-transform the imported JS modules linked. this may cause `transformIndexHtml` + // plugins to be executed twice, but that's probably fine. + if (file.endsWith('.html')) { + const url = htmlFileToUrl(file, server.config.root); + if (url) { + try { + const html = await fsp.readFile(file, 'utf-8'); + await server.transformIndexHtml(url, html); + } + catch (e) { + // Unexpected error, log the issue but avoid an unhandled exception + server.config.logger.error(`Pre-transform error (${colors$1.cyan(file)}): ${e.message}`, { + error: e, + timestamp: true, + }); + } + } + } + // for other files, pass it through `transformRequest` with warmup + else { + const url = fileToUrl(file, server.config.root); + await server.warmupRequest(url, { ssr }); + } +} +function htmlFileToUrl(file, root) { + const url = path$o.relative(root, file); + // out of root, ignore file + if (url[0] === '.') + return; + // file within root, create root-relative url + return '/' + normalizePath$3(url); +} +function fileToUrl(file, root) { + const url = path$o.relative(root, file); + // out of root, use /@fs/ prefix + if (url[0] === '.') { + return path$o.posix.join(FS_PREFIX, normalizePath$3(file)); + } + // file within root, create root-relative url + return '/' + normalizePath$3(url); +} +function mapFiles(files, root) { + return glob(files, { + cwd: root, + absolute: true, + }); +} + +function createServer(inlineConfig = {}) { + return _createServer(inlineConfig, { ws: true }); +} +async function _createServer(inlineConfig = {}, options) { + const config = await resolveConfig(inlineConfig, 'serve'); + const initPublicFilesPromise = initPublicFiles(config); + const { root, server: serverConfig } = config; + const httpsOptions = await resolveHttpsConfig(config.server.https); + const { middlewareMode } = serverConfig; + const resolvedWatchOptions = resolveChokidarOptions(config, { + disableGlobbing: true, + ...serverConfig.watch, + }); + const middlewares = connect$1(); + const httpServer = middlewareMode + ? null + : await resolveHttpServer(serverConfig, middlewares, httpsOptions); + const ws = createWebSocketServer(httpServer, config, httpsOptions); + if (httpServer) { + setClientErrorHandler(httpServer, config.logger); + } + // eslint-disable-next-line eqeqeq + const watchEnabled = serverConfig.watch !== null; + const watcher = watchEnabled + ? chokidar.watch( + // config file dependencies and env file might be outside of root + [...new Set([root, ...config.configFileDependencies, config.envDir])], resolvedWatchOptions) + : createNoopWatcher(resolvedWatchOptions); + const moduleGraph = new ModuleGraph((url, ssr) => container.resolveId(url, undefined, { ssr })); + const container = await createPluginContainer(config, moduleGraph, watcher); + const closeHttpServer = createServerCloseFn(httpServer); + let exitProcess; + const devHtmlTransformFn = createDevHtmlTransformFn(config); + let server = { + config, + middlewares, + httpServer, + watcher, + pluginContainer: container, + ws, + moduleGraph, + resolvedUrls: null, + ssrTransform(code, inMap, url, originalCode = code) { + return ssrTransform(code, inMap, url, originalCode, server.config); + }, + transformRequest(url, options) { + return transformRequest(url, server, options); + }, + async warmupRequest(url, options) { + await transformRequest(url, server, options).catch((e) => { + if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP || + e?.code === ERR_CLOSED_SERVER) { + // these are expected errors + return; + } + // Unexpected error, log the issue but avoid an unhandled exception + server.config.logger.error(`Pre-transform error: ${e.message}`, { + error: e, + timestamp: true, + }); + }); + }, + transformIndexHtml(url, html, originalUrl) { + return devHtmlTransformFn(server, url, html, originalUrl); + }, + async ssrLoadModule(url, opts) { + if (isDepsOptimizerEnabled(config, true)) { + await initDevSsrDepsOptimizer(config, server); + } + return ssrLoadModule(url, server, undefined, undefined, opts?.fixStacktrace); + }, + ssrFixStacktrace(e) { + ssrFixStacktrace(e, moduleGraph); + }, + ssrRewriteStacktrace(stack) { + return ssrRewriteStacktrace(stack, moduleGraph); + }, + async reloadModule(module) { + if (serverConfig.hmr !== false && module.file) { + updateModules(module.file, [module], Date.now(), server); + } + }, + async listen(port, isRestart) { + await startServer(server, port); + if (httpServer) { + server.resolvedUrls = await resolveServerUrls(httpServer, config.server, config); + if (!isRestart && config.server.open) + server.openBrowser(); + } + return server; + }, + openBrowser() { + const options = server.config.server; + const url = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0]; + if (url) { + const path = typeof options.open === 'string' + ? new URL(options.open, url).href + : url; + // We know the url that the browser would be opened to, so we can + // start the request while we are awaiting the browser. This will + // start the crawling of static imports ~500ms before. + // preTransformRequests needs to be enabled for this optimization. + if (server.config.server.preTransformRequests) { + setTimeout(() => { + const getMethod = path.startsWith('https:') ? get$1 : get$2; + getMethod(path, { + headers: { + // Allow the history middleware to redirect to /index.html + Accept: 'text/html', + }, + }, (res) => { + res.on('end', () => { + // Ignore response, scripts discovered while processing the entry + // will be preprocessed (server.config.server.preTransformRequests) + }); + }) + .on('error', () => { + // Ignore errors + }) + .end(); + }, 0); + } + openBrowser(path, true, server.config.logger); + } + else { + server.config.logger.warn('No URL available to open in browser'); + } + }, + async close() { + if (!middlewareMode) { + process.off('SIGTERM', exitProcess); + if (process.env.CI !== 'true') { + process.stdin.off('end', exitProcess); + } + } + await Promise.allSettled([ + watcher.close(), + ws.close(), + container.close(), + getDepsOptimizer(server.config)?.close(), + getDepsOptimizer(server.config, true)?.close(), + closeHttpServer(), + ]); + // Await pending requests. We throw early in transformRequest + // and in hooks if the server is closing for non-ssr requests, + // so the import analysis plugin stops pre-transforming static + // imports and this block is resolved sooner. + // During SSR, we let pending requests finish to avoid exposing + // the server closed error to the users. + while (server._pendingRequests.size > 0) { + await Promise.allSettled([...server._pendingRequests.values()].map((pending) => pending.request)); + } + server.resolvedUrls = null; + }, + printUrls() { + if (server.resolvedUrls) { + printServerUrls(server.resolvedUrls, serverConfig.host, config.logger.info); + } + else if (middlewareMode) { + throw new Error('cannot print server URLs in middleware mode.'); + } + else { + throw new Error('cannot print server URLs before server.listen is called.'); + } + }, + bindCLIShortcuts(options) { + bindCLIShortcuts(server, options); + }, + async restart(forceOptimize) { + if (!server._restartPromise) { + server._forceOptimizeOnRestart = !!forceOptimize; + server._restartPromise = restartServer(server).finally(() => { + server._restartPromise = null; + server._forceOptimizeOnRestart = false; + }); + } + return server._restartPromise; + }, + _setInternalServer(_server) { + // Rebind internal the server variable so functions reference the user + // server instance after a restart + server = _server; + }, + _restartPromise: null, + _importGlobMap: new Map(), + _forceOptimizeOnRestart: false, + _pendingRequests: new Map(), + _fsDenyGlob: picomatch$4(config.server.fs.deny, { matchBase: true }), + _shortcutsOptions: undefined, + }; + if (!middlewareMode) { + exitProcess = async () => { + try { + await server.close(); + } + finally { + process.exit(); + } + }; + process.once('SIGTERM', exitProcess); + if (process.env.CI !== 'true') { + process.stdin.on('end', exitProcess); + } + } + const publicFiles = await initPublicFilesPromise; + const onHMRUpdate = async (file, configOnly) => { + if (serverConfig.hmr !== false) { + try { + await handleHMRUpdate(file, server, configOnly); + } + catch (err) { + ws.send({ + type: 'error', + err: prepareError(err), + }); + } + } + }; + const normalizedPublicDir = normalizePath$3(config.publicDir); + const onFileAddUnlink = async (file, isUnlink) => { + file = normalizePath$3(file); + await container.watchChange(file, { event: isUnlink ? 'delete' : 'create' }); + if (config.publicDir && publicFiles) { + if (file.startsWith(normalizedPublicDir)) { + publicFiles[isUnlink ? 'delete' : 'add'](file.slice(normalizedPublicDir.length)); + } + } + await handleFileAddUnlink(file, server, isUnlink); + await onHMRUpdate(file, true); + }; + watcher.on('change', async (file) => { + file = normalizePath$3(file); + await container.watchChange(file, { event: 'update' }); + // invalidate module graph cache on file change + moduleGraph.onFileChange(file); + await onHMRUpdate(file, false); + }); + getFsUtils(config).initWatcher?.(watcher); + watcher.on('add', (file) => { + onFileAddUnlink(file, false); + }); + watcher.on('unlink', (file) => { + onFileAddUnlink(file, true); + }); + ws.on('vite:invalidate', async ({ path, message }) => { + const mod = moduleGraph.urlToModuleMap.get(path); + if (mod && mod.isSelfAccepting && mod.lastHMRTimestamp > 0) { + config.logger.info(colors$1.yellow(`hmr invalidate `) + + colors$1.dim(path) + + (message ? ` ${message}` : ''), { timestamp: true }); + const file = getShortName(mod.file, config.root); + updateModules(file, [...mod.importers], mod.lastHMRTimestamp, server, true); + } + }); + if (!middlewareMode && httpServer) { + httpServer.once('listening', () => { + // update actual port since this may be different from initial value + serverConfig.port = httpServer.address().port; + }); + } + // apply server configuration hooks from plugins + const postHooks = []; + for (const hook of config.getSortedPluginHooks('configureServer')) { + postHooks.push(await hook(server)); + } + // Internal middlewares ------------------------------------------------------ + // request timer + if (process.env.DEBUG) { + middlewares.use(timeMiddleware(root)); + } + // cors (enabled by default) + const { cors } = serverConfig; + if (cors !== false) { + middlewares.use(corsMiddleware(typeof cors === 'boolean' ? {} : cors)); + } + // proxy + const { proxy } = serverConfig; + if (proxy) { + const middlewareServer = (isObject$1(serverConfig.middlewareMode) + ? serverConfig.middlewareMode.server + : null) || httpServer; + middlewares.use(proxyMiddleware(middlewareServer, proxy, config)); + } + // base + if (config.base !== '/') { + middlewares.use(baseMiddleware(config.rawBase, middlewareMode)); + } + // open in editor support + middlewares.use('/__open-in-editor', launchEditorMiddleware$1()); + // ping request handler + // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` + middlewares.use(function viteHMRPingMiddleware(req, res, next) { + if (req.headers['accept'] === 'text/x-vite-ping') { + res.writeHead(204).end(); + } + else { + next(); + } + }); + // serve static files under /public + // this applies before the transform middleware so that these files are served + // as-is without transforms. + if (config.publicDir) { + middlewares.use(servePublicMiddleware(server, publicFiles)); + } + // main transform middleware + middlewares.use(transformMiddleware(server)); + // serve static files + middlewares.use(serveRawFsMiddleware(server)); + middlewares.use(serveStaticMiddleware(server)); + // html fallback + if (config.appType === 'spa' || config.appType === 'mpa') { + middlewares.use(htmlFallbackMiddleware(root, config.appType === 'spa', getFsUtils(config))); + } + // run post config hooks + // This is applied before the html middleware so that user middleware can + // serve custom content instead of index.html. + postHooks.forEach((fn) => fn && fn()); + if (config.appType === 'spa' || config.appType === 'mpa') { + // transform index.html + middlewares.use(indexHtmlMiddleware(root, server)); + // handle 404s + middlewares.use(notFoundMiddleware()); + } + // error handler + middlewares.use(errorMiddleware(server, middlewareMode)); + // httpServer.listen can be called multiple times + // when port when using next port number + // this code is to avoid calling buildStart multiple times + let initingServer; + let serverInited = false; + const initServer = async () => { + if (serverInited) + return; + if (initingServer) + return initingServer; + initingServer = (async function () { + await container.buildStart({}); + // start deps optimizer after all container plugins are ready + if (isDepsOptimizerEnabled(config, false)) { + await initDepsOptimizer(config, server); + } + warmupFiles(server); + initingServer = undefined; + serverInited = true; + })(); + return initingServer; + }; + if (!middlewareMode && httpServer) { + // overwrite listen to init optimizer before server start + const listen = httpServer.listen.bind(httpServer); + httpServer.listen = (async (port, ...args) => { + try { + // ensure ws server started + ws.listen(); + await initServer(); + } + catch (e) { + httpServer.emit('error', e); + return; + } + return listen(port, ...args); + }); + } + else { + if (options.ws) { + ws.listen(); + } + await initServer(); + } + return server; +} +async function startServer(server, inlinePort) { + const httpServer = server.httpServer; + if (!httpServer) { + throw new Error('Cannot call server.listen in middleware mode.'); + } + const options = server.config.server; + const hostname = await resolveHostname(options.host); + const configPort = inlinePort ?? options.port; + // When using non strict port for the dev server, the running port can be different from the config one. + // When restarting, the original port may be available but to avoid a switch of URL for the running + // browser tabs, we enforce the previously used port, expect if the config port changed. + const port = (!configPort || configPort === server._configServerPort + ? server._currentServerPort + : configPort) ?? DEFAULT_DEV_PORT; + server._configServerPort = configPort; + const serverPort = await httpServerStart(httpServer, { + port, + strictPort: options.strictPort, + host: hostname.host, + logger: server.config.logger, + }); + server._currentServerPort = serverPort; +} +function createServerCloseFn(server) { + if (!server) { + return () => { }; + } + let hasListened = false; + const openSockets = new Set(); + server.on('connection', (socket) => { + openSockets.add(socket); + socket.on('close', () => { + openSockets.delete(socket); + }); + }); + server.once('listening', () => { + hasListened = true; + }); + return () => new Promise((resolve, reject) => { + openSockets.forEach((s) => s.destroy()); + if (hasListened) { + server.close((err) => { + if (err) { + reject(err); + } + else { + resolve(); + } + }); + } + else { + resolve(); + } + }); +} +function resolvedAllowDir(root, dir) { + return normalizePath$3(path$o.resolve(root, dir)); +} +function resolveServerOptions(root, raw, logger) { + const server = { + preTransformRequests: true, + ...raw, + sourcemapIgnoreList: raw?.sourcemapIgnoreList === false + ? () => false + : raw?.sourcemapIgnoreList || isInNodeModules$1, + middlewareMode: !!raw?.middlewareMode, + }; + let allowDirs = server.fs?.allow; + const deny = server.fs?.deny || ['.env', '.env.*', '*.{crt,pem}']; + if (!allowDirs) { + allowDirs = [searchForWorkspaceRoot(root)]; + } + allowDirs = allowDirs.map((i) => resolvedAllowDir(root, i)); + // only push client dir when vite itself is outside-of-root + const resolvedClientDir = resolvedAllowDir(root, CLIENT_DIR); + if (!allowDirs.some((dir) => isParentDirectory(dir, resolvedClientDir))) { + allowDirs.push(resolvedClientDir); + } + server.fs = { + strict: server.fs?.strict ?? true, + allow: allowDirs, + deny, + cachedChecks: server.fs?.cachedChecks ?? !!process.env.VITE_SERVER_FS_CACHED_CHECKS, + }; + if (server.origin?.endsWith('/')) { + server.origin = server.origin.slice(0, -1); + logger.warn(colors$1.yellow(`${colors$1.bold('(!)')} server.origin should not end with "/". Using "${server.origin}" instead.`)); + } + return server; +} +async function restartServer(server) { + global.__vite_start_time = performance.now(); + const shortcutsOptions = server._shortcutsOptions; + let inlineConfig = server.config.inlineConfig; + if (server._forceOptimizeOnRestart) { + inlineConfig = mergeConfig(inlineConfig, { + optimizeDeps: { + force: true, + }, + }); + } + // Reinit the server by creating a new instance using the same inlineConfig + // This will triger a reload of the config file and re-create the plugins and + // middlewares. We then assign all properties of the new server to the existing + // server instance and set the user instance to be used in the new server. + // This allows us to keep the same server instance for the user. + { + let newServer = null; + try { + // delay ws server listen + newServer = await _createServer(inlineConfig, { ws: false }); + } + catch (err) { + server.config.logger.error(err.message, { + timestamp: true, + }); + server.config.logger.error('server restart failed', { timestamp: true }); + return; + } + await server.close(); + // Assign new server props to existing server instance + const middlewares = server.middlewares; + newServer._configServerPort = server._configServerPort; + newServer._currentServerPort = server._currentServerPort; + Object.assign(server, newServer); + // Keep the same connect instance so app.use(vite.middlewares) works + // after a restart in middlewareMode (.route is always '/') + middlewares.stack = newServer.middlewares.stack; + server.middlewares = middlewares; + // Rebind internal server variable so functions reference the user server + newServer._setInternalServer(server); + } + const { logger, server: { port, middlewareMode }, } = server.config; + if (!middlewareMode) { + await server.listen(port, true); + } + else { + server.ws.listen(); + } + logger.info('server restarted.', { timestamp: true }); + if (shortcutsOptions) { + shortcutsOptions.print = false; + bindCLIShortcuts(server, shortcutsOptions); + } +} +/** + * Internal function to restart the Vite server and print URLs if changed + */ +async function restartServerWithUrls(server) { + if (server.config.server.middlewareMode) { + await server.restart(); + return; + } + const { port: prevPort, host: prevHost } = server.config.server; + const prevUrls = server.resolvedUrls; + await server.restart(); + const { logger, server: { port, host }, } = server.config; + if ((port ?? DEFAULT_DEV_PORT) !== (prevPort ?? DEFAULT_DEV_PORT) || + host !== prevHost || + diffDnsOrderChange(prevUrls, server.resolvedUrls)) { + logger.info(''); + server.printUrls(); + } +} + +var index$1 = { + __proto__: null, + _createServer: _createServer, + createServer: createServer, + resolveServerOptions: resolveServerOptions, + restartServerWithUrls: restartServerWithUrls +}; + +const debugHmr = createDebugger('vite:hmr'); +const whitespaceRE = /\s/; +const normalizedClientDir = normalizePath$3(CLIENT_DIR); +function getShortName(file, root) { + return file.startsWith(withTrailingSlash(root)) + ? path$o.posix.relative(root, file) + : file; +} +async function handleHMRUpdate(file, server, configOnly) { + const { ws, config, moduleGraph } = server; + const shortFile = getShortName(file, config.root); + const fileName = path$o.basename(file); + const isConfig = file === config.configFile; + const isConfigDependency = config.configFileDependencies.some((name) => file === name); + const isEnv = config.inlineConfig.envFile !== false && + getEnvFilesForMode(config.mode).includes(fileName); + if (isConfig || isConfigDependency || isEnv) { + // auto restart server + debugHmr?.(`[config change] ${colors$1.dim(shortFile)}`); + config.logger.info(colors$1.green(`${path$o.relative(process.cwd(), file)} changed, restarting server...`), { clear: true, timestamp: true }); + try { + await restartServerWithUrls(server); + } + catch (e) { + config.logger.error(colors$1.red(e)); + } + return; + } + if (configOnly) { + return; + } + debugHmr?.(`[file change] ${colors$1.dim(shortFile)}`); + // (dev only) the client itself cannot be hot updated. + if (file.startsWith(withTrailingSlash(normalizedClientDir))) { + ws.send({ + type: 'full-reload', + path: '*', + }); + return; + } + const mods = moduleGraph.getModulesByFile(file); + // check if any plugin wants to perform custom HMR handling + const timestamp = Date.now(); + const hmrContext = { + file, + timestamp, + modules: mods ? [...mods] : [], + read: () => readModifiedFile(file), + server, + }; + for (const hook of config.getSortedPluginHooks('handleHotUpdate')) { + const filteredModules = await hook(hmrContext); + if (filteredModules) { + hmrContext.modules = filteredModules; + } + } + if (!hmrContext.modules.length) { + // html file cannot be hot updated + if (file.endsWith('.html')) { + config.logger.info(colors$1.green(`page reload `) + colors$1.dim(shortFile), { + clear: true, + timestamp: true, + }); + ws.send({ + type: 'full-reload', + path: config.server.middlewareMode + ? '*' + : '/' + normalizePath$3(path$o.relative(config.root, file)), + }); + } + else { + // loaded but not in the module graph, probably not js + debugHmr?.(`[no modules matched] ${colors$1.dim(shortFile)}`); + } + return; + } + updateModules(shortFile, hmrContext.modules, timestamp, server); +} +function updateModules(file, modules, timestamp, { config, ws, moduleGraph }, afterInvalidation) { + const updates = []; + const invalidatedModules = new Set(); + const traversedModules = new Set(); + let needFullReload = false; + for (const mod of modules) { + const boundaries = []; + const hasDeadEnd = propagateUpdate(mod, traversedModules, boundaries); + moduleGraph.invalidateModule(mod, invalidatedModules, timestamp, true); + if (needFullReload) { + continue; + } + if (hasDeadEnd) { + needFullReload = hasDeadEnd; + continue; + } + updates.push(...boundaries.map(({ boundary, acceptedVia }) => ({ + type: `${boundary.type}-update`, + timestamp, + path: normalizeHmrUrl(boundary.url), + explicitImportRequired: boundary.type === 'js' + ? isExplicitImportRequired(acceptedVia.url) + : undefined, + acceptedPath: normalizeHmrUrl(acceptedVia.url), + }))); + } + if (needFullReload) { + const reason = typeof needFullReload === 'string' + ? colors$1.dim(` (${needFullReload})`) + : ''; + config.logger.info(colors$1.green(`page reload `) + colors$1.dim(file) + reason, { clear: !afterInvalidation, timestamp: true }); + ws.send({ + type: 'full-reload', + }); + return; + } + if (updates.length === 0) { + debugHmr?.(colors$1.yellow(`no update happened `) + colors$1.dim(file)); + return; + } + config.logger.info(colors$1.green(`hmr update `) + + colors$1.dim([...new Set(updates.map((u) => u.path))].join(', ')), { clear: !afterInvalidation, timestamp: true }); + ws.send({ + type: 'update', + updates, + }); +} +async function handleFileAddUnlink(file, server, isUnlink) { + const modules = [...(server.moduleGraph.getModulesByFile(file) || [])]; + if (isUnlink) { + for (const deletedMod of modules) { + deletedMod.importedModules.forEach((importedMod) => { + importedMod.importers.delete(deletedMod); + }); + } + } + modules.push(...getAffectedGlobModules(file, server)); + if (modules.length > 0) { + updateModules(getShortName(file, server.config.root), unique(modules), Date.now(), server); + } +} +function areAllImportsAccepted(importedBindings, acceptedExports) { + for (const binding of importedBindings) { + if (!acceptedExports.has(binding)) { + return false; + } + } + return true; +} +function propagateUpdate(node, traversedModules, boundaries, currentChain = [node]) { + if (traversedModules.has(node)) { + return false; + } + traversedModules.add(node); + // #7561 + // if the imports of `node` have not been analyzed, then `node` has not + // been loaded in the browser and we should stop propagation. + if (node.id && node.isSelfAccepting === undefined) { + debugHmr?.(`[propagate update] stop propagation because not analyzed: ${colors$1.dim(node.id)}`); + return false; + } + if (node.isSelfAccepting) { + boundaries.push({ boundary: node, acceptedVia: node }); + const result = isNodeWithinCircularImports(node, currentChain); + if (result) + return result; + // additionally check for CSS importers, since a PostCSS plugin like + // Tailwind JIT may register any file as a dependency to a CSS file. + for (const importer of node.importers) { + if (isCSSRequest(importer.url) && !currentChain.includes(importer)) { + propagateUpdate(importer, traversedModules, boundaries, currentChain.concat(importer)); + } + } + return false; + } + // A partially accepted module with no importers is considered self accepting, + // because the deal is "there are parts of myself I can't self accept if they + // are used outside of me". + // Also, the imported module (this one) must be updated before the importers, + // so that they do get the fresh imported module when/if they are reloaded. + if (node.acceptedHmrExports) { + boundaries.push({ boundary: node, acceptedVia: node }); + const result = isNodeWithinCircularImports(node, currentChain); + if (result) + return result; + } + else { + if (!node.importers.size) { + return true; + } + // #3716, #3913 + // For a non-CSS file, if all of its importers are CSS files (registered via + // PostCSS plugins) it should be considered a dead end and force full reload. + if (!isCSSRequest(node.url) && + [...node.importers].every((i) => isCSSRequest(i.url))) { + return true; + } + } + for (const importer of node.importers) { + const subChain = currentChain.concat(importer); + if (importer.acceptedHmrDeps.has(node)) { + boundaries.push({ boundary: importer, acceptedVia: node }); + const result = isNodeWithinCircularImports(importer, subChain); + if (result) + return result; + continue; + } + if (node.id && node.acceptedHmrExports && importer.importedBindings) { + const importedBindingsFromNode = importer.importedBindings.get(node.id); + if (importedBindingsFromNode && + areAllImportsAccepted(importedBindingsFromNode, node.acceptedHmrExports)) { + continue; + } + } + if (!currentChain.includes(importer) && + propagateUpdate(importer, traversedModules, boundaries, subChain)) { + return true; + } + } + return false; +} +/** + * Check importers recursively if it's an import loop. An accepted module within + * an import loop cannot recover its execution order and should be reloaded. + * + * @param node The node that accepts HMR and is a boundary + * @param nodeChain The chain of nodes/imports that lead to the node. + * (The last node in the chain imports the `node` parameter) + * @param currentChain The current chain tracked from the `node` parameter + * @param traversedModules The set of modules that have traversed + */ +function isNodeWithinCircularImports(node, nodeChain, currentChain = [node], traversedModules = new Set()) { + // To help visualize how each parameters work, imagine this import graph: + // + // A -> B -> C -> ACCEPTED -> D -> E -> NODE + // ^--------------------------| + // + // ACCEPTED: the node that accepts HMR. the `node` parameter. + // NODE : the initial node that triggered this HMR. + // + // This function will return true in the above graph, which: + // `node` : ACCEPTED + // `nodeChain` : [NODE, E, D, ACCEPTED] + // `currentChain` : [ACCEPTED, C, B] + // + // It works by checking if any `node` importers are within `nodeChain`, which + // means there's an import loop with a HMR-accepted module in it. + if (traversedModules.has(node)) { + return false; + } + traversedModules.add(node); + for (const importer of node.importers) { + // Node may import itself which is safe + if (importer === node) + continue; + // a PostCSS plugin like Tailwind JIT may register + // any file as a dependency to a CSS file. + // But in that case, the actual dependency chain is separate. + if (isCSSRequest(importer.url)) + continue; + // Check circular imports + const importerIndex = nodeChain.indexOf(importer); + if (importerIndex > -1) { + // Log extra debug information so users can fix and remove the circular imports + if (debugHmr) { + // Following explanation above: + // `importer` : E + // `currentChain` reversed : [B, C, ACCEPTED] + // `nodeChain` sliced & reversed : [D, E] + // Combined : [E, B, C, ACCEPTED, D, E] + const importChain = [ + importer, + ...[...currentChain].reverse(), + ...nodeChain.slice(importerIndex, -1).reverse(), + ]; + debugHmr(colors$1.yellow(`circular imports detected: `) + + importChain.map((m) => colors$1.dim(m.url)).join(' -> ')); + } + return 'circular imports'; + } + // Continue recursively + if (!currentChain.includes(importer)) { + const result = isNodeWithinCircularImports(importer, nodeChain, currentChain.concat(importer), traversedModules); + if (result) + return result; + } + } + return false; +} +function handlePrunedModules(mods, { ws }) { + // update the disposed modules' hmr timestamp + // since if it's re-imported, it should re-apply side effects + // and without the timestamp the browser will not re-import it! + const t = Date.now(); + mods.forEach((mod) => { + mod.lastHMRTimestamp = t; + debugHmr?.(`[dispose] ${colors$1.dim(mod.file)}`); + }); + ws.send({ + type: 'prune', + paths: [...mods].map((m) => m.url), + }); +} +/** + * Lex import.meta.hot.accept() for accepted deps. + * Since hot.accept() can only accept string literals or array of string + * literals, we don't really need a heavy @babel/parse call on the entire source. + * + * @returns selfAccepts + */ +function lexAcceptedHmrDeps(code, start, urls) { + let state = 0 /* LexerState.inCall */; + // the state can only be 2 levels deep so no need for a stack + let prevState = 0 /* LexerState.inCall */; + let currentDep = ''; + function addDep(index) { + urls.add({ + url: currentDep, + start: index - currentDep.length - 1, + end: index + 1, + }); + currentDep = ''; + } + for (let i = start; i < code.length; i++) { + const char = code.charAt(i); + switch (state) { + case 0 /* LexerState.inCall */: + case 4 /* LexerState.inArray */: + if (char === `'`) { + prevState = state; + state = 1 /* LexerState.inSingleQuoteString */; + } + else if (char === `"`) { + prevState = state; + state = 2 /* LexerState.inDoubleQuoteString */; + } + else if (char === '`') { + prevState = state; + state = 3 /* LexerState.inTemplateString */; + } + else if (whitespaceRE.test(char)) { + continue; + } + else { + if (state === 0 /* LexerState.inCall */) { + if (char === `[`) { + state = 4 /* LexerState.inArray */; + } + else { + // reaching here means the first arg is neither a string literal + // nor an Array literal (direct callback) or there is no arg + // in both case this indicates a self-accepting module + return true; // done + } + } + else if (state === 4 /* LexerState.inArray */) { + if (char === `]`) { + return false; // done + } + else if (char === ',') { + continue; + } + else { + error(i); + } + } + } + break; + case 1 /* LexerState.inSingleQuoteString */: + if (char === `'`) { + addDep(i); + if (prevState === 0 /* LexerState.inCall */) { + // accept('foo', ...) + return false; + } + else { + state = prevState; + } + } + else { + currentDep += char; + } + break; + case 2 /* LexerState.inDoubleQuoteString */: + if (char === `"`) { + addDep(i); + if (prevState === 0 /* LexerState.inCall */) { + // accept('foo', ...) + return false; + } + else { + state = prevState; + } + } + else { + currentDep += char; + } + break; + case 3 /* LexerState.inTemplateString */: + if (char === '`') { + addDep(i); + if (prevState === 0 /* LexerState.inCall */) { + // accept('foo', ...) + return false; + } + else { + state = prevState; + } + } + else if (char === '$' && code.charAt(i + 1) === '{') { + error(i); + } + else { + currentDep += char; + } + break; + default: + throw new Error('unknown import.meta.hot lexer state'); + } + } + return false; +} +function lexAcceptedHmrExports(code, start, exportNames) { + const urls = new Set(); + lexAcceptedHmrDeps(code, start, urls); + for (const { url } of urls) { + exportNames.add(url); + } + return urls.size > 0; +} +function normalizeHmrUrl(url) { + if (url[0] !== '.' && url[0] !== '/') { + url = wrapId(url); + } + return url; +} +function error(pos) { + const err = new Error(`import.meta.hot.accept() can only accept string literals or an ` + + `Array of string literals.`); + err.pos = pos; + throw err; +} +// vitejs/vite#610 when hot-reloading Vue files, we read immediately on file +// change event and sometimes this can be too early and get an empty buffer. +// Poll until the file's modified time has changed before reading again. +async function readModifiedFile(file) { + const content = await fsp.readFile(file, 'utf-8'); + if (!content) { + const mtime = (await fsp.stat(file)).mtimeMs; + await new Promise((r) => { + let n = 0; + const poll = async () => { + n++; + const newMtime = (await fsp.stat(file)).mtimeMs; + if (newMtime !== mtime || n > 10) { + r(0); + } + else { + setTimeout(poll, 10); + } + }; + setTimeout(poll, 10); + }); + return await fsp.readFile(file, 'utf-8'); + } + else { + return content; + } +} + +const nonJsRe = /\.json(?:$|\?)/; +const isNonJsRequest = (request) => nonJsRe.test(request); +function definePlugin(config) { + const isBuild = config.command === 'build'; + const isBuildLib = isBuild && config.build.lib; + // ignore replace process.env in lib build + const processEnv = {}; + if (!isBuildLib) { + const nodeEnv = process.env.NODE_ENV || config.mode; + Object.assign(processEnv, { + 'process.env': `{}`, + 'global.process.env': `{}`, + 'globalThis.process.env': `{}`, + 'process.env.NODE_ENV': JSON.stringify(nodeEnv), + 'global.process.env.NODE_ENV': JSON.stringify(nodeEnv), + 'globalThis.process.env.NODE_ENV': JSON.stringify(nodeEnv), + }); + } + // during dev, import.meta properties are handled by importAnalysis plugin. + const importMetaKeys = {}; + const importMetaEnvKeys = {}; + const importMetaFallbackKeys = {}; + if (isBuild) { + importMetaKeys['import.meta.hot'] = `undefined`; + for (const key in config.env) { + const val = JSON.stringify(config.env[key]); + importMetaKeys[`import.meta.env.${key}`] = val; + importMetaEnvKeys[key] = val; + } + // these will be set to a proper value in `generatePattern` + importMetaKeys['import.meta.env.SSR'] = `undefined`; + importMetaFallbackKeys['import.meta.env'] = `undefined`; + } + const userDefine = {}; + const userDefineEnv = {}; + for (const key in config.define) { + userDefine[key] = handleDefineValue(config.define[key]); + // make sure `import.meta.env` object has user define properties + if (isBuild && key.startsWith('import.meta.env.')) { + userDefineEnv[key.slice(16)] = config.define[key]; + } + } + function generatePattern(ssr) { + const replaceProcessEnv = !ssr || config.ssr?.target === 'webworker'; + const define = { + ...(replaceProcessEnv ? processEnv : {}), + ...importMetaKeys, + ...userDefine, + ...importMetaFallbackKeys, + }; + // Additional define fixes based on `ssr` value + if ('import.meta.env.SSR' in define) { + define['import.meta.env.SSR'] = ssr + ''; + } + if ('import.meta.env' in define) { + define['import.meta.env'] = serializeDefine({ + ...importMetaEnvKeys, + SSR: ssr + '', + ...userDefineEnv, + }); + } + // Create regex pattern as a fast check before running esbuild + const patternKeys = Object.keys(userDefine); + if (replaceProcessEnv && Object.keys(processEnv).length) { + patternKeys.push('process.env'); + } + if (Object.keys(importMetaKeys).length) { + patternKeys.push('import.meta.env', 'import.meta.hot'); + } + const pattern = patternKeys.length + ? new RegExp(patternKeys.map(escapeRegex).join('|')) + : null; + return [define, pattern]; + } + const defaultPattern = generatePattern(false); + const ssrPattern = generatePattern(true); + return { + name: 'vite:define', + async transform(code, id, options) { + const ssr = options?.ssr === true; + if (!ssr && !isBuild) { + // for dev we inject actual global defines in the vite client to + // avoid the transform cost. see the `clientInjection` and + // `importAnalysis` plugin. + return; + } + if ( + // exclude html, css and static assets for performance + isHTMLRequest(id) || + isCSSRequest(id) || + isNonJsRequest(id) || + config.assetsInclude(id)) { + return; + } + const [define, pattern] = ssr ? ssrPattern : defaultPattern; + if (!pattern) + return; + // Check if our code needs any replacements before running esbuild + pattern.lastIndex = 0; + if (!pattern.test(code)) + return; + return await replaceDefine(code, id, define, config); + }, + }; +} +async function replaceDefine(code, id, define, config) { + // Because esbuild only allows JSON-serializable values, and `import.meta.env` + // may contain values with raw identifiers, making it non-JSON-serializable, + // we replace it with a temporary marker and then replace it back after to + // workaround it. This means that esbuild is unable to optimize the `import.meta.env` + // access, but that's a tradeoff for now. + const replacementMarkers = {}; + const env = define['import.meta.env']; + if (env && !canJsonParse(env)) { + const marker = `_${getHash(env, env.length - 2)}_`; + replacementMarkers[marker] = env; + define = { ...define, 'import.meta.env': marker }; + } + const esbuildOptions = config.esbuild || {}; + const result = await transform$1(code, { + loader: 'js', + charset: esbuildOptions.charset ?? 'utf8', + platform: 'neutral', + define, + sourcefile: id, + sourcemap: config.command === 'build' ? !!config.build.sourcemap : true, + }); + for (const marker in replacementMarkers) { + result.code = result.code.replaceAll(marker, replacementMarkers[marker]); + } + return { + code: result.code, + map: result.map || null, + }; +} +/** + * Like `JSON.stringify` but keeps raw string values as a literal + * in the generated code. For example: `"window"` would refer to + * the global `window` object directly. + */ +function serializeDefine(define) { + let res = `{`; + const keys = Object.keys(define); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const val = define[key]; + res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`; + if (i !== keys.length - 1) { + res += `, `; + } + } + return res + `}`; +} +function handleDefineValue(value) { + if (typeof value === 'undefined') + return 'undefined'; + if (typeof value === 'string') + return value; + return JSON.stringify(value); +} +function canJsonParse(value) { + try { + JSON.parse(value); + return true; + } + catch { + return false; + } +} + +const WORKER_FILE_ID = 'worker_file'; +const workerCache = new WeakMap(); +function saveEmitWorkerAsset(config, asset) { + const fileName = asset.fileName; + const workerMap = workerCache.get(config.mainConfig || config); + workerMap.assets.set(fileName, asset); +} +async function bundleWorkerEntry(config, id, query) { + // bundle the file as entry to support imports + const { rollup } = await import('rollup'); + const { plugins, rollupOptions, format } = config.worker; + const bundle = await rollup({ + ...rollupOptions, + input: cleanUrl(id), + plugins: await plugins(), + onwarn(warning, warn) { + onRollupWarning(warning, warn, config); + }, + preserveEntrySignatures: false, + }); + let chunk; + try { + const workerOutputConfig = config.worker.rollupOptions.output; + const workerConfig = workerOutputConfig + ? Array.isArray(workerOutputConfig) + ? workerOutputConfig[0] || {} + : workerOutputConfig + : {}; + const { output: [outputChunk, ...outputChunks], } = await bundle.generate({ + entryFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].js'), + chunkFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].js'), + assetFileNames: path$o.posix.join(config.build.assetsDir, '[name]-[hash].[ext]'), + ...workerConfig, + format, + sourcemap: config.build.sourcemap, + }); + chunk = outputChunk; + outputChunks.forEach((outputChunk) => { + if (outputChunk.type === 'asset') { + saveEmitWorkerAsset(config, outputChunk); + } + else if (outputChunk.type === 'chunk') { + saveEmitWorkerAsset(config, { + fileName: outputChunk.fileName, + source: outputChunk.code, + type: 'asset', + }); + } + }); + } + finally { + await bundle.close(); + } + return emitSourcemapForWorkerEntry(config, query, chunk); +} +function emitSourcemapForWorkerEntry(config, query, chunk) { + const { map: sourcemap } = chunk; + if (sourcemap) { + if (config.build.sourcemap === 'hidden' || + config.build.sourcemap === true) { + const data = sourcemap.toString(); + const mapFileName = chunk.fileName + '.map'; + saveEmitWorkerAsset(config, { + fileName: mapFileName, + type: 'asset', + source: data, + }); + } + } + return chunk; +} +const workerAssetUrlRE = /__VITE_WORKER_ASSET__([a-z\d]{8})__/g; +function encodeWorkerAssetFileName(fileName, workerCache) { + const { fileNameHash } = workerCache; + const hash = getHash(fileName); + if (!fileNameHash.get(hash)) { + fileNameHash.set(hash, fileName); + } + return `__VITE_WORKER_ASSET__${hash}__`; +} +async function workerFileToUrl(config, id, query) { + const workerMap = workerCache.get(config.mainConfig || config); + let fileName = workerMap.bundle.get(id); + if (!fileName) { + const outputChunk = await bundleWorkerEntry(config, id, query); + fileName = outputChunk.fileName; + saveEmitWorkerAsset(config, { + fileName, + source: outputChunk.code, + type: 'asset', + }); + workerMap.bundle.set(id, fileName); + } + return encodeWorkerAssetFileName(fileName, workerMap); +} +function webWorkerPostPlugin() { + return { + name: 'vite:worker-post', + resolveImportMeta(property, { format }) { + // document is undefined in the worker, so we need to avoid it in iife + if (format === 'iife') { + // compiling import.meta + if (!property) { + // rollup only supports `url` property. we only support `url` property as well. + // https://github.com/rollup/rollup/blob/62b648e1cc6a1f00260bb85aa2050097bb4afd2b/src/ast/nodes/MetaProperty.ts#L164-L173 + return `{ + url: self.location.href + }`; + } + // compiling import.meta.url + if (property === 'url') { + return 'self.location.href'; + } + } + return null; + }, + }; +} +function webWorkerPlugin(config) { + const isBuild = config.command === 'build'; + let server; + const isWorker = config.isWorker; + const isWorkerQueryId = (id) => { + const parsedQuery = parseRequest(id); + if (parsedQuery && + (parsedQuery.worker ?? parsedQuery.sharedworker) != null) { + return true; + } + return false; + }; + return { + name: 'vite:worker', + configureServer(_server) { + server = _server; + }, + buildStart() { + if (isWorker) { + return; + } + workerCache.set(config, { + assets: new Map(), + bundle: new Map(), + fileNameHash: new Map(), + }); + }, + load(id) { + if (isBuild && isWorkerQueryId(id)) { + return ''; + } + }, + shouldTransformCachedModule({ id }) { + if (isBuild && config.build.watch && isWorkerQueryId(id)) { + return true; + } + }, + async transform(raw, id, options) { + const ssr = options?.ssr === true; + const query = parseRequest(id); + if (query && query[WORKER_FILE_ID] != null) { + // if import worker by worker constructor will have query.type + // other type will be import worker by esm + const workerType = query['type']; + let injectEnv = ''; + const scriptPath = JSON.stringify(path$o.posix.join(config.base, ENV_PUBLIC_PATH)); + if (workerType === 'classic') { + injectEnv = `importScripts(${scriptPath})\n`; + } + else if (workerType === 'module') { + injectEnv = `import ${scriptPath}\n`; + } + else if (workerType === 'ignore') { + if (isBuild) { + injectEnv = ''; + } + else if (server) { + // dynamic worker type we can't know how import the env + // so we copy /@vite/env code of server transform result into file header + const { moduleGraph } = server; + const module = moduleGraph.getModuleById(ENV_ENTRY); + injectEnv = module?.transformResult?.code || ''; + } + } + if (injectEnv) { + const s = new MagicString(raw); + s.prepend(injectEnv); + return { + code: s.toString(), + map: s.generateMap({ hires: 'boundary' }), + }; + } + return; + } + if (query == null || + (query && (query.worker ?? query.sharedworker) == null)) { + return; + } + // stringified url or `new URL(...)` + let url; + const { format } = config.worker; + const workerConstructor = query.sharedworker != null ? 'SharedWorker' : 'Worker'; + const workerType = isBuild + ? format === 'es' + ? 'module' + : 'classic' + : 'module'; + const workerTypeOption = `{ + ${workerType === 'module' ? `type: "module",` : ''} + name: options?.name + }`; + if (isBuild) { + getDepsOptimizer(config, ssr)?.registerWorkersSource(id); + if (query.inline != null) { + const chunk = await bundleWorkerEntry(config, id, query); + const encodedJs = `const encodedJs = "${Buffer.from(chunk.code).toString('base64')}";`; + const code = + // Using blob URL for SharedWorker results in multiple instances of a same worker + workerConstructor === 'Worker' + ? `${encodedJs} + const blob = typeof window !== "undefined" && window.Blob && new Blob([${workerType === 'classic' + ? '' + : // `URL` is always available, in `Worker[type="module"]` + `'URL.revokeObjectURL(import.meta.url);'+`}atob(encodedJs)], { type: "text/javascript;charset=utf-8" }); + export default function WorkerWrapper(options) { + let objURL; + try { + objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob); + if (!objURL) throw '' + const worker = new ${workerConstructor}(objURL, ${workerTypeOption}); + worker.addEventListener("error", () => { + (window.URL || window.webkitURL).revokeObjectURL(objURL); + }); + return worker; + } catch(e) { + return new ${workerConstructor}( + "data:application/javascript;base64," + encodedJs, + ${workerTypeOption} + ); + }${ + // For module workers, we should not revoke the URL until the worker runs, + // otherwise the worker fails to run + workerType === 'classic' + ? ` finally { + objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL); + }` + : ''} + }` + : `${encodedJs} + export default function WorkerWrapper(options) { + return new ${workerConstructor}( + "data:application/javascript;base64," + encodedJs, + ${workerTypeOption} + ); + } + `; + return { + code, + // Empty sourcemap to suppress Rollup warning + map: { mappings: '' }, + }; + } + else { + url = await workerFileToUrl(config, id, query); + } + } + else { + url = await fileToUrl$1(cleanUrl(id), config, this); + url = injectQuery(url, WORKER_FILE_ID); + url = injectQuery(url, `type=${workerType}`); + } + if (query.url != null) { + return { + code: `export default ${JSON.stringify(url)}`, + map: { mappings: '' }, // Empty sourcemap to suppress Rollup warning + }; + } + return { + code: `export default function WorkerWrapper(options) { + return new ${workerConstructor}( + ${JSON.stringify(url)}, + ${workerTypeOption} + ); + }`, + map: { mappings: '' }, // Empty sourcemap to suppress Rollup warning + }; + }, + renderChunk(code, chunk, outputOptions) { + let s; + const result = () => { + return (s && { + code: s.toString(), + map: config.build.sourcemap + ? s.generateMap({ hires: 'boundary' }) + : null, + }); + }; + workerAssetUrlRE.lastIndex = 0; + if (workerAssetUrlRE.test(code)) { + const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format, config.isWorker); + let match; + s = new MagicString(code); + workerAssetUrlRE.lastIndex = 0; + // Replace "__VITE_WORKER_ASSET__5aa0ddc0__" using relative paths + const workerMap = workerCache.get(config.mainConfig || config); + const { fileNameHash } = workerMap; + while ((match = workerAssetUrlRE.exec(code))) { + const [full, hash] = match; + const filename = fileNameHash.get(hash); + const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', config, toRelativeRuntime); + const replacementString = typeof replacement === 'string' + ? JSON.stringify(replacement).slice(1, -1) + : `"+${replacement.runtime}+"`; + s.update(match.index, match.index + full.length, replacementString); + } + } + return result(); + }, + generateBundle(opts) { + // @ts-expect-error asset emits are skipped in legacy bundle + if (opts.__vite_skip_asset_emit__ || isWorker) { + return; + } + const workerMap = workerCache.get(config); + workerMap.assets.forEach((asset) => { + this.emitFile(asset); + workerMap.assets.delete(asset.fileName); + }); + }, + }; +} + +const debug$4 = createDebugger('vite:import-analysis'); +const clientDir = normalizePath$3(CLIENT_DIR); +const skipRE = /\.(?:map|json)(?:$|\?)/; +const canSkipImportAnalysis = (id) => skipRE.test(id) || isDirectCSSRequest(id); +const optimizedDepChunkRE$1 = /\/chunk-[A-Z\d]{8}\.js/; +const optimizedDepDynamicRE$1 = /-[A-Z\d]{8}\.js/; +const hasImportInQueryParamsRE = /[?&]import=?\b/; +const hasViteIgnoreRE = /\/\*\s*@vite-ignore\s*\*\//; +const urlIsStringRE = /^(?:'.*'|".*"|`.*`)$/; +const templateLiteralRE = /^\s*`(.*)`\s*$/; +function isExplicitImportRequired(url) { + return !isJSRequest(cleanUrl(url)) && !isCSSRequest(url); +} +function markExplicitImport(url) { + if (isExplicitImportRequired(url)) { + return injectQuery(url, 'import'); + } + return url; +} +function extractImportedBindings(id, source, importSpec, importedBindings) { + let bindings = importedBindings.get(id); + if (!bindings) { + bindings = new Set(); + importedBindings.set(id, bindings); + } + const isDynamic = importSpec.d > -1; + const isMeta = importSpec.d === -2; + if (isDynamic || isMeta) { + // this basically means the module will be impacted by any change in its dep + bindings.add('*'); + return; + } + const exp = source.slice(importSpec.ss, importSpec.se); + const [match0] = findStaticImports(exp); + if (!match0) { + return; + } + const parsed = parseStaticImport(match0); + if (!parsed) { + return; + } + if (parsed.namespacedImport) { + bindings.add('*'); + } + if (parsed.defaultImport) { + bindings.add('default'); + } + if (parsed.namedImports) { + for (const name of Object.keys(parsed.namedImports)) { + bindings.add(name); + } + } +} +/** + * Server-only plugin that lexes, resolves, rewrites and analyzes url imports. + * + * - Imports are resolved to ensure they exist on disk + * + * - Lexes HMR accept calls and updates import relationships in the module graph + * + * - Bare module imports are resolved (by @rollup-plugin/node-resolve) to + * absolute file paths, e.g. + * + * ```js + * import 'foo' + * ``` + * is rewritten to + * ```js + * import '/@fs//project/node_modules/foo/dist/foo.js' + * ``` + * + * - CSS imports are appended with `.js` since both the js module and the actual + * css (referenced via ``) may go through the transform pipeline: + * + * ```js + * import './style.css' + * ``` + * is rewritten to + * ```js + * import './style.css.js' + * ``` + */ +function importAnalysisPlugin(config) { + const { root, base } = config; + const fsUtils = getFsUtils(config); + const clientPublicPath = path$o.posix.join(base, CLIENT_PUBLIC_PATH); + const enablePartialAccept = config.experimental?.hmrPartialAccept; + let server; + let _env; + let _ssrEnv; + function getEnv(ssr) { + if (!_ssrEnv || !_env) { + const importMetaEnvKeys = {}; + const userDefineEnv = {}; + for (const key in config.env) { + importMetaEnvKeys[key] = JSON.stringify(config.env[key]); + } + for (const key in config.define) { + // non-import.meta.env.* is handled in `clientInjection` plugin + if (key.startsWith('import.meta.env.')) { + userDefineEnv[key.slice(16)] = config.define[key]; + } + } + const env = `import.meta.env = ${serializeDefine({ + ...importMetaEnvKeys, + SSR: '__vite_ssr__', + ...userDefineEnv, + })};`; + _ssrEnv = env.replace('__vite_ssr__', 'true'); + _env = env.replace('__vite_ssr__', 'false'); + } + return ssr ? _ssrEnv : _env; + } + return { + name: 'vite:import-analysis', + configureServer(_server) { + server = _server; + }, + async transform(source, importer, options) { + // In a real app `server` is always defined, but it is undefined when + // running src/node/server/__tests__/pluginContainer.spec.ts + if (!server) { + return null; + } + const ssr = options?.ssr === true; + if (canSkipImportAnalysis(importer)) { + debug$4?.(colors$1.dim(`[skipped] ${prettifyUrl(importer, root)}`)); + return null; + } + const start = performance.now(); + await init; + let imports; + let exports; + source = stripBomTag(source); + try { + [imports, exports] = parse$e(source); + } + catch (_e) { + const e = _e; + const { message, showCodeFrame } = createParseErrorInfo(importer, source); + this.error(message, showCodeFrame ? e.idx : undefined); + } + const depsOptimizer = getDepsOptimizer(config, ssr); + const { moduleGraph } = server; + // since we are already in the transform phase of the importer, it must + // have been loaded so its entry is guaranteed in the module graph. + const importerModule = moduleGraph.getModuleById(importer); + if (!importerModule) { + // This request is no longer valid. It could happen for optimized deps + // requests. A full reload is going to request this id again. + // Throwing an outdated error so we properly finish the request with a + // 504 sent to the browser. + throwOutdatedRequest(importer); + } + if (!imports.length && !this._addedImports) { + importerModule.isSelfAccepting = false; + debug$4?.(`${timeFrom(start)} ${colors$1.dim(`[no imports] ${prettifyUrl(importer, root)}`)}`); + return source; + } + let hasHMR = false; + let isSelfAccepting = false; + let hasEnv = false; + let needQueryInjectHelper = false; + let s; + const str = () => s || (s = new MagicString(source)); + let isPartiallySelfAccepting = false; + const importedBindings = enablePartialAccept + ? new Map() + : null; + const toAbsoluteUrl = (url) => path$o.posix.resolve(path$o.posix.dirname(importerModule.url), url); + const normalizeUrl = async (url, pos, forceSkipImportAnalysis = false) => { + url = stripBase(url, base); + let importerFile = importer; + const optimizeDeps = getDepOptimizationConfig(config, ssr); + if (moduleListContains(optimizeDeps?.exclude, url)) { + if (depsOptimizer) { + await depsOptimizer.scanProcessing; + // if the dependency encountered in the optimized file was excluded from the optimization + // the dependency needs to be resolved starting from the original source location of the optimized file + // because starting from node_modules/.vite will not find the dependency if it was not hoisted + // (that is, if it is under node_modules directory in the package source of the optimized file) + for (const optimizedModule of depsOptimizer.metadata.depInfoList) { + if (!optimizedModule.src) + continue; // Ignore chunks + if (optimizedModule.file === importerModule.file) { + importerFile = optimizedModule.src; + } + } + } + } + const resolved = await this.resolve(url, importerFile); + if (!resolved || resolved.meta?.['vite:alias']?.noResolved) { + // in ssr, we should let node handle the missing modules + if (ssr) { + return [url, url]; + } + // fix#9534, prevent the importerModuleNode being stopped from propagating updates + importerModule.isSelfAccepting = false; + return this.error(`Failed to resolve import "${url}" from "${path$o.relative(process.cwd(), importerFile)}". Does the file exist?`, pos); + } + if (isExternalUrl(resolved.id)) { + return [resolved.id, resolved.id]; + } + const isRelative = url[0] === '.'; + const isSelfImport = !isRelative && cleanUrl(url) === cleanUrl(importer); + // normalize all imports into resolved URLs + // e.g. `import 'foo'` -> `import '/@fs/.../node_modules/foo/index.js'` + if (resolved.id.startsWith(withTrailingSlash(root))) { + // in root: infer short absolute path from root + url = resolved.id.slice(root.length); + } + else if (depsOptimizer?.isOptimizedDepFile(resolved.id) || + // vite-plugin-react isn't following the leading \0 virtual module convention. + // This is a temporary hack to avoid expensive fs checks for React apps. + // We'll remove this as soon we're able to fix the react plugins. + (resolved.id !== '/@react-refresh' && + path$o.isAbsolute(resolved.id) && + fsUtils.existsSync(cleanUrl(resolved.id)))) { + // an optimized deps may not yet exists in the filesystem, or + // a regular file exists but is out of root: rewrite to absolute /@fs/ paths + url = path$o.posix.join(FS_PREFIX, resolved.id); + } + else { + url = resolved.id; + } + // if the resolved id is not a valid browser import specifier, + // prefix it to make it valid. We will strip this before feeding it + // back into the transform pipeline + if (url[0] !== '.' && url[0] !== '/') { + url = wrapId(resolved.id); + } + // make the URL browser-valid if not SSR + if (!ssr) { + // mark non-js/css imports with `?import` + url = markExplicitImport(url); + // If the url isn't a request for a pre-bundled common chunk, + // for relative js/css imports, or self-module virtual imports + // (e.g. vue blocks), inherit importer's version query + // do not do this for unknown type imports, otherwise the appended + // query can break 3rd party plugin's extension checks. + if ((isRelative || isSelfImport) && + !hasImportInQueryParamsRE.test(url) && + !DEP_VERSION_RE.test(url)) { + const versionMatch = importer.match(DEP_VERSION_RE); + if (versionMatch) { + url = injectQuery(url, versionMatch[1]); + } + } + // check if the dep has been hmr updated. If yes, we need to attach + // its last updated timestamp to force the browser to fetch the most + // up-to-date version of this module. + try { + // delay setting `isSelfAccepting` until the file is actually used (#7870) + // We use an internal function to avoid resolving the url again + const depModule = await moduleGraph._ensureEntryFromUrl(unwrapId(url), ssr, canSkipImportAnalysis(url) || forceSkipImportAnalysis, resolved); + if (depModule.lastHMRTimestamp > 0) { + url = injectQuery(url, `t=${depModule.lastHMRTimestamp}`); + } + } + catch (e) { + // it's possible that the dep fails to resolve (non-existent import) + // attach location to the missing import + e.pos = pos; + throw e; + } + // prepend base + url = joinUrlSegments(base, url); + } + return [url, resolved.id]; + }; + const orderedImportedUrls = new Array(imports.length); + const orderedAcceptedUrls = new Array(imports.length); + const orderedAcceptedExports = new Array(imports.length); + await Promise.all(imports.map(async (importSpecifier, index) => { + const { s: start, e: end, ss: expStart, se: expEnd, d: dynamicIndex, a: attributeIndex, } = importSpecifier; + // #2083 User may use escape path, + // so use imports[index].n to get the unescaped string + let specifier = importSpecifier.n; + const rawUrl = source.slice(start, end); + // check import.meta usage + if (rawUrl === 'import.meta') { + const prop = source.slice(end, end + 4); + if (prop === '.hot') { + hasHMR = true; + const endHot = end + 4 + (source[end + 4] === '?' ? 1 : 0); + if (source.slice(endHot, endHot + 7) === '.accept') { + // further analyze accepted modules + if (source.slice(endHot, endHot + 14) === '.acceptExports') { + const importAcceptedExports = (orderedAcceptedExports[index] = + new Set()); + lexAcceptedHmrExports(source, source.indexOf('(', endHot + 14) + 1, importAcceptedExports); + isPartiallySelfAccepting = true; + } + else { + const importAcceptedUrls = (orderedAcceptedUrls[index] = + new Set()); + if (lexAcceptedHmrDeps(source, source.indexOf('(', endHot + 7) + 1, importAcceptedUrls)) { + isSelfAccepting = true; + } + } + } + } + else if (prop === '.env') { + hasEnv = true; + } + return; + } + else if (templateLiteralRE.test(rawUrl)) { + // If the import has backticks but isn't transformed as a glob import + // (as there's nothing to glob), check if it's simply a plain string. + // If so, we can replace the specifier as a plain string to prevent + // an incorrect "cannot be analyzed" warning. + if (!(rawUrl.includes('${') && rawUrl.includes('}'))) { + specifier = rawUrl.replace(templateLiteralRE, '$1'); + } + } + const isDynamicImport = dynamicIndex > -1; + // strip import attributes as we can process them ourselves + if (!isDynamicImport && attributeIndex > -1) { + str().remove(end + 1, expEnd); + } + // static import or valid string in dynamic import + // If resolvable, let's resolve it + if (specifier) { + // skip external / data uri + if (isExternalUrl(specifier) || isDataUrl(specifier)) { + return; + } + // skip ssr external + if (ssr) { + if (shouldExternalizeForSSR(specifier, importer, config)) { + return; + } + if (isBuiltin(specifier)) { + return; + } + } + // skip client + if (specifier === clientPublicPath) { + return; + } + // warn imports to non-asset /public files + if (specifier[0] === '/' && + !(config.assetsInclude(cleanUrl(specifier)) || + urlRE.test(specifier)) && + checkPublicFile(specifier, config)) { + throw new Error(`Cannot import non-asset file ${specifier} which is inside /public. ` + + `JS/CSS files inside /public are copied as-is on build and ` + + `can only be referenced via