diff --git a/main.js b/main.js index e6a7361..aadca6c 100644 --- a/main.js +++ b/main.js @@ -3,7 +3,7 @@ import store from './store/' // const baseURL = 'http://localhost:7010' const baseURL = 'http://81.69.47.31:7010' -//const baseURL = 'http://veqf45.natappfree.cc' +// const baseURL = 'http://veqf45.natappfree.cc' Vue.prototype.baseURL = baseURL; diff --git a/node_modules/@vue/devtools-api/lib/cjs/api/index.js b/node_modules/@vue/devtools-api/lib/cjs/api/index.js index fcdfd58..22f7589 100644 --- a/node_modules/@vue/devtools-api/lib/cjs/api/index.js +++ b/node_modules/@vue/devtools-api/lib/cjs/api/index.js @@ -14,9 +14,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(require("./api"), exports); -__exportStar(require("./app"), exports); -__exportStar(require("./component"), exports); -__exportStar(require("./context"), exports); -__exportStar(require("./hooks"), exports); -__exportStar(require("./util"), exports); +__exportStar(require("./api.js"), exports); +__exportStar(require("./app.js"), exports); +__exportStar(require("./component.js"), exports); +__exportStar(require("./context.js"), exports); +__exportStar(require("./hooks.js"), exports); +__exportStar(require("./util.js"), exports); diff --git a/node_modules/@vue/devtools-api/lib/cjs/index.js b/node_modules/@vue/devtools-api/lib/cjs/index.js index ad9765a..249ac4d 100644 --- a/node_modules/@vue/devtools-api/lib/cjs/index.js +++ b/node_modules/@vue/devtools-api/lib/cjs/index.js @@ -15,22 +15,22 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.setupDevtoolsPlugin = void 0; -const env_1 = require("./env"); -const const_1 = require("./const"); -const proxy_1 = require("./proxy"); -__exportStar(require("./api"), exports); -__exportStar(require("./plugin"), exports); -__exportStar(require("./time"), exports); +const env_js_1 = require("./env.js"); +const const_js_1 = require("./const.js"); +const proxy_js_1 = require("./proxy.js"); +__exportStar(require("./api/index.js"), exports); +__exportStar(require("./plugin.js"), exports); +__exportStar(require("./time.js"), exports); function setupDevtoolsPlugin(pluginDescriptor, setupFn) { const descriptor = pluginDescriptor; - const target = (0, env_1.getTarget)(); - const hook = (0, env_1.getDevtoolsGlobalHook)(); - const enableProxy = env_1.isProxyAvailable && descriptor.enableEarlyProxy; + const target = (0, env_js_1.getTarget)(); + const hook = (0, env_js_1.getDevtoolsGlobalHook)(); + const enableProxy = env_js_1.isProxyAvailable && descriptor.enableEarlyProxy; if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) { - hook.emit(const_1.HOOK_SETUP, pluginDescriptor, setupFn); + hook.emit(const_js_1.HOOK_SETUP, pluginDescriptor, setupFn); } else { - const proxy = enableProxy ? new proxy_1.ApiProxy(descriptor, hook) : null; + const proxy = enableProxy ? new proxy_js_1.ApiProxy(descriptor, hook) : null; const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || []; list.push({ pluginDescriptor: descriptor, diff --git a/node_modules/@vue/devtools-api/lib/cjs/proxy.js b/node_modules/@vue/devtools-api/lib/cjs/proxy.js index 2cc792e..5385e60 100644 --- a/node_modules/@vue/devtools-api/lib/cjs/proxy.js +++ b/node_modules/@vue/devtools-api/lib/cjs/proxy.js @@ -1,8 +1,8 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ApiProxy = void 0; -const const_1 = require("./const"); -const time_1 = require("./time"); +const const_js_1 = require("./const.js"); +const time_js_1 = require("./time.js"); class ApiProxy { constructor(plugin, hook) { this.target = null; @@ -41,11 +41,11 @@ class ApiProxy { currentSettings = value; }, now() { - return (0, time_1.now)(); + return (0, time_js_1.now)(); }, }; if (hook) { - hook.on(const_1.HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => { + hook.on(const_js_1.HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => { if (pluginId === this.plugin.id) { this.fallbacks.setSettings(value); } diff --git a/node_modules/@vue/devtools-api/lib/esm/api/api.d.ts b/node_modules/@vue/devtools-api/lib/esm/api/api.d.ts index 25bd777..071312a 100644 --- a/node_modules/@vue/devtools-api/lib/esm/api/api.d.ts +++ b/node_modules/@vue/devtools-api/lib/esm/api/api.d.ts @@ -1,8 +1,8 @@ -import { ComponentBounds, Hookable } from './hooks'; -import { Context } from './context'; -import { ComponentInstance, ComponentState, StateBase } from './component'; -import { App } from './app'; -import { ID } from './util'; +import type { ComponentBounds, Hookable } from './hooks.js'; +import type { Context } from './context.js'; +import type { ComponentInstance, ComponentState, StateBase } from './component.js'; +import type { App } from './app.js'; +import type { ID } from './util.js'; export interface DevtoolsPluginApi { on: Hookable; notifyComponentUpdate(instance?: ComponentInstance): void; diff --git a/node_modules/@vue/devtools-api/lib/esm/api/component.d.ts b/node_modules/@vue/devtools-api/lib/esm/api/component.d.ts index ae8d545..335dd04 100644 --- a/node_modules/@vue/devtools-api/lib/esm/api/component.d.ts +++ b/node_modules/@vue/devtools-api/lib/esm/api/component.d.ts @@ -1,5 +1,5 @@ -import { InspectorNodeTag } from './api'; -import { ID } from './util'; +import type { InspectorNodeTag } from './api.js'; +import type { ID } from './util.js'; export declare type ComponentInstance = any; export interface ComponentTreeNode { uid: ID; @@ -15,6 +15,7 @@ export interface ComponentTreeNode { isRouterView?: boolean; macthedRouteSegment?: string; tags: InspectorNodeTag[]; + autoOpen: boolean; meta?: any; } export interface InspectedComponentData { diff --git a/node_modules/@vue/devtools-api/lib/esm/api/context.d.ts b/node_modules/@vue/devtools-api/lib/esm/api/context.d.ts index 7567403..29388f1 100644 --- a/node_modules/@vue/devtools-api/lib/esm/api/context.d.ts +++ b/node_modules/@vue/devtools-api/lib/esm/api/context.d.ts @@ -1,4 +1,4 @@ -import { AppRecord } from './api'; +import type { AppRecord } from './api.js'; export interface Context { currentTab: string; currentAppRecord: AppRecord; diff --git a/node_modules/@vue/devtools-api/lib/esm/api/hooks.d.ts b/node_modules/@vue/devtools-api/lib/esm/api/hooks.d.ts index 8331d89..c980b13 100644 --- a/node_modules/@vue/devtools-api/lib/esm/api/hooks.d.ts +++ b/node_modules/@vue/devtools-api/lib/esm/api/hooks.d.ts @@ -1,6 +1,6 @@ -import { ComponentTreeNode, InspectedComponentData, ComponentInstance, ComponentDevtoolsOptions } from './component'; -import { App } from './app'; -import { CustomInspectorNode, CustomInspectorState, TimelineEvent } from './api'; +import type { ComponentTreeNode, InspectedComponentData, ComponentInstance, ComponentDevtoolsOptions } from './component.js'; +import type { App } from './app.js'; +import type { CustomInspectorNode, CustomInspectorState, TimelineEvent } from './api.js'; export declare const enum Hooks { TRANSFORM_CALL = "transformCall", GET_APP_RECORD_NAME = "getAppRecordName", @@ -53,6 +53,7 @@ export declare type HookPayloads = { componentTreeData: ComponentTreeNode[]; maxDepth: number; filter: string; + recursively: boolean; }; [Hooks.VISIT_COMPONENT_TREE]: { app: App; diff --git a/node_modules/@vue/devtools-api/lib/esm/api/index.d.ts b/node_modules/@vue/devtools-api/lib/esm/api/index.d.ts index 5b68179..70d09d2 100644 --- a/node_modules/@vue/devtools-api/lib/esm/api/index.d.ts +++ b/node_modules/@vue/devtools-api/lib/esm/api/index.d.ts @@ -1,6 +1,6 @@ -export * from './api'; -export * from './app'; -export * from './component'; -export * from './context'; -export * from './hooks'; -export * from './util'; +export * from './api.js'; +export * from './app.js'; +export * from './component.js'; +export * from './context.js'; +export * from './hooks.js'; +export * from './util.js'; diff --git a/node_modules/@vue/devtools-api/lib/esm/api/index.js b/node_modules/@vue/devtools-api/lib/esm/api/index.js index 5b68179..70d09d2 100644 --- a/node_modules/@vue/devtools-api/lib/esm/api/index.js +++ b/node_modules/@vue/devtools-api/lib/esm/api/index.js @@ -1,6 +1,6 @@ -export * from './api'; -export * from './app'; -export * from './component'; -export * from './context'; -export * from './hooks'; -export * from './util'; +export * from './api.js'; +export * from './app.js'; +export * from './component.js'; +export * from './context.js'; +export * from './hooks.js'; +export * from './util.js'; diff --git a/node_modules/@vue/devtools-api/lib/esm/env.d.ts b/node_modules/@vue/devtools-api/lib/esm/env.d.ts index 1da7ca9..16c1399 100644 --- a/node_modules/@vue/devtools-api/lib/esm/env.d.ts +++ b/node_modules/@vue/devtools-api/lib/esm/env.d.ts @@ -1,5 +1,5 @@ -import { PluginDescriptor, SetupFunction } from '.'; -import { ApiProxy } from './proxy'; +import type { PluginDescriptor, SetupFunction } from './index.js'; +import type { ApiProxy } from './proxy.js'; export interface PluginQueueItem { pluginDescriptor: PluginDescriptor; setupFn: SetupFunction; diff --git a/node_modules/@vue/devtools-api/lib/esm/index.d.ts b/node_modules/@vue/devtools-api/lib/esm/index.d.ts index 2f39b55..6833324 100644 --- a/node_modules/@vue/devtools-api/lib/esm/index.d.ts +++ b/node_modules/@vue/devtools-api/lib/esm/index.d.ts @@ -1,9 +1,9 @@ -import { DevtoolsPluginApi } from './api'; -import { PluginDescriptor, ExtractSettingsTypes, PluginSettingsItem } from './plugin'; -export * from './api'; -export * from './plugin'; -export * from './time'; -export { PluginQueueItem } from './env'; +import type { DevtoolsPluginApi } from './api/index.js'; +import type { PluginDescriptor, ExtractSettingsTypes, PluginSettingsItem } from './plugin.js'; +export * from './api/index.js'; +export * from './plugin.js'; +export * from './time.js'; +export { PluginQueueItem } from './env.js'; declare type Cast = A extends B ? A : B; declare type Narrowable = string | number | bigint | boolean; declare type Narrow = Cast", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/call-bind/issues" + }, + "homepage": "https://github.com/ljharb/call-bind#readme", + "devDependencies": { + "@ljharb/eslint-config": "^17.3.0", + "aud": "^1.1.3", + "auto-changelog": "^2.2.1", + "eslint": "^7.17.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.1.1" + }, + "dependencies": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } } diff --git a/node_modules/follow-redirects/index.js b/node_modules/follow-redirects/index.js index 252c9bf..3e199c1 100644 --- a/node_modules/follow-redirects/index.js +++ b/node_modules/follow-redirects/index.js @@ -15,6 +15,11 @@ events.forEach(function (event) { }; }); +var InvalidUrlError = createErrorType( + "ERR_INVALID_URL", + "Invalid URL", + TypeError +); // Error types with codes var RedirectionError = createErrorType( "ERR_FR_REDIRECTION_FAILURE", @@ -75,10 +80,10 @@ RedirectableRequest.prototype.write = function (data, encoding, callback) { } // Validate input and shift parameters if necessary - if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { + if (!isString(data) && !isBuffer(data)) { throw new TypeError("data should be a string, Buffer or Uint8Array"); } - if (typeof encoding === "function") { + if (isFunction(encoding)) { callback = encoding; encoding = null; } @@ -107,11 +112,11 @@ RedirectableRequest.prototype.write = function (data, encoding, callback) { // Ends the current native request RedirectableRequest.prototype.end = function (data, encoding, callback) { // Shift parameters if necessary - if (typeof data === "function") { + if (isFunction(data)) { callback = data; data = encoding = null; } - else if (typeof encoding === "function") { + else if (isFunction(encoding)) { callback = encoding; encoding = null; } @@ -274,21 +279,26 @@ RedirectableRequest.prototype._performRequest = function () { this._options.agent = this._options.agents[scheme]; } - // Create the native request + // Create the native request and set up its event handlers 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]]); + for (var event of events) { + request.on(event, eventHandlers[event]); } + // RFC7230§5.3.1: When making a request directly to an origin server, […] + // a client MUST send only the absolute path […] as the request-target. + this._currentUrl = /^\//.test(this._options.path) ? + url.format(this._options) : + // When making a request to a proxy, […] + // a client MUST send the target URI in absolute-form […]. + this._options.path; + // End a redirected request // (The first request must be ended explicitly with RedirectableRequest#end) if (this._isRedirect) { - // Write the request entity and end. + // Write the request entity and end var i = 0; var self = this; var buffers = this._requestBodyBuffers; @@ -404,7 +414,7 @@ RedirectableRequest.prototype._processResponse = function (response) { redirectUrl = url.resolve(currentUrl, location); } catch (cause) { - this.emit("error", new RedirectionError(cause)); + this.emit("error", new RedirectionError({ cause: cause })); return; } @@ -424,7 +434,7 @@ RedirectableRequest.prototype._processResponse = function (response) { } // Evaluate the beforeRedirect callback - if (typeof beforeRedirect === "function") { + if (isFunction(beforeRedirect)) { var responseDetails = { headers: response.headers, statusCode: statusCode, @@ -449,7 +459,7 @@ RedirectableRequest.prototype._processResponse = function (response) { this._performRequest(); } catch (cause) { - this.emit("error", new RedirectionError(cause)); + this.emit("error", new RedirectionError({ cause: cause })); } }; @@ -471,15 +481,19 @@ function wrap(protocols) { // Executes a request, following redirects function request(input, options, callback) { // Parse parameters - if (typeof input === "string") { - var urlStr = input; + if (isString(input)) { + var parsed; try { - input = urlToOptions(new URL(urlStr)); + parsed = urlToOptions(new URL(input)); } catch (err) { /* istanbul ignore next */ - input = url.parse(urlStr); + parsed = url.parse(input); + } + if (!isString(parsed.protocol)) { + throw new InvalidUrlError({ input }); } + input = parsed; } else if (URL && (input instanceof URL)) { input = urlToOptions(input); @@ -489,7 +503,7 @@ function wrap(protocols) { options = input; input = { protocol: protocol }; } - if (typeof options === "function") { + if (isFunction(options)) { callback = options; options = null; } @@ -500,6 +514,9 @@ function wrap(protocols) { maxBodyLength: exports.maxBodyLength, }, input, options); options.nativeProtocols = nativeProtocols; + if (!isString(options.host) && !isString(options.hostname)) { + options.hostname = "::1"; + } assert.equal(options.protocol, protocol, "protocol mismatch"); debug("options", options); @@ -557,37 +574,48 @@ function removeMatchingHeaders(regex, headers) { undefined : String(lastValue).trim(); } -function createErrorType(code, defaultMessage) { - function CustomError(cause) { +function createErrorType(code, message, baseClass) { + // Create constructor + function CustomError(properties) { Error.captureStackTrace(this, this.constructor); - if (!cause) { - this.message = defaultMessage; - } - else { - this.message = defaultMessage + ": " + cause.message; - this.cause = cause; - } + Object.assign(this, properties || {}); + this.code = code; + this.message = this.cause ? message + ": " + this.cause.message : message; } - CustomError.prototype = new Error(); + + // Attach constructor and set default properties + CustomError.prototype = new (baseClass || 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]]); + for (var event of events) { + request.removeListener(event, eventHandlers[event]); } request.on("error", noop); request.abort(); } function isSubdomain(subdomain, domain) { - const dot = subdomain.length - domain.length - 1; + assert(isString(subdomain) && isString(domain)); + var dot = subdomain.length - domain.length - 1; return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); } +function isString(value) { + return typeof value === "string" || value instanceof String; +} + +function isFunction(value) { + return typeof value === "function"; +} + +function isBuffer(value) { + return typeof value === "object" && ("length" in value); +} + // Exports module.exports = wrap({ http: http, https: https }); module.exports.wrap = wrap; diff --git a/node_modules/follow-redirects/package.json b/node_modules/follow-redirects/package.json index a6ae2a0..97717c5 100644 --- a/node_modules/follow-redirects/package.json +++ b/node_modules/follow-redirects/package.json @@ -1,70 +1,28 @@ { - "_from": "follow-redirects@^1.14.8", - "_id": "follow-redirects@1.15.0", - "_inBundle": false, - "_integrity": "sha512-aExlJShTV4qOUOL7yF1U5tvLCB0xQuudbf6toyYA0E/acBNw71mvjFTnLaRp50aQaYocMR0a/RMMBIHeZnGyjQ==", - "_location": "/follow-redirects", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "follow-redirects@^1.14.8", - "name": "follow-redirects", - "escapedName": "follow-redirects", - "rawSpec": "^1.14.8", - "saveSpec": null, - "fetchSpec": "^1.14.8" - }, - "_requiredBy": [ - "/axios" - ], - "_resolved": "https://registry.npmmirror.com/follow-redirects/-/follow-redirects-1.15.0.tgz", - "_shasum": "06441868281c86d0dda4ad8bdaead2d02dca89d4", - "_spec": "follow-redirects@^1.14.8", - "_where": "D:\\workbench\\personal\\bnyer-cloud-tiktok\\node_modules\\axios", - "author": { - "name": "Ruben Verborgh", - "email": "ruben@verborgh.org", - "url": "https://ruben.verborgh.org/" - }, - "bugs": { - "url": "https://github.com/follow-redirects/follow-redirects/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Olivier Lalonde", - "email": "olalonde@gmail.com", - "url": "http://www.syskall.com" - }, - { - "name": "James Talmage", - "email": "james@talmage.io" - } - ], - "deprecated": false, + "name": "follow-redirects", + "version": "1.15.2", "description": "HTTP and HTTPS modules that follow redirects.", - "devDependencies": { - "concat-stream": "^2.0.0", - "eslint": "^5.16.0", - "express": "^4.16.4", - "lolex": "^3.1.0", - "mocha": "^6.0.2", - "nyc": "^14.1.1" - }, - "engines": { - "node": ">=4.0" - }, + "license": "MIT", + "main": "index.js", "files": [ "*.js" ], - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/RubenVerborgh" - } - ], + "engines": { + "node": ">=4.0" + }, + "scripts": { + "test": "npm run lint && npm run mocha", + "lint": "eslint *.js test", + "mocha": "nyc mocha" + }, + "repository": { + "type": "git", + "url": "git@github.com:follow-redirects/follow-redirects.git" + }, "homepage": "https://github.com/follow-redirects/follow-redirects", + "bugs": { + "url": "https://github.com/follow-redirects/follow-redirects/issues" + }, "keywords": [ "http", "https", @@ -74,22 +32,28 @@ "location", "utility" ], - "license": "MIT", - "main": "index.js", - "name": "follow-redirects", + "author": "Ruben Verborgh (https://ruben.verborgh.org/)", + "contributors": [ + "Olivier Lalonde (http://www.syskall.com)", + "James Talmage " + ], + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], "peerDependenciesMeta": { "debug": { "optional": true } }, - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/follow-redirects/follow-redirects.git" - }, - "scripts": { - "lint": "eslint *.js test", - "mocha": "nyc mocha", - "test": "npm run lint && npm run mocha" - }, - "version": "1.15.0" + "devDependencies": { + "concat-stream": "^2.0.0", + "eslint": "^5.16.0", + "express": "^4.16.4", + "lolex": "^3.1.0", + "mocha": "^6.0.2", + "nyc": "^14.1.1" + } } diff --git a/node_modules/function-bind/package.json b/node_modules/function-bind/package.json index 5e67181..20a1727 100644 --- a/node_modules/function-bind/package.json +++ b/node_modules/function-bind/package.json @@ -1,38 +1,17 @@ { - "_from": "function-bind@^1.1.1", - "_id": "function-bind@1.1.1", - "_inBundle": false, - "_integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "_location": "/function-bind", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "function-bind@^1.1.1", - "name": "function-bind", - "escapedName": "function-bind", - "rawSpec": "^1.1.1", - "saveSpec": null, - "fetchSpec": "^1.1.1" - }, - "_requiredBy": [ - "/call-bind", - "/get-intrinsic", - "/has" + "name": "function-bind", + "version": "1.1.1", + "description": "Implementation of Function.prototype.bind", + "keywords": [ + "function", + "bind", + "shim", + "es5" ], - "_resolved": "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.1.tgz", - "_shasum": "a56899d3ea3c9bab874bb9773b7c5ede92f4895d", - "_spec": "function-bind@^1.1.1", - "_where": "D:\\workbench\\personal\\bnyer-cloud-tiktok\\node_modules\\call-bind", - "author": { - "name": "Raynos", - "email": "raynos2@gmail.com" - }, - "bugs": { - "url": "https://github.com/Raynos/function-bind/issues", - "email": "raynos2@gmail.com" - }, - "bundleDependencies": false, + "author": "Raynos ", + "repository": "git://github.com/Raynos/function-bind.git", + "main": "index", + "homepage": "https://github.com/Raynos/function-bind", "contributors": [ { "name": "Raynos" @@ -42,9 +21,11 @@ "url": "https://github.com/ljharb" } ], + "bugs": { + "url": "https://github.com/Raynos/function-bind/issues", + "email": "raynos2@gmail.com" + }, "dependencies": {}, - "deprecated": false, - "description": "Implementation of Function.prototype.bind", "devDependencies": { "@ljharb/eslint-config": "^12.2.1", "covert": "^1.1.0", @@ -52,29 +33,16 @@ "jscs": "^3.0.7", "tape": "^4.8.0" }, - "homepage": "https://github.com/Raynos/function-bind", - "keywords": [ - "function", - "bind", - "shim", - "es5" - ], "license": "MIT", - "main": "index", - "name": "function-bind", - "repository": { - "type": "git", - "url": "git://github.com/Raynos/function-bind.git" - }, "scripts": { - "coverage": "covert test/*.js", - "eslint": "eslint *.js */*.js", - "jscs": "jscs *.js */*.js", - "lint": "npm run jscs && npm run eslint", - "posttest": "npm run coverage -- --quiet", "pretest": "npm run lint", "test": "npm run tests-only", - "tests-only": "node test" + "posttest": "npm run coverage -- --quiet", + "tests-only": "node test", + "coverage": "covert test/*.js", + "lint": "npm run jscs && npm run eslint", + "jscs": "jscs *.js */*.js", + "eslint": "eslint *.js */*.js" }, "testling": { "files": "test/index.js", @@ -91,6 +59,5 @@ "iphone/6.0..latest", "android-browser/4.2..latest" ] - }, - "version": "1.1.1" + } } diff --git a/node_modules/get-intrinsic/.eslintignore b/node_modules/get-intrinsic/.eslintignore deleted file mode 100644 index 404abb2..0000000 --- a/node_modules/get-intrinsic/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -coverage/ diff --git a/node_modules/get-intrinsic/.eslintrc b/node_modules/get-intrinsic/.eslintrc index d04e483..0ab0876 100644 --- a/node_modules/get-intrinsic/.eslintrc +++ b/node_modules/get-intrinsic/.eslintrc @@ -8,26 +8,21 @@ "es2017": true, "es2020": true, "es2021": true, - }, - - "globals": { - "AggregateError": false, + "es2022": true, }, "rules": { "array-bracket-newline": 0, - "array-element-newline": 0, "complexity": 0, "eqeqeq": [2, "allow-null"], "func-name-matching": 0, "id-length": 0, - "max-lines-per-function": [2, 80], + "max-lines-per-function": [2, 90], "max-params": [2, 4], "max-statements": 0, "max-statements-per-line": [2, { "max": 2 }], "multiline-comment-style": 0, "no-magic-numbers": 0, - "operator-linebreak": [2, "before"], "sort-keys": 0, }, @@ -35,7 +30,6 @@ { "files": "test/**", "rules": { - "max-lines-per-function": 0, "new-cap": 0, }, }, diff --git a/node_modules/get-intrinsic/.nycrc b/node_modules/get-intrinsic/.nycrc index 1826526..bdd626c 100644 --- a/node_modules/get-intrinsic/.nycrc +++ b/node_modules/get-intrinsic/.nycrc @@ -2,10 +2,6 @@ "all": true, "check-coverage": false, "reporter": ["text-summary", "text", "html", "json"], - "lines": 86, - "statements": 85.93, - "functions": 82.43, - "branches": 76.06, "exclude": [ "coverage", "test" diff --git a/node_modules/get-intrinsic/CHANGELOG.md b/node_modules/get-intrinsic/CHANGELOG.md index 32502ec..1bb52d3 100644 --- a/node_modules/get-intrinsic/CHANGELOG.md +++ b/node_modules/get-intrinsic/CHANGELOG.md @@ -5,6 +5,40 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [v1.1.3](https://github.com/ljharb/get-intrinsic/compare/v1.1.2...v1.1.3) - 2022-09-12 + +### Commits + +- [Dev Deps] update `es-abstract`, `es-value-fixtures`, `tape` [`07ff291`](https://github.com/ljharb/get-intrinsic/commit/07ff291816406ebe5a12d7f16965bde0942dd688) +- [Fix] properly check for % signs [`50ac176`](https://github.com/ljharb/get-intrinsic/commit/50ac1760fe99c227e64eabde76e9c0e44cd881b5) + +## [v1.1.2](https://github.com/ljharb/get-intrinsic/compare/v1.1.1...v1.1.2) - 2022-06-08 + +### Fixed + +- [Fix] properly validate against extra % signs [`#16`](https://github.com/ljharb/get-intrinsic/issues/16) + +### Commits + +- [actions] reuse common workflows [`0972547`](https://github.com/ljharb/get-intrinsic/commit/0972547efd0abc863fe4c445a6ca7eb4f8c6901d) +- [meta] use `npmignore` to autogenerate an npmignore file [`5ba0b51`](https://github.com/ljharb/get-intrinsic/commit/5ba0b51d8d8d4f1c31d426d74abc0770fd106bad) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`c364492`](https://github.com/ljharb/get-intrinsic/commit/c364492af4af51333e6f81c0bf21fd3d602c3661) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `es-abstract`, `object-inspect`, `tape` [`dc04dad`](https://github.com/ljharb/get-intrinsic/commit/dc04dad86f6e5608775a2640cb0db5927ae29ed9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `es-abstract`, `object-inspect`, `safe-publish-latest`, `tape` [`1c14059`](https://github.com/ljharb/get-intrinsic/commit/1c1405984e86dd2dc9366c15d8a0294a96a146a5) +- [Tests] use `mock-property` [`b396ef0`](https://github.com/ljharb/get-intrinsic/commit/b396ef05bb73b1d699811abd64b0d9b97997fdda) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `object-inspect`, `tape` [`c2c758d`](https://github.com/ljharb/get-intrinsic/commit/c2c758d3b90af4fef0a76910d8d3c292ec8d1d3e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`29e3c09`](https://github.com/ljharb/get-intrinsic/commit/29e3c091c2bf3e17099969847e8729d0e46896de) +- [actions] update codecov uploader [`8cbc141`](https://github.com/ljharb/get-intrinsic/commit/8cbc1418940d7a8941f3a7985cbc4ac095c5e13d) +- [Dev Deps] update `@ljharb/eslint-config`, `es-abstract`, `es-value-fixtures`, `object-inspect`, `tape` [`10b6f5c`](https://github.com/ljharb/get-intrinsic/commit/10b6f5c02593fb3680c581d696ac124e30652932) +- [readme] add github actions/codecov badges [`4e25400`](https://github.com/ljharb/get-intrinsic/commit/4e25400d9f51ae9eb059cbe22d9144e70ea214e8) +- [Tests] use `for-each` instead of `foreach` [`c05b957`](https://github.com/ljharb/get-intrinsic/commit/c05b957ad9a7bc7721af7cc9e9be1edbfe057496) +- [Dev Deps] update `es-abstract` [`29b05ae`](https://github.com/ljharb/get-intrinsic/commit/29b05aec3e7330e9ad0b8e0f685a9112c20cdd97) +- [meta] use `prepublishOnly` script for npm 7+ [`95c285d`](https://github.com/ljharb/get-intrinsic/commit/95c285da810516057d3bbfa871176031af38f05d) +- [Deps] update `has-symbols` [`593cb4f`](https://github.com/ljharb/get-intrinsic/commit/593cb4fb38e7922e40e42c183f45274b636424cd) +- [readme] fix repo URLs [`1c8305b`](https://github.com/ljharb/get-intrinsic/commit/1c8305b5365827c9b6fc785434aac0e1328ff2f5) +- [Deps] update `has-symbols` [`c7138b6`](https://github.com/ljharb/get-intrinsic/commit/c7138b6c6d73132d859471fb8c13304e1e7c8b20) +- [Dev Deps] remove unused `has-bigints` [`bd63aff`](https://github.com/ljharb/get-intrinsic/commit/bd63aff6ad8f3a986c557fcda2914187bdaab359) + ## [v1.1.1](https://github.com/ljharb/get-intrinsic/compare/v1.1.0...v1.1.1) - 2021-02-03 ### Fixed diff --git a/node_modules/get-intrinsic/README.md b/node_modules/get-intrinsic/README.md index 335a3b4..3aa0bba 100644 --- a/node_modules/get-intrinsic/README.md +++ b/node_modules/get-intrinsic/README.md @@ -1,5 +1,7 @@ # get-intrinsic [![Version Badge][npm-version-svg]][package-url] +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] [![License][license-image]][license-url] @@ -53,7 +55,7 @@ Simply clone the repo, `npm install`, and run `npm test` Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. [package-url]: https://npmjs.org/package/get-intrinsic -[npm-version-svg]: http://versionbadg.es/ljharb/get-intrinsic.svg +[npm-version-svg]: https://versionbadg.es/ljharb/get-intrinsic.svg [deps-svg]: https://david-dm.org/ljharb/get-intrinsic.svg [deps-url]: https://david-dm.org/ljharb/get-intrinsic [dev-deps-svg]: https://david-dm.org/ljharb/get-intrinsic/dev-status.svg @@ -63,3 +65,7 @@ Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/se [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/get-intrinsic.svg [downloads-url]: https://npm-stat.com/charts.html?package=get-intrinsic +[codecov-image]: https://codecov.io/gh/ljharb/get-intrinsic/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/get-intrinsic/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/get-intrinsic +[actions-url]: https://github.com/ljharb/get-intrinsic/actions diff --git a/node_modules/get-intrinsic/index.js b/node_modules/get-intrinsic/index.js index d6c06c2..3c3d93e 100644 --- a/node_modules/get-intrinsic/index.js +++ b/node_modules/get-intrinsic/index.js @@ -202,6 +202,7 @@ 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; @@ -257,6 +258,9 @@ module.exports = function GetIntrinsic(name, allowMissing) { throw new $TypeError('"allowMissing" argument must be a boolean'); } + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` 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] : ''; diff --git a/node_modules/get-intrinsic/package.json b/node_modules/get-intrinsic/package.json index 5b76586..dfde032 100644 --- a/node_modules/get-intrinsic/package.json +++ b/node_modules/get-intrinsic/package.json @@ -1,107 +1,91 @@ { - "_from": "get-intrinsic@^1.0.2", - "_id": "get-intrinsic@1.1.1", - "_inBundle": false, - "_integrity": "sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==", - "_location": "/get-intrinsic", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "get-intrinsic@^1.0.2", - "name": "get-intrinsic", - "escapedName": "get-intrinsic", - "rawSpec": "^1.0.2", - "saveSpec": null, - "fetchSpec": "^1.0.2" - }, - "_requiredBy": [ - "/call-bind", - "/side-channel" - ], - "_resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.1.1.tgz", - "_shasum": "15f59f376f855c446963948f0d24cd3637b4abc6", - "_spec": "get-intrinsic@^1.0.2", - "_where": "D:\\workbench\\personal\\bnyer-cloud-tiktok\\node_modules\\side-channel", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com" - }, - "auto-changelog": { - "output": "CHANGELOG.md", - "template": "keepachangelog", - "unreleased": false, - "commitLimit": false, - "backfillLimit": false, - "hideCredit": true - }, - "bugs": { - "url": "https://github.com/ljharb/get-intrinsic/issues" - }, - "bundleDependencies": false, - "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1" - }, - "deprecated": false, - "description": "Get and robustly cache all JS language-level intrinsics at first require time", - "devDependencies": { - "@ljharb/eslint-config": "^17.5.0", - "aud": "^1.1.3", - "auto-changelog": "^2.2.1", - "call-bind": "^1.0.2", - "es-abstract": "^1.18.0-next.2", - "es-value-fixtures": "^1.0.0", - "eslint": "^7.19.0", - "evalmd": "^0.0.19", - "foreach": "^2.0.5", - "has-bigints": "^1.0.1", - "make-async-function": "^1.0.0", - "make-async-generator-function": "^1.0.0", - "make-generator-function": "^2.0.0", - "nyc": "^10.3.2", - "object-inspect": "^1.9.0", - "tape": "^5.1.1" - }, - "exports": { - ".": [ - { - "default": "./index.js" - }, - "./index.js" - ], - "./package.json": "./package.json" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "homepage": "https://github.com/ljharb/get-intrinsic#readme", - "keywords": [ - "javascript", - "ecmascript", - "es", - "js", - "intrinsic", - "getintrinsic", - "es-abstract" - ], - "license": "MIT", - "main": "index.js", - "name": "get-intrinsic", - "repository": { - "type": "git", - "url": "git+https://github.com/ljharb/get-intrinsic.git" - }, - "scripts": { - "lint": "eslint --ext=.js,.mjs .", - "posttest": "aud --production", - "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", - "prelint": "evalmd README.md", - "pretest": "npm run lint", - "test": "npm run tests-only", - "tests-only": "nyc tape 'test/**/*.js'", - "version": "auto-changelog && git add CHANGELOG.md" - }, - "version": "1.1.1" + "name": "get-intrinsic", + "version": "1.1.3", + "description": "Get and robustly cache all JS language-level intrinsics at first require time", + "main": "index.js", + "exports": { + ".": [ + { + "default": "./index.js" + }, + "./index.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=.js,.mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/get-intrinsic.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "es", + "js", + "intrinsic", + "getintrinsic", + "es-abstract" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/get-intrinsic/issues" + }, + "homepage": "https://github.com/ljharb/get-intrinsic#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "call-bind": "^1.0.2", + "es-abstract": "^1.20.2", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "make-async-function": "^1.0.0", + "make-async-generator-function": "^1.0.0", + "make-generator-function": "^2.0.0", + "mock-property": "^1.0.0", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.12.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.0" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "dependencies": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.3" + }, + "testling": { + "files": "test/GetIntrinsic.js" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } } diff --git a/node_modules/get-intrinsic/test/GetIntrinsic.js b/node_modules/get-intrinsic/test/GetIntrinsic.js index 695e3ad..7e0ea30 100644 --- a/node_modules/get-intrinsic/test/GetIntrinsic.js +++ b/node_modules/get-intrinsic/test/GetIntrinsic.js @@ -3,16 +3,17 @@ var GetIntrinsic = require('../'); var test = require('tape'); -var forEach = require('foreach'); +var forEach = require('for-each'); var debug = require('object-inspect'); var generatorFns = require('make-generator-function')(); var asyncFns = require('make-async-function').list(); var asyncGenFns = require('make-async-generator-function')(); +var mockProperty = require('mock-property'); var callBound = require('call-bind/callBound'); var v = require('es-value-fixtures'); var $gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var defineProperty = require('es-abstract/test/helpers/defineProperty'); +var DefinePropertyOrThrow = require('es-abstract/2021/DefinePropertyOrThrow'); var $isProto = callBound('%Object.prototype.isPrototypeOf%'); @@ -66,6 +67,18 @@ test('throws', function (t) { "Throws when middle part doesn't exist (%Proxy.prototype.undefined%)" ); + t['throws']( + function () { GetIntrinsic('%Array.prototype%garbage%'); }, + SyntaxError, + 'Throws with extra percent signs' + ); + + t['throws']( + function () { GetIntrinsic('%Array.prototype%push%'); }, + SyntaxError, + 'Throws with extra percent signs, even on an existing intrinsic' + ); + forEach(v.nonStrings, function (nonString) { t['throws']( function () { GetIntrinsic(nonString); }, @@ -123,15 +136,15 @@ test('dotted paths', function (t) { '%ObjProto_toString%', 'ObjProto_toString' ], function (name) { - defineProperty(Object.prototype, 'toString', { - value: function toString() { + DefinePropertyOrThrow(Object.prototype, 'toString', { + '[[Value]]': function toString() { return original.apply(this, arguments); } }); st.equal(GetIntrinsic(name), original, name + ' yields original Object.prototype.toString'); }); - defineProperty(Object.prototype, 'toString', { value: original }); + DefinePropertyOrThrow(Object.prototype, 'toString', { '[[Value]]': original }); st.end(); }); @@ -144,15 +157,16 @@ test('dotted paths', function (t) { '%ObjectPrototype.propertyIsEnumerable%', 'ObjectPrototype.propertyIsEnumerable' ], function (name) { - // eslint-disable-next-line no-extend-native - Object.prototype.propertyIsEnumerable = function propertyIsEnumerable() { - return original.apply(this, arguments); - }; + var restore = mockProperty(Object.prototype, 'propertyIsEnumerable', { + value: function propertyIsEnumerable() { + return original.apply(this, arguments); + } + }); st.equal(GetIntrinsic(name), original, name + ' yields cached Object.prototype.propertyIsEnumerable'); + + restore(); }); - // eslint-disable-next-line no-extend-native - Object.prototype.propertyIsEnumerable = original; st.end(); }); diff --git a/node_modules/has-symbols/package.json b/node_modules/has-symbols/package.json index 8512f37..fe7004a 100644 --- a/node_modules/has-symbols/package.json +++ b/node_modules/has-symbols/package.json @@ -1,126 +1,101 @@ { - "_from": "has-symbols@^1.0.1", - "_id": "has-symbols@1.0.3", - "_inBundle": false, - "_integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", - "_location": "/has-symbols", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "has-symbols@^1.0.1", - "name": "has-symbols", - "escapedName": "has-symbols", - "rawSpec": "^1.0.1", - "saveSpec": null, - "fetchSpec": "^1.0.1" - }, - "_requiredBy": [ - "/get-intrinsic" - ], - "_resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.0.3.tgz", - "_shasum": "bb7b2c4349251dce87b125f7bdf874aa7c8b39f8", - "_spec": "has-symbols@^1.0.1", - "_where": "D:\\workbench\\personal\\bnyer-cloud-tiktok\\node_modules\\get-intrinsic", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - }, - "auto-changelog": { - "output": "CHANGELOG.md", - "template": "keepachangelog", - "unreleased": false, - "commitLimit": false, - "backfillLimit": false, - "hideCredit": true - }, - "bugs": { - "url": "https://github.com/ljharb/has-symbols/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - } - ], - "deprecated": false, - "description": "Determine if the JS environment has Symbol support. Supports spec, or shams.", - "devDependencies": { - "@ljharb/eslint-config": "^20.2.3", - "aud": "^2.0.0", - "auto-changelog": "^2.4.0", - "core-js": "^2.6.12", - "eslint": "=8.8.0", - "get-own-property-symbols": "^0.9.5", - "nyc": "^10.3.2", - "safe-publish-latest": "^2.0.0", - "tape": "^5.5.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "greenkeeper": { - "ignore": [ - "core-js" - ] - }, - "homepage": "https://github.com/ljharb/has-symbols#readme", - "keywords": [ - "Symbol", - "symbols", - "typeof", - "sham", - "polyfill", - "native", - "core-js", - "ES6" - ], - "license": "MIT", - "main": "index.js", - "name": "has-symbols", - "repository": { - "type": "git", - "url": "git://github.com/inspect-js/has-symbols.git" - }, - "scripts": { - "lint": "eslint --ext=js,mjs .", - "posttest": "aud --production", - "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", - "prepublish": "not-in-publish || npm run prepublishOnly", - "prepublishOnly": "safe-publish-latest", - "pretest": "npm run --silent lint", - "test": "npm run tests-only", - "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", - "test:shams:corejs": "nyc node test/shams/core-js.js", - "test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js", - "test:staging": "nyc node --harmony --es-staging test", - "test:stock": "nyc node test", - "tests-only": "npm run test:stock && npm run test:staging && npm run test:shams", - "version": "auto-changelog && git add CHANGELOG.md" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.3" + "name": "has-symbols", + "version": "1.0.3", + "description": "Determine if the JS environment has Symbol support. Supports spec, or shams.", + "main": "index.js", + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "npm run test:stock && npm run test:staging && npm run test:shams", + "test:stock": "nyc node test", + "test:staging": "nyc node --harmony --es-staging test", + "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", + "test:shams:corejs": "nyc node test/shams/core-js.js", + "test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/has-symbols.git" + }, + "keywords": [ + "Symbol", + "symbols", + "typeof", + "sham", + "polyfill", + "native", + "core-js", + "ES6" + ], + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/has-symbols/issues" + }, + "homepage": "https://github.com/ljharb/has-symbols#readme", + "devDependencies": { + "@ljharb/eslint-config": "^20.2.3", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", + "core-js": "^2.6.12", + "eslint": "=8.8.0", + "get-own-property-symbols": "^0.9.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.5.2" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "greenkeeper": { + "ignore": [ + "core-js" + ] + } } diff --git a/node_modules/has/package.json b/node_modules/has/package.json index eab1e96..7c4592f 100644 --- a/node_modules/has/package.json +++ b/node_modules/has/package.json @@ -1,56 +1,26 @@ { - "_from": "has@^1.0.3", - "_id": "has@1.0.3", - "_inBundle": false, - "_integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "_location": "/has", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "has@^1.0.3", - "name": "has", - "escapedName": "has", - "rawSpec": "^1.0.3", - "saveSpec": null, - "fetchSpec": "^1.0.3" - }, - "_requiredBy": [ - "/get-intrinsic" - ], - "_resolved": "https://registry.npmmirror.com/has/-/has-1.0.3.tgz", - "_shasum": "722d7cbfc1f6aa8241f16dd814e011e1f41e8796", - "_spec": "has@^1.0.3", - "_where": "D:\\workbench\\personal\\bnyer-cloud-tiktok\\node_modules\\get-intrinsic", + "name": "has", + "description": "Object.prototype.hasOwnProperty.call shortcut", + "version": "1.0.3", + "homepage": "https://github.com/tarruda/has", "author": { "name": "Thiago de Arruda", "email": "tpadilha84@gmail.com" }, - "bugs": { - "url": "https://github.com/tarruda/has/issues" - }, - "bundleDependencies": false, - "contributors": [ + "contributors": [ { "name": "Jordan Harband", "email": "ljharb@gmail.com", "url": "http://ljharb.codes" } ], - "dependencies": { - "function-bind": "^1.1.1" - }, - "deprecated": false, - "description": "Object.prototype.hasOwnProperty.call shortcut", - "devDependencies": { - "@ljharb/eslint-config": "^12.2.1", - "eslint": "^4.19.1", - "tape": "^4.9.0" + "repository": { + "type": "git", + "url": "git://github.com/tarruda/has.git" }, - "engines": { - "node": ">= 0.4.0" + "bugs": { + "url": "https://github.com/tarruda/has/issues" }, - "homepage": "https://github.com/tarruda/has", "license": "MIT", "licenses": [ { @@ -59,15 +29,20 @@ } ], "main": "./src", - "name": "has", - "repository": { - "type": "git", - "url": "git://github.com/tarruda/has.git" + "dependencies": { + "function-bind": "^1.1.1" + }, + "devDependencies": { + "@ljharb/eslint-config": "^12.2.1", + "eslint": "^4.19.1", + "tape": "^4.9.0" + }, + "engines": { + "node": ">= 0.4.0" }, "scripts": { "lint": "eslint .", "pretest": "npm run lint", "test": "tape test" - }, - "version": "1.0.3" + } } diff --git a/node_modules/object-inspect/.eslintignore b/node_modules/object-inspect/.eslintignore deleted file mode 100644 index 404abb2..0000000 --- a/node_modules/object-inspect/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -coverage/ diff --git a/node_modules/object-inspect/CHANGELOG.md b/node_modules/object-inspect/CHANGELOG.md index 519f700..36d1958 100644 --- a/node_modules/object-inspect/CHANGELOG.md +++ b/node_modules/object-inspect/CHANGELOG.md @@ -5,6 +5,24 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [v1.12.2](https://github.com/inspect-js/object-inspect/compare/v1.12.1...v1.12.2) - 2022-05-26 + +### Commits + +- [Fix] use `util.inspect` for a custom inspection symbol method [`e243bf2`](https://github.com/inspect-js/object-inspect/commit/e243bf2eda6c4403ac6f1146fddb14d12e9646c1) +- [meta] add support info [`ca20ba3`](https://github.com/inspect-js/object-inspect/commit/ca20ba35713c17068ca912a86c542f5e8acb656c) +- [Fix] ignore `cause` in node v16.9 and v16.10 where it has a bug [`86aa553`](https://github.com/inspect-js/object-inspect/commit/86aa553a4a455562c2c56f1540f0bf857b9d314b) + +## [v1.12.1](https://github.com/inspect-js/object-inspect/compare/v1.12.0...v1.12.1) - 2022-05-21 + +### Commits + +- [Tests] use `mock-property` [`4ec8893`](https://github.com/inspect-js/object-inspect/commit/4ec8893ea9bfd28065ca3638cf6762424bf44352) +- [meta] use `npmignore` to autogenerate an npmignore file [`07f868c`](https://github.com/inspect-js/object-inspect/commit/07f868c10bd25a9d18686528339bb749c211fc9a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`b05244b`](https://github.com/inspect-js/object-inspect/commit/b05244b4f331e00c43b3151bc498041be77ccc91) +- [Dev Deps] update `@ljharb/eslint-config`, `error-cause`, `es-value-fixtures`, `functions-have-names`, `tape` [`d037398`](https://github.com/inspect-js/object-inspect/commit/d037398dcc5d531532e4c19c4a711ed677f579c1) +- [Fix] properly handle callable regexes in older engines [`848fe48`](https://github.com/inspect-js/object-inspect/commit/848fe48bd6dd0064ba781ee6f3c5e54a94144c37) + ## [v1.12.0](https://github.com/inspect-js/object-inspect/compare/v1.11.1...v1.12.0) - 2021-12-18 ### Commits diff --git a/node_modules/object-inspect/index.js b/node_modules/object-inspect/index.js index b4e02ff..7ab98a6 100644 --- a/node_modules/object-inspect/index.js +++ b/node_modules/object-inspect/index.js @@ -65,8 +65,9 @@ function addNumericSeparator(num, str) { return $replace.call(str, sepRegex, '$&_'); } -var inspectCustom = require('./util.inspect').custom; -var inspectSymbol = inspectCustom && isSymbol(inspectCustom) ? inspectCustom : null; +var utilInspect = require('./util.inspect'); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; module.exports = function inspect_(obj, options, depth, seen) { var opts = options || {}; @@ -156,7 +157,7 @@ module.exports = function inspect_(obj, options, depth, seen) { return inspect_(value, opts, depth + 1, seen); } - if (typeof obj === 'function') { + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable var name = nameOf(obj); var keys = arrObjKeys(obj, inspect); return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); @@ -186,15 +187,15 @@ module.exports = function inspect_(obj, options, depth, seen) { } if (isError(obj)) { var parts = arrObjKeys(obj, inspect); - if ('cause' in obj && !isEnumerable.call(obj, 'cause')) { + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; } if (parts.length === 0) { return '[' + String(obj) + ']'; } return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; } if (typeof obj === 'object' && customInspect) { - if (inspectSymbol && typeof obj[inspectSymbol] === 'function') { - return obj[inspectSymbol](); + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { return obj.inspect(); } diff --git a/node_modules/object-inspect/package.json b/node_modules/object-inspect/package.json index e604cd9..7e0b87c 100644 --- a/node_modules/object-inspect/package.json +++ b/node_modules/object-inspect/package.json @@ -1,97 +1,41 @@ { - "_from": "object-inspect@^1.9.0", - "_id": "object-inspect@1.12.0", - "_inBundle": false, - "_integrity": "sha512-Ho2z80bVIvJloH+YzRmpZVQe87+qASmBUKZDWgx9cu+KDrX2ZDH/3tMy+gXbZETVGs2M8YdxObOh7XAtim9Y0g==", - "_location": "/object-inspect", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "object-inspect@^1.9.0", - "name": "object-inspect", - "escapedName": "object-inspect", - "rawSpec": "^1.9.0", - "saveSpec": null, - "fetchSpec": "^1.9.0" - }, - "_requiredBy": [ - "/side-channel" - ], - "_resolved": "https://registry.npmmirror.com/object-inspect/-/object-inspect-1.12.0.tgz", - "_shasum": "6e2c120e868fd1fd18cb4f18c31741d0d6e776f0", - "_spec": "object-inspect@^1.9.0", - "_where": "D:\\workbench\\personal\\bnyer-cloud-tiktok\\node_modules\\side-channel", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "auto-changelog": { - "output": "CHANGELOG.md", - "template": "keepachangelog", - "unreleased": false, - "commitLimit": false, - "backfillLimit": false, - "hideCredit": true - }, - "browser": { - "./util.inspect.js": false - }, - "bugs": { - "url": "https://github.com/inspect-js/object-inspect/issues" - }, - "bundleDependencies": false, - "deprecated": false, + "name": "object-inspect", + "version": "1.12.2", "description": "string representations of objects in node and the browser", + "main": "index.js", + "sideEffects": false, "devDependencies": { - "@ljharb/eslint-config": "^20.1.0", - "aud": "^1.1.5", - "auto-changelog": "^2.3.0", + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.0", + "auto-changelog": "^2.4.0", "core-js": "^2.6.12", - "error-cause": "^1.0.3", - "es-value-fixtures": "^1.2.1", - "eslint": "^8.5.0", + "error-cause": "^1.0.4", + "es-value-fixtures": "^1.4.1", + "eslint": "=8.8.0", "for-each": "^0.3.3", - "functions-have-names": "^1.2.2", + "functions-have-names": "^1.2.3", "has-tostringtag": "^1.0.0", "make-arrow-function": "^1.2.0", + "mock-property": "^1.0.0", + "npmignore": "^0.3.0", "nyc": "^10.3.2", "safe-publish-latest": "^2.0.0", "string.prototype.repeat": "^1.0.0", - "tape": "^5.3.2" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "homepage": "https://github.com/inspect-js/object-inspect", - "keywords": [ - "inspect", - "util.inspect", - "object", - "stringify", - "pretty" - ], - "license": "MIT", - "main": "index.js", - "name": "object-inspect", - "repository": { - "type": "git", - "url": "git://github.com/inspect-js/object-inspect.git" + "tape": "^5.5.3" }, "scripts": { - "lint": "eslint .", - "posttest": "npx aud --production", - "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", + "prepack": "npmignore --auto --commentLines=autogenerated", "prepublish": "not-in-publish || npm run prepublishOnly", "prepublishOnly": "safe-publish-latest", "pretest": "npm run lint", + "lint": "eslint .", "test": "npm run tests-only && npm run test:corejs", - "test:corejs": "nyc tape test-core-js.js 'test/*.js'", "tests-only": "nyc tape 'test/*.js'", - "version": "auto-changelog && git add CHANGELOG.md" + "test:corejs": "nyc tape test-core-js.js 'test/*.js'", + "posttest": "npx aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" }, - "sideEffects": false, "testling": { "files": [ "test/*.js", @@ -108,5 +52,43 @@ "android/latest" ] }, - "version": "1.12.0" + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/object-inspect.git" + }, + "homepage": "https://github.com/inspect-js/object-inspect", + "keywords": [ + "inspect", + "util.inspect", + "object", + "stringify", + "pretty" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "browser": { + "./util.inspect.js": false + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "./test-core-js.js" + ] + }, + "support": true } diff --git a/node_modules/object-inspect/test/err.js b/node_modules/object-inspect/test/err.js index ef8b1cb..cc1d884 100644 --- a/node_modules/object-inspect/test/err.js +++ b/node_modules/object-inspect/test/err.js @@ -40,9 +40,9 @@ test('type error', function (t) { '{ [TypeError] foo: 555, bar: [ 1, 2, 3 ] }', '{ [TypeError: tuv] baz: 555 }', '{ [SyntaxError: whoa] message: \'whoa\', \'a-b\': 5 }', - '{ [Error: foo] [cause]: \'bar\' }', - '{ [Error: foo] [cause]: \'bar\', foo: \'bar\' }', - '{ [Error: foo] [cause]: undefined }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: \'bar\' }', + '{ [Error: foo] ' + ('cause' in Error.prototype ? '' : '[cause]: \'bar\', ') + 'foo: \'bar\' }', + 'cause' in Error.prototype ? '[Error: foo]' : '{ [Error: foo] [cause]: undefined }', '{ [Error: foo] cause: \'bar\' }' ].join(', ') + ' ]'); }); diff --git a/node_modules/object-inspect/test/has.js b/node_modules/object-inspect/test/has.js index 026d6d5..01800de 100644 --- a/node_modules/object-inspect/test/has.js +++ b/node_modules/object-inspect/test/has.js @@ -1,34 +1,15 @@ +'use strict'; + var inspect = require('../'); var test = require('tape'); - -function withoutProperty(object, property, fn) { - var original; - if (Object.getOwnPropertyDescriptor) { - original = Object.getOwnPropertyDescriptor(object, property); - } else { - original = object[property]; - } - delete object[property]; - try { - fn(); - } finally { - if (Object.getOwnPropertyDescriptor) { - Object.defineProperty(object, property, original); - } else { - object[property] = original; - } - } -} +var mockProperty = require('mock-property'); test('when Object#hasOwnProperty is deleted', function (t) { t.plan(1); var arr = [1, , 3]; // eslint-disable-line no-sparse-arrays - // eslint-disable-next-line no-extend-native - Array.prototype[1] = 2; // this is needed to account for "in" vs "hasOwnProperty" + t.teardown(mockProperty(Array.prototype, 1, { value: 2 })); // this is needed to account for "in" vs "hasOwnProperty" + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); - withoutProperty(Object.prototype, 'hasOwnProperty', function () { - t.equal(inspect(arr), '[ 1, , 3 ]'); - }); - delete Array.prototype[1]; + t.equal(inspect(arr), '[ 1, , 3 ]'); }); diff --git a/node_modules/object-inspect/test/inspect.js b/node_modules/object-inspect/test/inspect.js index bcf264e..1abf81b 100644 --- a/node_modules/object-inspect/test/inspect.js +++ b/node_modules/object-inspect/test/inspect.js @@ -100,3 +100,40 @@ test('maxStringLength', function (t) { t.end(); }); + +test('inspect options', { skip: !utilInspect.custom }, function (t) { + var obj = {}; + obj[utilInspect.custom] = function () { + return JSON.stringify(arguments); + }; + t.equal( + inspect(obj), + utilInspect(obj, { depth: 5 }), + 'custom symbols will use node\'s inspect' + ); + t.equal( + inspect(obj, { depth: 2 }), + utilInspect(obj, { depth: 2 }), + 'a reduced depth will be passed to node\'s inspect' + ); + t.equal( + inspect({ d1: obj }, { depth: 3 }), + '{ d1: ' + utilInspect(obj, { depth: 2 }) + ' }', + 'deep objects will receive a reduced depth' + ); + t.equal( + inspect({ d1: obj }, { depth: 1 }), + '{ d1: [Object] }', + 'unlike nodejs inspect, customInspect will not be used once the depth is exceeded.' + ); + t.end(); +}); + +test('inspect URL', { skip: typeof URL === 'undefined' }, function (t) { + t.match( + inspect(new URL('https://nodejs.org')), + /nodejs\.org/, // Different environments stringify it differently + 'url can be inspected' + ); + t.end(); +}); diff --git a/node_modules/object-inspect/test/values.js b/node_modules/object-inspect/test/values.js index c83cb95..4832b9f 100644 --- a/node_modules/object-inspect/test/values.js +++ b/node_modules/object-inspect/test/values.js @@ -2,6 +2,7 @@ var inspect = require('../'); var test = require('tape'); +var mockProperty = require('mock-property'); var hasSymbols = require('has-symbols/shams')(); var hasToStringTag = require('has-tostringtag/shams')(); @@ -23,10 +24,9 @@ test('arrays with properties', function (t) { test('has', function (t) { t.plan(1); - var has = Object.prototype.hasOwnProperty; - delete Object.prototype.hasOwnProperty; + t.teardown(mockProperty(Object.prototype, 'hasOwnProperty', { 'delete': true })); + t.equal(inspect({ a: 1, b: 2 }), '{ a: 1, b: 2 }'); - Object.prototype.hasOwnProperty = has; // eslint-disable-line no-extend-native }); test('indexOf seen', function (t) { diff --git a/node_modules/qs/.editorconfig b/node_modules/qs/.editorconfig index 0ea91d9..2f08444 100644 --- a/node_modules/qs/.editorconfig +++ b/node_modules/qs/.editorconfig @@ -38,3 +38,6 @@ indent_size = off indent_style = off indent = off max_line_length = off + +[.nycrc] +indent_style = tab diff --git a/node_modules/qs/.eslintrc b/node_modules/qs/.eslintrc index 6884760..35220cd 100644 --- a/node_modules/qs/.eslintrc +++ b/node_modules/qs/.eslintrc @@ -14,8 +14,8 @@ "id-length": [2, { "min": 1, "max": 25, "properties": "never" }], "indent": [2, 4], "max-lines-per-function": [2, { "max": 150 }], - "max-params": [2, 15], - "max-statements": [2, 52], + "max-params": [2, 16], + "max-statements": [2, 53], "multiline-comment-style": 0, "no-continue": 1, "no-magic-numbers": 0, @@ -32,7 +32,7 @@ "no-buffer-constructor": 0, "no-extend-native": 0, "no-throw-literal": 0, - } - } - ] + }, + }, + ], } diff --git a/node_modules/qs/CHANGELOG.md b/node_modules/qs/CHANGELOG.md index c6b2915..37b1d3f 100644 --- a/node_modules/qs/CHANGELOG.md +++ b/node_modules/qs/CHANGELOG.md @@ -1,3 +1,15 @@ +## **6.11.0 +- [New] [Fix] `stringify`: revert 0e903c0; add `commaRoundTrip` option (#442) +- [readme] fix version badge + +## **6.10.5** +- [Fix] `stringify`: with `arrayFormat: comma`, properly include an explicit `[]` on a single-item array (#434) + +## **6.10.4** +- [Fix] `stringify`: with `arrayFormat: comma`, include an explicit `[]` on a single-item array (#441) +- [meta] use `npmignore` to autogenerate an npmignore file +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `has-symbol`, `object-inspect`, `tape` + ## **6.10.3** - [Fix] `parse`: ignore `__proto__` keys (#428) - [Robustness] `stringify`: avoid relying on a global `undefined` (#427) @@ -27,6 +39,18 @@ - [Tests] use `ljharb/actions/node/install` instead of `ljharb/actions/node/run` - [Tests] Revert "[meta] ignore eclint transitive audit warning" +## **6.9.7** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [Tests] clean up stringify tests slightly +- [meta] fix README.md (#399) +- Revert "[meta] ignore eclint transitive audit warning" +- [actions] backport actions from main +- [Dev Deps] backport updates from main + ## **6.9.6** - [Fix] restore `dist` dir; mistakenly removed in d4f6c32 @@ -75,6 +99,19 @@ - [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16` - [Tests] `Buffer.from` in node v5.0-v5.9 and v4.0-v4.4 requires a TypedArray +## **6.8.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Tests] clean up stringify tests slightly +- [Docs] add note and links for coercing primitive values (#408) +- [meta] fix README.md (#399) +- [actions] backport actions from main +- [Dev Deps] backport updates from main +- [Refactor] `stringify`: reduce branching +- [meta] do not publish workflow files + ## **6.8.2** - [Fix] proper comma parsing of URL-encoded commas (#361) - [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) @@ -106,6 +143,19 @@ - [meta] add FUNDING.yml - [meta] Clean up license text so it’s properly detected as BSD-3-Clause +## **6.7.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `stringify`: avoid encoding arrayformat comma when `encodeValuesOnly = true` (#424) +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] add note and links for coercing primitive values (#408) +- [meta] fix README.md (#399) +- [meta] do not publish workflow files +- [actions] backport actions from main +- [Dev Deps] backport updates from main +- [Tests] use `nyc` for coverage +- [Tests] clean up stringify tests slightly + ## **6.7.2** - [Fix] proper comma parsing of URL-encoded commas (#361) - [Fix] parses comma delimited array while having percent-encoded comma treated as normal text (#336) @@ -144,6 +194,32 @@ - [Tests] fix Buffer tests to work in node < 4.5 and node < 5.10 - [Tests] temporarily allow coverage to fail +## **6.6.1** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] correctly parse nested arrays +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Robustness] `stringify`: cache `Object.prototype.hasOwnProperty` +- [Refactor] `formats`: tiny bit of cleanup. +- [Refactor] `utils`: `isBuffer`: small tweak; add tests +- [Refactor]: `stringify`/`utils`: cache `Array.isArray` +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] use cached `Array.isArray` +- [Refactor] `parse`/`stringify`: make a function to normalize the options +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] do not publish workflow files +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [meta] Fixes typo in CHANGELOG.md +- [actions] backport actions from main +- [Tests] fix Buffer tests to work in node < 4.5 and node < 5.10 +- [Tests] always use `String(x)` over `x.toString()` +- [Dev Deps] backport from main + ## **6.6.0** - [New] Add support for iso-8859-1, utf8 "sentinel" and numeric entities (#268) - [New] move two-value combine to a `utils` function (#189) @@ -160,6 +236,30 @@ - [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`, `iconv-lite`, `safe-publish-latest`, `tape` - [Tests] up to `node` `v10.10`, `v9.11`, `v8.12`, `v6.14`, `v4.9`; pin included builds to LTS +## **6.5.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix]` `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] correctly parse nested arrays +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Refactor] `utils`: reduce observable [[Get]]s +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Refactor] `parse`: only need to reassign the var once +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clean up license text so it’s properly detected as BSD-3-Clause +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] always use `String(x)` over `x.toString()` +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + ## **6.5.2** - [Fix] use `safer-buffer` instead of `Buffer` constructor - [Refactor] utils: `module.exports` one thing, instead of mutating `exports` (#230) @@ -186,6 +286,27 @@ - [Tests] up to `node` `v8.1`, `v7.10`, `v6.11`; npm v4.6 breaks on node < v1; npm v5+ breaks on node < v4 - [Tests] add `editorconfig-tools` +## **6.4.1** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] use `safer-buffer` instead of `Buffer` constructor +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix]` `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [readme] remove travis badge; add github actions/codecov badges; update URLs +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + ## **6.4.0** - [New] `qs.stringify`: add `encodeValuesOnly` option - [Fix] follow `allowPrototypes` option during merge (#201, #201) @@ -195,6 +316,26 @@ - [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds - [eslint] reduce warnings +## **6.3.3** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] fix for an impossible situation: when the formatter is called with a non-string value +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix]` `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `stringify`: fix a crash with `strictNullHandling` and a custom `filter`/`serializeDate` (#279) +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Refactor] `stringify`: Avoid arr = arr.concat(...), push to the existing instance (#269) +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] use `safer-buffer` instead of `Buffer` constructor +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + ## **6.3.2** - [Fix] follow `allowPrototypes` option during merge (#201, #200) - [Dev Deps] update `eslint` @@ -228,6 +369,23 @@ - [Tests] skip Object.create tests when null objects are not available - [Tests] Turn on eslint for test files (#175) +## **6.2.4** +- [Fix] `parse`: ignore `__proto__` keys (#428) +- [Fix] `utils.merge`: avoid a crash with a null target and an array source +- [Fix] `utils.merge`: avoid a crash with a null target and a truthy non-array source +- [Fix] `utils`: `merge`: fix crash when `source` is a truthy primitive & no options are provided +- [Fix] when `parseArrays` is false, properly handle keys ending in `[]` +- [Robustness] `stringify`: avoid relying on a global `undefined` (#427) +- [Refactor] use cached `Array.isArray` +- [Docs] Clarify the need for "arrayLimit" option +- [meta] fix README.md (#399) +- [meta] Clean up license text so it’s properly detected as BSD-3-Clause +- [meta] add FUNDING.yml +- [actions] backport actions from main +- [Tests] use `safer-buffer` instead of `Buffer` constructor +- [Tests] remove nonexistent tape option +- [Dev Deps] backport from main + ## **6.2.3** - [Fix] follow `allowPrototypes` option during merge (#201, #200) - [Fix] chmod a-x diff --git a/node_modules/qs/README.md b/node_modules/qs/README.md index 0126380..11be853 100644 --- a/node_modules/qs/README.md +++ b/node_modules/qs/README.md @@ -1,4 +1,4 @@ -# qs [![Version Badge][2]][1] +# qs [![Version Badge][npm-version-svg]][package-url] [![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] @@ -402,6 +402,8 @@ qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'comma' }) // 'a=b,c' ``` +Note: when using `arrayFormat` set to `'comma'`, you can also pass the `commaRoundTrip` option set to `true` or `false`, to append `[]` on single-item arrays, so that they can round trip through a parse. + When objects are stringified, by default they use bracket notation: ```javascript diff --git a/node_modules/qs/dist/qs.js b/node_modules/qs/dist/qs.js index 94baf8f..1c620a4 100644 --- a/node_modules/qs/dist/qs.js +++ b/node_modules/qs/dist/qs.js @@ -366,6 +366,7 @@ var stringify = function stringify( object, prefix, generateArrayPrefix, + commaRoundTrip, strictNullHandling, skipNulls, encoder, @@ -430,7 +431,7 @@ var stringify = function stringify( for (var i = 0; i < valuesArray.length; ++i) { valuesJoined += (i === 0 ? '' : ',') + formatter(encoder(valuesArray[i], defaults.encoder, charset, 'value', format)); } - return [formatter(keyValue) + '=' + valuesJoined]; + return [formatter(keyValue) + (commaRoundTrip && isArray(obj) && valuesArray.length === 1 ? '[]' : '') + '=' + valuesJoined]; } return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; } @@ -454,6 +455,8 @@ var stringify = function stringify( objKeys = sort ? keys.sort(sort) : keys; } + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix; + for (var j = 0; j < objKeys.length; ++j) { var key = objKeys[j]; var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; @@ -463,8 +466,8 @@ var stringify = function stringify( } var keyPrefix = isArray(obj) - ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix - : prefix + (allowDots ? '.' + key : '[' + key + ']'); + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']'); sideChannel.set(object, step); var valueSideChannel = getSideChannel(); @@ -473,6 +476,7 @@ var stringify = function stringify( value, keyPrefix, generateArrayPrefix, + commaRoundTrip, strictNullHandling, skipNulls, encoder, @@ -569,6 +573,10 @@ module.exports = function (object, opts) { } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip; if (!objKeys) { objKeys = Object.keys(obj); @@ -589,6 +597,7 @@ module.exports = function (object, opts) { obj[key], key, generateArrayPrefix, + commaRoundTrip, options.strictNullHandling, options.skipNulls, options.encode ? options.encoder : null, @@ -1469,8 +1478,9 @@ function addNumericSeparator(num, str) { return $replace.call(str, sepRegex, '$&_'); } -var inspectCustom = require('./util.inspect').custom; -var inspectSymbol = inspectCustom && isSymbol(inspectCustom) ? inspectCustom : null; +var utilInspect = require('./util.inspect'); +var inspectCustom = utilInspect.custom; +var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; module.exports = function inspect_(obj, options, depth, seen) { var opts = options || {}; @@ -1560,7 +1570,7 @@ module.exports = function inspect_(obj, options, depth, seen) { return inspect_(value, opts, depth + 1, seen); } - if (typeof obj === 'function') { + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable var name = nameOf(obj); var keys = arrObjKeys(obj, inspect); return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); @@ -1590,15 +1600,15 @@ module.exports = function inspect_(obj, options, depth, seen) { } if (isError(obj)) { var parts = arrObjKeys(obj, inspect); - if ('cause' in obj && !isEnumerable.call(obj, 'cause')) { + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; } if (parts.length === 0) { return '[' + String(obj) + ']'; } return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; } if (typeof obj === 'object' && customInspect) { - if (inspectSymbol && typeof obj[inspectSymbol] === 'function') { - return obj[inspectSymbol](); + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { return obj.inspect(); } diff --git a/node_modules/qs/lib/stringify.js b/node_modules/qs/lib/stringify.js index 47ea4b1..48ec030 100644 --- a/node_modules/qs/lib/stringify.js +++ b/node_modules/qs/lib/stringify.js @@ -62,6 +62,7 @@ var stringify = function stringify( object, prefix, generateArrayPrefix, + commaRoundTrip, strictNullHandling, skipNulls, encoder, @@ -126,7 +127,7 @@ var stringify = function stringify( for (var i = 0; i < valuesArray.length; ++i) { valuesJoined += (i === 0 ? '' : ',') + formatter(encoder(valuesArray[i], defaults.encoder, charset, 'value', format)); } - return [formatter(keyValue) + '=' + valuesJoined]; + return [formatter(keyValue) + (commaRoundTrip && isArray(obj) && valuesArray.length === 1 ? '[]' : '') + '=' + valuesJoined]; } return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; } @@ -150,6 +151,8 @@ var stringify = function stringify( objKeys = sort ? keys.sort(sort) : keys; } + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix; + for (var j = 0; j < objKeys.length; ++j) { var key = objKeys[j]; var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; @@ -159,8 +162,8 @@ var stringify = function stringify( } var keyPrefix = isArray(obj) - ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix - : prefix + (allowDots ? '.' + key : '[' + key + ']'); + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']'); sideChannel.set(object, step); var valueSideChannel = getSideChannel(); @@ -169,6 +172,7 @@ var stringify = function stringify( value, keyPrefix, generateArrayPrefix, + commaRoundTrip, strictNullHandling, skipNulls, encoder, @@ -265,6 +269,10 @@ module.exports = function (object, opts) { } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip; if (!objKeys) { objKeys = Object.keys(obj); @@ -285,6 +293,7 @@ module.exports = function (object, opts) { obj[key], key, generateArrayPrefix, + commaRoundTrip, options.strictNullHandling, options.skipNulls, options.encode ? options.encoder : null, diff --git a/node_modules/qs/package.json b/node_modules/qs/package.json index 88395d5..2ff42f3 100644 --- a/node_modules/qs/package.json +++ b/node_modules/qs/package.json @@ -1,101 +1,77 @@ { - "_from": "qs@^6.10.3", - "_id": "qs@6.10.3", - "_inBundle": false, - "_integrity": "sha512-wr7M2E0OFRfIfJZjKGieI8lBKb7fRCH4Fv5KNPEs7gJ8jadvotdsS08PzOKR7opXhZ/Xkjtt3WF9g38drmyRqQ==", - "_location": "/qs", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "qs@^6.10.3", "name": "qs", - "escapedName": "qs", - "rawSpec": "^6.10.3", - "saveSpec": null, - "fetchSpec": "^6.10.3" - }, - "_requiredBy": [ - "/" - ], - "_resolved": "https://registry.npmmirror.com/qs/-/qs-6.10.3.tgz", - "_shasum": "d6cde1b2ffca87b5aa57889816c5f81535e22e8e", - "_spec": "qs@^6.10.3", - "_where": "D:\\workbench\\personal\\bnyer-cloud-tiktok", - "bugs": { - "url": "https://github.com/ljharb/qs/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "homepage": "https://github.com/ljharb/qs", + "version": "6.11.0", + "repository": { + "type": "git", + "url": "https://github.com/ljharb/qs.git" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "main": "lib/index.js", + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "keywords": [ + "querystring", + "qs", + "query", + "url", + "parse", + "stringify" + ], + "engines": { + "node": ">=0.6" + }, + "dependencies": { + "side-channel": "^1.0.4" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.0", + "browserify": "^16.5.2", + "eclint": "^2.8.1", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "has-symbols": "^1.0.3", + "iconv-lite": "^0.5.1", + "in-publish": "^2.0.1", + "mkdirp": "^0.5.5", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "object-inspect": "^1.12.2", + "qs-iconv": "^1.0.4", + "safe-publish-latest": "^2.0.0", + "safer-buffer": "^2.1.2", + "tape": "^5.5.3" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest && npm run dist", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent readme && npm run --silent lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/**/*.js'", + "posttest": "aud --production", + "readme": "evalmd README.md", + "postlint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git' | grep -v dist/)", + "lint": "eslint --ext=js,mjs .", + "dist": "mkdirp dist && browserify --standalone Qs lib/index.js > dist/qs.js" + }, + "license": "BSD-3-Clause", + "publishConfig": { + "ignore": [ + "!dist/*", + "bower.json", + "component.json", + ".github/workflows" + ] } - ], - "dependencies": { - "side-channel": "^1.0.4" - }, - "deprecated": false, - "description": "A querystring parser that supports nesting and arrays, with a depth limit", - "devDependencies": { - "@ljharb/eslint-config": "^20.1.0", - "aud": "^1.1.5", - "browserify": "^16.5.2", - "eclint": "^2.8.1", - "eslint": "^8.6.0", - "evalmd": "^0.0.19", - "for-each": "^0.3.3", - "has-symbols": "^1.0.2", - "iconv-lite": "^0.5.1", - "in-publish": "^2.0.1", - "mkdirp": "^0.5.5", - "nyc": "^10.3.2", - "object-inspect": "^1.12.0", - "qs-iconv": "^1.0.4", - "safe-publish-latest": "^2.0.0", - "safer-buffer": "^2.1.2", - "tape": "^5.4.0" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "greenkeeper": { - "ignore": [ - "iconv-lite", - "mkdirp" - ] - }, - "homepage": "https://github.com/ljharb/qs", - "keywords": [ - "querystring", - "qs", - "query", - "url", - "parse", - "stringify" - ], - "license": "BSD-3-Clause", - "main": "lib/index.js", - "name": "qs", - "repository": { - "type": "git", - "url": "git+https://github.com/ljharb/qs.git" - }, - "scripts": { - "dist": "mkdirp dist && browserify --standalone Qs lib/index.js > dist/qs.js", - "lint": "eslint .", - "postlint": "eclint check * lib/* test/* !dist/*", - "posttest": "aud --production", - "prepublish": "not-in-publish || npm run prepublishOnly", - "prepublishOnly": "safe-publish-latest && npm run dist", - "pretest": "npm run --silent readme && npm run --silent lint", - "readme": "evalmd README.md", - "test": "npm run tests-only", - "tests-only": "nyc tape 'test/**/*.js'" - }, - "version": "6.10.3" } diff --git a/node_modules/qs/test/parse.js b/node_modules/qs/test/parse.js index 7d61023..7d7b4dd 100644 --- a/node_modules/qs/test/parse.js +++ b/node_modules/qs/test/parse.js @@ -140,6 +140,9 @@ test('parse()', function (t) { t.test('limits specific array indices to arrayLimit', function (st) { st.deepEqual(qs.parse('a[20]=a', { arrayLimit: 20 }), { a: ['a'] }); st.deepEqual(qs.parse('a[21]=a', { arrayLimit: 20 }), { a: { 21: 'a' } }); + + st.deepEqual(qs.parse('a[20]=a'), { a: ['a'] }); + st.deepEqual(qs.parse('a[21]=a'), { a: { 21: 'a' } }); st.end(); }); @@ -378,6 +381,7 @@ test('parse()', function (t) { st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); st.deepEqual(qs.parse('foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: false }), { '?foo': 'bar' }); + st.end(); }); @@ -406,6 +410,16 @@ test('parse()', function (t) { st.deepEqual(qs.parse('foo=', { comma: true }), { foo: '' }); st.deepEqual(qs.parse('foo', { comma: true }), { foo: '' }); st.deepEqual(qs.parse('foo', { comma: true, strictNullHandling: true }), { foo: null }); + + // test cases inversed from from stringify tests + st.deepEqual(qs.parse('a[0]=c'), { a: ['c'] }); + st.deepEqual(qs.parse('a[]=c'), { a: ['c'] }); + st.deepEqual(qs.parse('a[]=c', { comma: true }), { a: ['c'] }); + + st.deepEqual(qs.parse('a[0]=c&a[1]=d'), { a: ['c', 'd'] }); + st.deepEqual(qs.parse('a[]=c&a[]=d'), { a: ['c', 'd'] }); + st.deepEqual(qs.parse('a=c,d', { comma: true }), { a: ['c', 'd'] }); + st.end(); }); diff --git a/node_modules/qs/test/stringify.js b/node_modules/qs/test/stringify.js index a3800aa..f0cdfef 100644 --- a/node_modules/qs/test/stringify.js +++ b/node_modules/qs/test/stringify.js @@ -131,6 +131,38 @@ test('stringify()', function (t) { st.end(); }); + t.test('stringifies an array value with one item vs multiple items', function (st) { + st.test('non-array item', function (s2t) { + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); + s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true }), 'a=c'); + + s2t.end(); + }); + + st.test('array with a single item', function (s2t) { + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), 'a[]=c'); // so it parses back as an array + s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true }), 'a[0]=c'); + + s2t.end(); + }); + + st.test('array with multiple items', function (s2t) { + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c&a[1]=d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c&a[]=d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c,d'); + s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true }), 'a[0]=c&a[1]=d'); + + s2t.end(); + }); + + st.end(); + }); + t.test('stringifies a nested array value', function (st) { st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[b][0]=c&a[b][1]=d'); st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[b][]=c&a[b][]=d'); @@ -349,11 +381,13 @@ test('stringify()', function (t) { st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets' }), 'b[]=&c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat' }), 'b=&c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma' }), 'b=&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', commaRoundTrip: true }), 'b[]=&c=c'); // with strictNullHandling st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', strictNullHandling: true }), 'b[0]&c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', strictNullHandling: true }), 'b[]&c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', strictNullHandling: true }), 'b&c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true }), 'b&c=c'); + st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true, commaRoundTrip: true }), 'b[]&c=c'); // with skipNulls st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', skipNulls: true }), 'c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', skipNulls: true }), 'c=c'); @@ -684,6 +718,18 @@ test('stringify()', function (t) { 'a=' + date.getTime(), 'works with arrayFormat comma' ); + st.equal( + qs.stringify( + { a: [date] }, + { + serializeDate: function (d) { return d.getTime(); }, + arrayFormat: 'comma', + commaRoundTrip: true + } + ), + 'a%5B%5D=' + date.getTime(), + 'works with arrayFormat comma' + ); st.end(); }); @@ -714,16 +760,14 @@ test('stringify()', function (t) { }); t.test('Edge cases and unknown formats', function (st) { - ['UFO1234', false, 1234, null, {}, []].forEach( - function (format) { - st['throws']( - function () { - qs.stringify({ a: 'b c' }, { format: format }); - }, - new TypeError('Unknown format option provided.') - ); - } - ); + ['UFO1234', false, 1234, null, {}, []].forEach(function (format) { + st['throws']( + function () { + qs.stringify({ a: 'b c' }, { format: format }); + }, + new TypeError('Unknown format option provided.') + ); + }); st.end(); }); diff --git a/node_modules/side-channel/package.json b/node_modules/side-channel/package.json index 69b8d79..a3e33f6 100644 --- a/node_modules/side-channel/package.json +++ b/node_modules/side-channel/package.json @@ -1,95 +1,67 @@ { - "_from": "side-channel@^1.0.4", - "_id": "side-channel@1.0.4", - "_inBundle": false, - "_integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", - "_location": "/side-channel", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "side-channel@^1.0.4", - "name": "side-channel", - "escapedName": "side-channel", - "rawSpec": "^1.0.4", - "saveSpec": null, - "fetchSpec": "^1.0.4" - }, - "_requiredBy": [ - "/qs" - ], - "_resolved": "https://registry.npmmirror.com/side-channel/-/side-channel-1.0.4.tgz", - "_shasum": "efce5c8fdc104ee751b25c58d4290011fa5ea2cf", - "_spec": "side-channel@^1.0.4", - "_where": "D:\\workbench\\personal\\bnyer-cloud-tiktok\\node_modules\\qs", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com" - }, - "auto-changelog": { - "output": "CHANGELOG.md", - "template": "keepachangelog", - "unreleased": false, - "commitLimit": false, - "backfillLimit": false, - "hideCredit": true - }, - "bugs": { - "url": "https://github.com/ljharb/side-channel/issues" - }, - "bundleDependencies": false, - "dependencies": { - "call-bind": "^1.0.0", - "get-intrinsic": "^1.0.2", - "object-inspect": "^1.9.0" - }, - "deprecated": false, - "description": "Store information about any JS value in a side channel. Uses WeakMap if available.", - "devDependencies": { - "@ljharb/eslint-config": "^17.3.0", - "aud": "^1.1.3", - "auto-changelog": "^2.2.1", - "eslint": "^7.16.0", - "nyc": "^10.3.2", - "safe-publish-latest": "^1.1.4", - "tape": "^5.0.1" - }, - "exports": { - "./package.json": "./package.json", - ".": [ - { - "default": "./index.js" - }, - "./index.js" - ] - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "homepage": "https://github.com/ljharb/side-channel#readme", - "keywords": [ - "weakmap", - "map", - "side", - "channel", - "metadata" - ], - "license": "MIT", - "main": "index.js", - "name": "side-channel", - "repository": { - "type": "git", - "url": "git+https://github.com/ljharb/side-channel.git" - }, - "scripts": { - "lint": "eslint .", - "posttest": "npx aud --production", - "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", - "prepublish": "safe-publish-latest", - "pretest": "npm run lint", - "test": "npm run tests-only", - "tests-only": "nyc tape 'test/**/*.js'", - "version": "auto-changelog && git add CHANGELOG.md" - }, - "version": "1.0.4" + "name": "side-channel", + "version": "1.0.4", + "description": "Store information about any JS value in a side channel. Uses WeakMap if available.", + "main": "index.js", + "exports": { + "./package.json": "./package.json", + ".": [ + { + "default": "./index.js" + }, + "./index.js" + ] + }, + "scripts": { + "prepublish": "safe-publish-latest", + "lint": "eslint .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel.git" + }, + "keywords": [ + "weakmap", + "map", + "side", + "channel", + "metadata" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel/issues" + }, + "homepage": "https://github.com/ljharb/side-channel#readme", + "devDependencies": { + "@ljharb/eslint-config": "^17.3.0", + "aud": "^1.1.3", + "auto-changelog": "^2.2.1", + "eslint": "^7.16.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^1.1.4", + "tape": "^5.0.1" + }, + "dependencies": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } } diff --git a/node_modules/vue-router/CHANGELOG.md b/node_modules/vue-router/CHANGELOG.md deleted file mode 100644 index 78e045f..0000000 --- a/node_modules/vue-router/CHANGELOG.md +++ /dev/null @@ -1,744 +0,0 @@ -## [4.0.15](https://github.com/vuejs/router/compare/v4.0.14...v4.0.15) (2022-05-04) - -### Bug Fixes - -- **matcher:** keep trailing slash on empty optional params ([2f1e9b9](https://github.com/vuejs/router/commit/2f1e9b976d7c5c1ada38c57f276304688d31b7e4)), closes [#1357](https://github.com/vuejs/router/issues/1357) -- setup history listeners once ([faa8562](https://github.com/vuejs/router/commit/faa85624d37367c638fb9272a4130d8524143120)), closes [#1344](https://github.com/vuejs/router/issues/1344) -- **view:** handle @vue/compat automatically ([92becf6](https://github.com/vuejs/router/commit/92becf6dc6c4ef21985abb52887b4cec626f5c82)), closes [#1315](https://github.com/vuejs/router/issues/1315) - -## [4.0.14](https://github.com/vuejs/router/compare/v4.0.13...v4.0.14) (2022-03-10) - -### Features - -- **devtools:** use api.now() ([06ac7bb](https://github.com/vuejs/router/commit/06ac7bbc4caaacaf8f054aa2ee164517b99b18ba)) - -## [4.0.13](https://github.com/vuejs/router/compare/v4.0.12...v4.0.13) (2022-02-28) - -### Bug Fixes - -- **matcher:** add child before parent when using `addRoute` ([8744bba](https://github.com/vuejs/router/commit/8744bbae7789e236e5308f939fb4b2d946a8ca6d)) -- **ssr:** reject unfinished initial navigation ([509fc0d](https://github.com/vuejs/router/commit/509fc0d5c78b32cbd5ce0c86f716774ad6163cad)), closes [#1305](https://github.com/vuejs/router/issues/1305) - -## [4.0.12](https://github.com/vuejs/router/compare/v4.0.11...v4.0.12) (2021-10-14) - -### Bug Fixes - -- **history:** ensure base is normalized in memory history ([#1112](https://github.com/vuejs/router/issues/1112)) ([198a5bd](https://github.com/vuejs/router/commit/198a5bda8354ea6c3121f5fbf92ed93390e70cfb)) - -### Features - -- **devtools:** display router view path ([3ce3834](https://github.com/vuejs/router/commit/3ce383402fbaa1539cdfe32cbdd48dfda5fbfa7b)), closes [#1119](https://github.com/vuejs/router/issues/1119) -- **warn:** improve message for onBeforeRoute\*() ([7d5230e](https://github.com/vuejs/router/commit/7d5230e556002b6ddd17c857ad43608590e9a7bd)) - -## [4.0.11](https://github.com/vuejs/router/compare/v4.0.10...v4.0.11) (2021-08-09) - -### Bug Fixes - -- **query:** empty object with custom stringify ([4dd2fbf](https://github.com/vuejs/router/commit/4dd2fbfeb486800a7d5fbc384eb567c3c6532f41)) -- **router:** allow null | undefined for params ([ebca15a](https://github.com/vuejs/router/commit/ebca15a0140453c6671fdae7a9864badc650531e)) -- **router:** invalidate ongoing navigation when unmounting ([d8fb7d0](https://github.com/vuejs/router/commit/d8fb7d0ab1694fe86edbd52668f84fb9bb9f4dcf)) -- **types:** Support `undefined` in NavigationGuardNext ([#1059](https://github.com/vuejs/router/issues/1059)) ([6cce232](https://github.com/vuejs/router/commit/6cce232ba0dc5d89f6a53c1af674a8e0c6eb8790)) - -## [4.0.10](https://github.com/vuejs/router/compare/v4.0.9...v4.0.10) (2021-06-21) - -### Features - -- **devtools:** display components using `useLink()` ([aab8c04](https://github.com/vuejs/router/commit/aab8c0414af6784fc0250fb4b81be4186ff4cfec)), closes [#1003](https://github.com/vuejs/router/issues/1003) -- **link:** expose useLink on RouterLink as internal ([#1002](https://github.com/vuejs/router/issues/1002)) ([57b1468](https://github.com/vuejs/router/commit/57b1468645248068c76b809efd10f3f42762d52b)) - -## [4.0.9](https://github.com/vuejs/router/compare/v4.0.8...v4.0.9) (2021-06-16) - -### Bug Fixes - -- **guards:** propagate lazy loading rejections ([3d465cc](https://github.com/vuejs/router/commit/3d465cc128b2f5c109e71386760c7b99e3d71bce)) -- **hash:** force navigation restore on manual navigation ([#921](https://github.com/vuejs/router/issues/921)) ([e08a0d0](https://github.com/vuejs/router/commit/e08a0d0b64d2798164895da430de7edbb66d7ead)), closes [#916](https://github.com/vuejs/router/issues/916) -- **link:** catch errors ([e7b2156](https://github.com/vuejs/router/commit/e7b2156c7436f18d1a08694f502eb00b10029f1c)) -- **query:** allow arbitrary keys in queries ([a57b5f1](https://github.com/vuejs/router/commit/a57b5f179b8859776550f3b754f972fad8955566)), closes [#880](https://github.com/vuejs/router/issues/880) -- **warn:** drop unused params on string redirect ([bed24df](https://github.com/vuejs/router/commit/bed24dff90c19a0ee3e335dbe43ed9ddbfc74542)), closes [#951](https://github.com/vuejs/router/issues/951) - -### Features - -- **devtools:** group navigation errors ([a776a84](https://github.com/vuejs/router/commit/a776a8402b7ae5bdc017409f26d4574bcee4858b)) -- **errors:** add to and from to router.onError()` ([c76feab](https://github.com/vuejs/router/commit/c76feabf3703f06bff400d7aa84edede48329b82)) -- **errors:** log errors when no error handlers ([46a354e](https://github.com/vuejs/router/commit/46a354ec5b9359bb1dcd3ac82716e898b3843ae4)) - -## [4.0.8](https://github.com/vuejs/router/compare/v4.0.6...v4.0.8) (2021-05-13) - -This release is a correct tag and doesn't contain any extra changes. - -## [4.0.7](https://github.com/vuejs/router/compare/v4.0.6...v4.0.7) (2021-05-13) - -### Bug Fixes - -- **$route:** Make $route have an enumerable type ([#912](https://github.com/vuejs/router/issues/912)) ([d90520e](https://github.com/vuejs/router/commit/d90520eb36ca310f52b22caeb88fd8cb06dca04a)) -- **devtools:** stabilize record id ([#897](https://github.com/vuejs/router/issues/897)) ([c6460f0](https://github.com/vuejs/router/commit/c6460f09aab3a834121dc58fc5880c81a65147ef)) -- **history:** make properties enumerable ([8e6ebdf](https://github.com/vuejs/router/commit/8e6ebdf75adc1ab662e46835c5b7f078bc68a93b)) -- **history:** proper destroy in memory history ([9d188aa](https://github.com/vuejs/router/commit/9d188aa165aeb12aa3771aaa56a269f5dad3ccf6)) -- **query:** filter undefined values in arrays ([df25fb5](https://github.com/vuejs/router/commit/df25fb5c34ae4a1540d375ad078705719b56332b)) -- **query:** prevent trailing & in query ([#935](https://github.com/vuejs/router/issues/935)) ([885bb06](https://github.com/vuejs/router/commit/885bb06bb590944f2e58176151f7b7a6acbc1b4e)) -- do not allow invalid hazardous keys in query ([#880](https://github.com/vuejs/router/issues/880)) ([ecd52e0](https://github.com/vuejs/router/commit/ecd52e017ac30fa996d4796974371374f65640d1)) - -## [4.0.6](https://github.com/vuejs/router/compare/v4.0.5...v4.0.6) (2021-04-06) - -### Bug Fixes - -- **link:** let vue merge attrs ([4142871](https://github.com/vuejs/router/commit/4142871189dbb13e1ce2d6be8d82bd5aa27526a3)), closes [#846](https://github.com/vuejs/router/issues/846) -- **link:** use flush post in devtools watcher ([4108814](https://github.com/vuejs/router/commit/41088143c62244fe7b198e0907f4f6f98852df62)), closes [#845](https://github.com/vuejs/router/issues/845) - -### Features - -- **types:** allow currentLocation param in resolve ([add6ce9](https://github.com/vuejs/router/commit/add6ce9677ffd2c636e215ffab5ddbdef22b0158)) -- **warn:** throws if history is missing ([#844](https://github.com/vuejs/router/issues/844)) ([dd8bf6c](https://github.com/vuejs/router/commit/dd8bf6cf48db352cef72f419a14d1540818eb6ff)) - -## [4.0.5](https://github.com/vuejs/router/compare/v4.0.4...v4.0.5) (2021-03-11) - -### Bug Fixes - -- **guards:** avoid enter guards between aliases ([0048b9b](https://github.com/vuejs/router/commit/0048b9b1b0fd0a0652fdabb683309fc5c0d5dbe4)) -- **guards:** ensure beforeRouteUpdate works with aliases ([#819](https://github.com/vuejs/router/issues/819)) ([45ecb20](https://github.com/vuejs/router/commit/45ecb205920be60c9b454dbb55cf4fe213bbc697)), closes [#805](https://github.com/vuejs/router/issues/805) -- **view:** correctly reuse instance guards ([#795](https://github.com/vuejs/router/issues/795)) ([d4fde59](https://github.com/vuejs/router/commit/d4fde599803a1be9d4823de0e406c9ce66143e2c)) - -### Features - -- **devtools:** group navigations ([d3b5dfb](https://github.com/vuejs/router/commit/d3b5dfb6d8a3da96ee93426dc4b5429581e8a739)) - -## [4.0.4](https://github.com/vuejs/router/compare/v4.0.3...v4.0.4) (2021-02-19) - -### Bug Fixes - -- **devtools:** id and label ([#742](https://github.com/vuejs/router/issues/742)) ([d034307](https://github.com/vuejs/router/commit/d034307444860fb834b0f5b5a1ddd0cce9d6d842)) -- **guards:** vue-class-component call guards on first... ([#755](https://github.com/vuejs/router/issues/755)) ([06f942d](https://github.com/vuejs/router/commit/06f942d0fbe1c5c86dc7e17d38c00d595854bd4f)) -- **matcher:** force leading slash with optional param in multi segments ([11c882f](https://github.com/vuejs/router/commit/11c882f8f3b56d2c87fc095c46eb8050fbbf61df)) -- **warn:** should not warn missing optional params in aliases ([92f8901](https://github.com/vuejs/router/commit/92f8901f54775cb4b3d1f2415b6a2b3ff77eb440)) - -### Features - -- **types:** make meta type safe with unknown ([eef0472](https://github.com/vuejs/router/commit/eef0472e3589ed0a6df0528a7b96f1d7bf316843)) - -## [4.0.3](https://github.com/vuejs/router/compare/v4.0.2...v4.0.3) (2021-01-11) - -### Bug Fixes - -- **hash:** allow base tag different from base parameter ([85b1bff](https://github.com/vuejs/router/commit/85b1bff96fbb6e21cd556b688f6085b6fbfe993f)), closes [#685](https://github.com/vuejs/router/issues/685) -- **link:** use replace prop ([6edba5c](https://github.com/vuejs/router/commit/6edba5cf676bde94e5ebdb370a4146dc8f6b058e)), closes [#702](https://github.com/vuejs/router/issues/702) - -### Features - -- **types:** expose RouteParamsRaw ([09bbc89](https://github.com/vuejs/router/commit/09bbc895cd422af8354664062b29131ae32472d7)) -- **warn:** more specific warnings ([2cd8d86](https://github.com/vuejs/router/commit/2cd8d867beda6f7c54578d40934774547866e069)) -- **warn:** warn defineAsyncComponent usage in routes ([#682](https://github.com/vuejs/router/issues/682)) ([9520d66](https://github.com/vuejs/router/commit/9520d66112c0f2922f4284cda1e75b316ddf3488)) - -## [4.0.2](https://github.com/vuejs/router/compare/v4.0.1...v4.0.2) (2020-12-27) - -### Bug Fixes - -- **matcher:** clear customRe after consuming buffer ([#680](https://github.com/vuejs/router/issues/680)) ([4c0b825](https://github.com/vuejs/router/commit/4c0b82507e1f949d55daffd06756615cd704e090)), closes [#679](https://github.com/vuejs/router/issues/679) -- **router:** allow replace to have query and hash ([6a8ccb6](https://github.com/vuejs/router/commit/6a8ccb6e3b80aef00dda7e73be2afb433d871a32)), closes [#668](https://github.com/vuejs/router/issues/668) -- **router:** do not restore history when ... ([db267be](https://github.com/vuejs/router/commit/db267be72bace7c99a0c65669ab04ce770e1532c)), closes [#662](https://github.com/vuejs/router/issues/662) -- **router-view:** disable inheritAttrs ([1e58574](https://github.com/vuejs/router/commit/1e58574e6175f591f7fb24bcfc6e11045e7b0148)), closes [#674](https://github.com/vuejs/router/issues/674) -- **types:** add missing exported types ([034c71c](https://github.com/vuejs/router/commit/034c71c72ca46d242daf53ae54ab67e6f7800f91)) -- spread operator compatible ([a2f3e91](https://github.com/vuejs/router/commit/a2f3e91cb3e3ae61118d803ce938d6f4eea76116)) - -## [4.0.1](https://github.com/vuejs/router/compare/v4.0.0...v4.0.1) (2020-12-07) - -### Bug Fixes - -- **build:** rollback rollup plugin commonjs ([9486950](https://github.com/vuejs/router/commit/9486950f3399bda34ab2840b83fd123ac5ce7ce9)) - -# [4.0.0](https://github.com/vuejs/router/compare/v4.0.0-rc.6...v4.0.0) (2020-12-07) - -### Bug Fixes - -- **router-view:** properly use route prop when nested ([b74051a](https://github.com/vuejs/router/commit/b74051a6bde7524d1a7cc6cc1daacb213987faa0)) -- **router-view:** return one node when possible ([d18e500](https://github.com/vuejs/router/commit/d18e500da2ed017be30871628a5cc59324bec15c)), closes [#537](https://github.com/vuejs/router/issues/537) - -### Features - -- expose routerViewLocationKey as internal ([f498646](https://github.com/vuejs/router/commit/f498646c3bc2ad480be7a3d0f11aa11710729911)) - -# [4.0.0-rc.6](https://github.com/vuejs/router/compare/v4.0.0-rc.5...v4.0.0-rc.6) (2020-11-30) - -### Bug Fixes - -- **guards:** correctly reuse guards ([#616](https://github.com/vuejs/router/issues/616)) ([95d44c8](https://github.com/vuejs/router/commit/95d44c8ff2a961e052fd67b2160b87fb32d0ffb4)), closes [#614](https://github.com/vuejs/router/issues/614) - -### Features - -- **devtools:** improve active + match in routes inspector ([9f59489](https://github.com/vuejs/router/commit/9f59489f04cedfca5ba55da019b2dc790e926fd7)) -- **types:** expose `LocationQueryValueRaw` as internal ([dc02850](https://github.com/vuejs/router/commit/dc028500c3e931ed5fd6beedf58b5425f5115b52)) - -# [4.0.0-rc.5](https://github.com/vuejs/router/compare/v4.0.0-rc.4...v4.0.0-rc.5) (2020-11-21) - -### Features - -- **scroll:** allow modifying scrollBehavior in options ([#602](https://github.com/vuejs/router/issues/602)) ([d6651f5](https://github.com/vuejs/router/commit/d6651f5f954c8ecaf1a77ec209d5aba06343e867)) - -# [4.0.0-rc.4](https://github.com/vuejs/router/compare/v4.0.0-rc.3...v4.0.0-rc.4) (2020-11-20) - -### Features - -- expose symbols as internals ([ef62d96](https://github.com/vuejs/router/commit/ef62d9645c456f069699480ae3f2c3dd97b9d30d)) - -# [4.0.0-rc.3](https://github.com/vuejs/router/compare/v4.0.0-rc.2...v4.0.0-rc.3) (2020-11-14) - -### Bug Fixes - -- trigger redirect on popstate ([#592](https://github.com/vuejs/router/issues/592)) ([18dbdc2](https://github.com/vuejs/router/commit/18dbdc2745cf7bd2516d4576a8d6a21de78516ec)) -- **query:** encode space as + ([4d3dd5f](https://github.com/vuejs/router/commit/4d3dd5fd523cefc675aa7e61ed9b06b66e42b80c)), closes [#561](https://github.com/vuejs/router/issues/561) - -# [4.0.0-rc.2](https://github.com/vuejs/router/compare/v4.0.0-rc.1...v4.0.0-rc.2) (2020-11-05) - -### Features - -- expose injection symbols as internals ([0056aca](https://github.com/vuejs/router/commit/0056aca5b251df2a18bab79e18874a18e0204b4d)) -- **devtools:** add devtools plugin ([894d50d](https://github.com/vuejs/router/commit/894d50d351a40df95a3227840f5485f7e8b90432)) -- **devtools:** add more ([ee07302](https://github.com/vuejs/router/commit/ee0730254522d6162114968e4d62b93e8b6f7f93)) -- **devtools:** better search ([5d68a29](https://github.com/vuejs/router/commit/5d68a29386f34363b38c4138fbeae01ec538285e)) -- **devtools:** support multiple router instances ([2e5d0d4](https://github.com/vuejs/router/commit/2e5d0d4d726ee6329745f34ca463a74820c5aa29)) - -# [4.0.0-rc.1](https://github.com/vuejs/router/compare/v4.0.0-beta.13...v4.0.0-rc.1) (2020-10-23) - -### Features - -- **warn:** improve warning for invalid components ([5985b65](https://github.com/vuejs/router/commit/5985b6560d40412d67311df10343ee6a119a0535)), closes [#517](https://github.com/vuejs/router/issues/517) - -# [4.0.0-beta.13](https://github.com/vuejs/router/compare/v4.0.0-beta.12...v4.0.0-beta.13) (2020-10-02) - -### Bug Fixes - -- **encoding:** decode hash in string location ([11acb3d](https://github.com/vuejs/router/commit/11acb3dea072592f00a23b912d39c3fcf72dc6c3)) -- **encoding:** differentiate keys and values in query ([a967e42](https://github.com/vuejs/router/commit/a967e427ab3bc5c1e6236b01f484a87b74a92be1)) -- **encoding:** keep decoded hash when resolving ([1a8ffc1](https://github.com/vuejs/router/commit/1a8ffc19b0d2bfc17daec4cb04b96d174c73dd9d)) -- **hash:** only pushState the hash part ([2a14c19](https://github.com/vuejs/router/commit/2a14c19e4f0313996fd075a6821f85d30c5cad66)), closes [#495](https://github.com/vuejs/router/issues/495) - -### Features - -- **warn:** help migrating catch all routes ([14e1eb9](https://github.com/vuejs/router/commit/14e1eb96485f74669f582a87f522d3b13b567c9c)) -- print errors from lazy loading ([f6db91a](https://github.com/vuejs/router/commit/f6db91aaf496b85c80e74727575cc1c2b1d06282)), closes [#497](https://github.com/vuejs/router/issues/497) - -# [4.0.0-beta.12](https://github.com/vuejs/router/compare/v4.0.0-beta.11...v4.0.0-beta.12) (2020-09-25) - -### Bug Fixes - -- **types:** extend @vue/runtime-core module ([#473](https://github.com/vuejs/router/issues/473)) ([556cd4b](https://github.com/vuejs/router/commit/556cd4b4af3d7ac1aa1c66848f5ab1bc33d13153)) - -# [4.0.0-beta.11](https://github.com/vuejs/router/compare/v4.0.0-beta.10...v4.0.0-beta.11) (2020-09-20) - -### Bug Fixes - -- use post flush in modal example ([2024281](https://github.com/vuejs/router/commit/2024281902d62454d9159c87d4288d691cd0bce8)) -- **guards:** use post watcher for instances ([3234c59](https://github.com/vuejs/router/commit/3234c5924f39fd9497866bfd160407256dc91bfe)) - -# [4.0.0-beta.10](https://github.com/vuejs/router/compare/v4.0.0-beta.9...v4.0.0-beta.10) (2020-09-18) - -### Bug Fixes - -- **history:** gracefully handle empty state ([cbcf2a9](https://github.com/vuejs/router/commit/cbcf2a95a2af001c8aea96f3c76c4c4ef139219f)), closes [#366](https://github.com/vuejs/router/issues/366) -- **types:** better type for navigate ([0384cb0](https://github.com/vuejs/router/commit/0384cb062d50f6be37512410b4c2d170896dc9cb)) -- **types:** explicit types on navigate ([36d218c](https://github.com/vuejs/router/commit/36d218c15268d0d3d15d4ed3adc75c8cb09ed68b)) -- **types:** fix types for redirect records ([a77f148](https://github.com/vuejs/router/commit/a77f1485323ef3b654077ecb227fd5a0373d3a2f)) -- **warn:** correctly warn against unused next ([47cd7b9](https://github.com/vuejs/router/commit/47cd7b97bb7a3999178a26a4ca1af955178ea5d6)) - -### Code Refactoring - -- **types:** Rename ScrollBehavior to RouterScrollBehavior ([9fc0996](https://github.com/vuejs/router/commit/9fc09969db854bc0201454fbecd546637b76213a)) - -### Features - -- **router:** remove partial Promise from router.go ([6ed6eee](https://github.com/vuejs/router/commit/6ed6eee38b59eb0b6dec0bcb7d73e24203e20ba4)) -- **types:** allow extending meta fields ([#407](https://github.com/vuejs/router/issues/407)) ([706e84f](https://github.com/vuejs/router/commit/706e84f0099a2a04485dfa98449fdc875442bb49)) -- **warn:** point to scrollBehavior in message ([70ce7fe](https://github.com/vuejs/router/commit/70ce7feefac3fddd2a9641fcc2ccc66b4b108775)) - -### BREAKING CHANGES - -- **router:** The `router.go()` methods doesn't return anything - (like in Vue Router 3) anymore. The existing implementation was wrong as it - would resolve the promise for the following navigation if `router.go()` - was called with something that wasn't possible e.g. `router.go(-20)` - right after entering the application would not do anything. Even worse, - the promise returned by that call would resolve **after the next - navigation**. There is no proper native API to implement this - promise-based api properly, but one can write a version that should work - in most scenarios by setting up multiple hooks right before calling - `router.go()`: - -```js -export function go(delta) { - return new Promise((resolve, reject) => { - function popStateListener() { - clearTimeout(timeout) - } - window.addEventListener('popstate', popStateListener) - - function clearHooks() { - removeAfterEach() - removeOnError() - window.removeEventListener('popstate', popStateListener) - } - - // if the popstate event is not called, consider this a failure - const timeout = setTimeout(() => { - clearHooks() - reject(new Error('Failed to use router.go()')) - // It's unclear of what value would always work here - }, 10) - - setImmediate - - const removeAfterEach = router.afterEach((_to, _from, failure) => { - clearHooks() - resolve(failure) - }) - const removeOnError = router.onError(err => { - clearHooks() - reject(err) - }) - - router.go(delta) - }) -} -``` - -- **types:** there is already an existing type named `ScrollBehavior`, - so we are renaming our type to avoid any confusions and allow the user - to use both types at the same type (which given what the existing - `ScrollBehavior` type is designed for, will likely happen). - -# [4.0.0-beta.9](https://github.com/vuejs/router/compare/v4.0.0-beta.8...v4.0.0-beta.9) (2020-09-01) - -Build related fixes - -# [4.0.0-beta.8](https://github.com/vuejs/router/compare/v4.0.0-beta.7...v4.0.0-beta.8) (2020-09-01) - -### Bug Fixes - -- **router-view:** reuse saved instances in different records ([#446](https://github.com/vuejs/router/issues/446)) ([6554171](https://github.com/vuejs/router/commit/65541718b0d5af665fd87dc0e48770cba832a2bb)) -- **types:** add HTML attributes for JSX ([06f3f8f](https://github.com/vuejs/router/commit/06f3f8fd7c3a32da331802fe5d3d19ced17200a3)), closes [#435](https://github.com/vuejs/router/issues/435) -- **types:** allow components defined via defineComponent ([#421](https://github.com/vuejs/router/issues/421)) ([e47c84c](https://github.com/vuejs/router/commit/e47c84c74a97ae7bb9095ea75f98a6fa8a216532)) - -### BREAKING CHANGES - -- **router-view:** `onBeforeRouteLeave` and `onBeforeRouteUpdate` used to - have access to the component instance through `instance.proxy` but given - that: - 1. It has been marked as `internal` (https://github.com/vuejs/vue-next/pull/1849) - 2. When using `setup`, all variables are accessible on the scope (and - should be accessed that way because the code minimizes better) - It has been removed to prevent wrong usage and lighten Vue Router - -# [4.0.0-beta.7](https://github.com/vuejs/router/compare/v4.0.0-beta.6...v4.0.0-beta.7) (2020-08-19) - -### Bug Fixes - -- **encoding:** encode partial params ([eb04117](https://github.com/vuejs/router/commit/eb041175c02ab0dac093823574a85bbbbf2056eb)) -- **matcher:** avoid trailing slash with optional params ([faf0aab](https://github.com/vuejs/router/commit/faf0aab6451848e5b4330e1d01033137a0c42a5a)) -- **types:** append declare module ([50ad404](https://github.com/vuejs/router/commit/50ad404ae45086f051b01ac552e4a3ab98535633)), closes [#419](https://github.com/vuejs/router/issues/419) -- **vetur:** update tags/attributes definition ([#408](https://github.com/vuejs/router/issues/408)) ([df8b2b1](https://github.com/vuejs/router/commit/df8b2b140155d1e4ad5d00cd17d57ab2046a75e2)) - -### Features - -- **warn:** warn against infinite redirections ([e3dcc8d](https://github.com/vuejs/router/commit/e3dcc8d9477e17f9b92e22787b750edc4658b77a)) - -# [4.0.0-beta.6](https://github.com/vuejs/router/compare/v4.0.0-beta.5...v4.0.0-beta.6) (2020-08-05) - -### Bug Fixes - -- **router:** stack overflow with redirect ([3594011](https://github.com/vuejs/router/commit/359401107078348f0410abbd36cffb3b8d4d8f85)), closes [#404](https://github.com/vuejs/router/issues/404) - -### Features - -- **router-link:** add ariaCurrentValue prop ([23e6e9c](https://github.com/vuejs/router/commit/23e6e9c10b4f9cb9f074ebb4f56d2d99acac9097)) -- add Vetur support ([1f1189f](https://github.com/vuejs/router/commit/1f1189fd23dc6ec318edd5d7e8f225b467d4d386)), closes [#381](https://github.com/vuejs/router/issues/381) - -# [4.0.0-beta.5](https://github.com/vuejs/router/compare/v4.0.0-beta.4...v4.0.0-beta.5) (2020-08-03) - -### Features - -- resolve simple relative links ([af1deaa](https://github.com/vuejs/router/commit/af1deaab5e0fd1597a7cf7ee9a6d01cac507970d)) -- **url:** simple resolve relative location ([69c44db](https://github.com/vuejs/router/commit/69c44db3fd5363a833675b4b0ef14f97ac691af6)) -- **warn:** warn if guard returns without calling next ([6e16bdd](https://github.com/vuejs/router/commit/6e16bdd6338ea3b7da1f8a0b3000ec880be840d6)) - -# [4.0.0-beta.4](https://github.com/vuejs/router/compare/v4.0.0-beta.3...v4.0.0-beta.4) (2020-07-25) - -### Bug Fixes - -- **router-view:** render the slot when there is no match ([bae42d4](https://github.com/vuejs/router/commit/bae42d41c2240947e5b649e568cad274214c6346)), closes [#385](https://github.com/vuejs/router/issues/385) -- work on Edge by adding an argument to catch ([#383](https://github.com/vuejs/router/issues/383)) ([9580bea](https://github.com/vuejs/router/commit/9580bead1f03f1be95473e965daa1f1ee78921f3)) - -# [4.0.0-beta.3](https://github.com/vuejs/router/compare/v4.0.0-beta.2...v4.0.0-beta.3) (2020-07-21) - -### Bug Fixes - -- **guards:** call beforeRouteEnter once per named view ([f2846ff](https://github.com/vuejs/router/commit/f2846ff2a0796e58a9b04593909f7a30b7b68bb1)) -- **guards:** remove registered update guards after leaving ([41bffda](https://github.com/vuejs/router/commit/41bffda49c24d560cfe555aa88bcebbbd1d03d68)) -- **guards:** skip update and leave guards of unmounted views ([f22e70a](https://github.com/vuejs/router/commit/f22e70a6d15ce9834c9eb841d9fe9547c5d21e24)) -- **hash:** allow url to contain search params before hash ([ae8b289](https://github.com/vuejs/router/commit/ae8b28934b1c9a092174ebd6fb5aa10aefe1de44)), closes [#378](https://github.com/vuejs/router/issues/378) - -### Features - -- **errors:** export isNavigationFailure ([28a9b25](https://github.com/vuejs/router/commit/28a9b25d976c325d3193cada8034a6e42297e665)) -- **guards:** allow guards to return a value instead of calling next ([#343](https://github.com/vuejs/router/issues/343)) ([5cb209f](https://github.com/vuejs/router/commit/5cb209f3bb53ac0ddf62152f695da610facf4724)) -- **guards:** wip context support in multi apps ([34d7390](https://github.com/vuejs/router/commit/34d7390b946644a128ab6fd03fd821a91fd4782c)) - -# [4.0.0-beta.2](https://github.com/vuejs/router/compare/v4.0.0-beta.1...v4.0.0-beta.2) (2020-07-07) - -Fix build cache issues - -# [4.0.0-beta.1](https://github.com/vuejs/router/compare/v4.0.0-alpha.14...v4.0.0-beta.1) (2020-07-03) - -### Bug Fixes - -- **hash:** manual changes should trigger a navigation ([93891ab](https://github.com/vuejs/router/commit/93891abf02fc24d66c6f43926a28f275560fb714)), closes [#346](https://github.com/vuejs/router/issues/346) -- **router-link:** add missing prop custom in jsx ([c6274ae](https://github.com/vuejs/router/commit/c6274aeaf5ad4ba4f97c82aad3e1819ef20f5d69)) -- **router-view:** preserve keep-alive route guard this context ([#344](https://github.com/vuejs/router/issues/344)) ([994c073](https://github.com/vuejs/router/commit/994c073fd90add30bf16b5268332277f8b082a74)) -- **warn:** warn when RouterView is wrapped with transition ([e4b3fbe](https://github.com/vuejs/router/commit/e4b3fbe8b799b6621537afe365267a18eab9d3cd)) - -### Code Refactoring - -- **history:** simplify location as a string ([10a071c](https://github.com/vuejs/router/commit/10a071c85c62b6674929162aa36220bd8c167f27)) -- **router:** remove history property ([aba3a3f](https://github.com/vuejs/router/commit/aba3a3f3a0d860f76d75938ae09616a329c7c13c)) - -### Features - -- **guards:** next callback beforeRouteEnter ([d9dad0b](https://github.com/vuejs/router/commit/d9dad0b9467fee9478406899043ee35f30cdf1fb)) - -### BREAKING CHANGES - -- **router:** the history property was marked as internal already. Since we - need to pass the history instance to the router, we always have access to it, - differently from Vue Router 3 where the history was instantiated internally. - The history API was also internal (it wasn't documented), so this change - shouldn't be a problem as people shouldn't be relying on `router.history` in - their apps. If you think this property is needed, please open an issue to - discuss the use case. Note it's already accessible as you have to create it: - -```js -export const history = createWebHistory() -export const router = createRouter({ history, routes: [] }) -``` - -- **history:** HistoryLocation is just a string now. It was pretty much an - internal property but it could be used inside `history.state`. It used to be an - object `{ fullPath: '/the-url' }`. And it's now just the `fullPath` property. - -# [4.0.0-alpha.14](https://github.com/vuejs/router/compare/v4.0.0-alpha.13...v4.0.0-alpha.14) (2020-07-01) - -### Bug Fixes - -- **hash:** use relative links in hash mode ([32c9590](https://github.com/vuejs/router/commit/32c9590db89e69c8f7c61905a5eaf19df2054e42)), closes [#342](https://github.com/vuejs/router/issues/342) -- **query:** do not normalize query with custom stringifyQuery ([ea65066](https://github.com/vuejs/router/commit/ea65066e8511d8320ad8de37b32ea9a8028fa9d5)), closes [#328](https://github.com/vuejs/router/issues/328) -- **query:** isSameRouteLocation compares queries by string ([6e1f0ea](https://github.com/vuejs/router/commit/6e1f0eacf60c7e3d465dd0af68f79dc649269b17)), closes [#328](https://github.com/vuejs/router/issues/328) - -### Features - -- **redirect:** allow redirect on routes witch children ([e57b875](https://github.com/vuejs/router/commit/e57b875dd9d375778a847627434803f4ec79a818)) -- **router:** support multiple apps at the same time ([565ec9d](https://github.com/vuejs/router/commit/565ec9d489b4aad347ee466b781ca85aff76bf2d)) - -# [4.0.0-alpha.13](https://github.com/vuejs/router/compare/v4.0.0-alpha.12...v4.0.0-alpha.13) (2020-06-18) - -### Bug Fixes - -- allow arbitrary selectors starting with # ([14b859d](https://github.com/vuejs/router/commit/14b859dfa6fa5ccefe42c6f834ddd24dd9921a1b)) -- use assign to align with Vue browser support ([#311](https://github.com/vuejs/router/issues/311)) ([f80b670](https://github.com/vuejs/router/commit/f80b670d4dac30323221fcb2f93137ffd874c51b)), closes [#304](https://github.com/vuejs/router/issues/304) -- **hash:** use location.pathname ([0078147](https://github.com/vuejs/router/commit/007814745dd98bb8cfa53f44d5c308193b2fbb60)), closes [#261](https://github.com/vuejs/router/issues/261) -- **matcher:** correct check when removing existing records on add ([2c267f5](https://github.com/vuejs/router/commit/2c267f5aceec899c84514571e4fa75dc61441ed4)) -- **matcher:** override records by name when adding ([07100fc](https://github.com/vuejs/router/commit/07100fc1386fb636da3eb1c8196a36f6538eb91f)) -- **scroll:** avoid reusing scroll position ([dfc1fb3](https://github.com/vuejs/router/commit/dfc1fb34a761138a3390ccd5a8a042863018222a)) - -### Features - -- **scroll:** allow passing behavior option ([12e9209](https://github.com/vuejs/router/commit/12e92094df46129ddf75d0fa8e3d9816644200de)) -- **scroll:** replace selector with el ([ab8a01c](https://github.com/vuejs/router/commit/ab8a01c0a6eda1bafc293b39cb6c77ed10fb359e)) -- **warn:** warn if component is a promise ([4b2bfa8](https://github.com/vuejs/router/commit/4b2bfa80cd3440441d71e690ca85d0532a4b8428)) -- **warn:** warn when routes are not found ([#279](https://github.com/vuejs/router/issues/279)) ([d125356](https://github.com/vuejs/router/commit/d125356e0f67f906f5f602f0b485f9e1e4f5bf51)) -- allow props for named views ([dbe2344](https://github.com/vuejs/router/commit/dbe2344af5fed39aa4aa8fbfe48b195580d9538b)) -- **warn:** warn multiple params with same name ([5c8cd6e](https://github.com/vuejs/router/commit/5c8cd6e8ae1223e9871252cc617b19424f01c5c2)) - -### BREAKING CHANGES - -- **scroll:** this change follows the RFC at - https://github.com/vuejs/rfcs/pull/176: - -* `selector` is renamed into `el` -* `el` also accepts an `Element` -* `left` and `top` are passed along `el` instead of inside an object - passed as `offset` - -- **scroll:** `scrollBehavior` doesn't accept an object with `x` and `y` - coordinates anymore. Instead it accepts an object like - [`ScrollToOptions`](https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions) - with `left` and `top` properties. You can now also pass the - [`behavior`](https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions/behavior) - property to enable smooth scrolling in most browsers. -- It is now necessary to escape id selectors like - explained at https://mathiasbynens.be/notes/css-escapes. This was - necessary to allow selectors like `#container > child`. - -# [4.0.0-alpha.12](https://github.com/vuejs/router/compare/v4.0.0-alpha.11...v4.0.0-alpha.12) (2020-05-19) - -### Bug Fixes - -- **hash:** allow base with non trailing slash ([f5cc050](https://github.com/vuejs/router/commit/f5cc0505f9e0cc30ff94e362ceb24d300afd684d)), closes [#247](https://github.com/vuejs/router/issues/247) -- prevent error on initial navigation to //invalid ([e72e4ba](https://github.com/vuejs/router/commit/e72e4ba1cc7b80aa44d3958db259d9e3a351d0fd)) - -### Features - -- **warn:** warn multiple leading slashes ([87c5e53](https://github.com/vuejs/router/commit/87c5e53b43c218c83f9db986ac7538d74525ea5b)) - -### BREAKING CHANGES - -- **hash:** When providing a base for hash histories, it is now necessary - to include a trailing slash to create a url that starts with `/#/`, otherwise it - will result in a url starting with `#/`. This allows users to use the routing - system directly in simple files without needing to configure a server at all: - - `https://example.com/file.html` + `base: 'file.html` will produce a final - url of `https://example.com/file.html#/` - - `https://example.com/folder` + `base: 'folder` will produce a final url of - `https://example.com/folder#/` - - `https://example.com/folder` + `base: 'folder/` will produce a final url of - `https://example.com/folder/#/` - -# [4.0.0-alpha.11](https://github.com/vuejs/router/compare/v4.0.0-alpha.10...v4.0.0-alpha.11) (2020-05-12) - -### Bug Fixes - -- **scroll:** change scrollRestoration if scrollBehavior is provided ([5cf2e61](https://github.com/vuejs/router/commit/5cf2e611de2477e92699121573cb162ff98a7b8d)) -- match base in a non-sensitive way ([7087bbc](https://github.com/vuejs/router/commit/7087bbc9c479f2955381d8a823a3ef8f9eed7b5a)) -- **router:** allow multiple router instance ([24d3d49](https://github.com/vuejs/router/commit/24d3d49babcdea751f4c4e7e9a87625f8744a122)) -- **router:** unique first navigation with multi app ([33172af](https://github.com/vuejs/router/commit/33172aff03b7c302699753a8abe5750094bdde26)) - -### Features - -- **types:** export NavigationGuardNext ([#229](https://github.com/vuejs/router/issues/229)) ([888bf4d](https://github.com/vuejs/router/commit/888bf4df33d718d74e5835e99d0f1ac4ce3a0ccf)) -- explicit injection symbols in dev mode ([#228](https://github.com/vuejs/router/issues/228)) ([fab88ee](https://github.com/vuejs/router/commit/fab88ee261c49b739545918deab583757aab561e)) -- support jsx and tsx for RouterLink and RouterView ([1d3dce3](https://github.com/vuejs/router/commit/1d3dce3106af700fc95a403f1c229644fe8d85b8)), closes [#226](https://github.com/vuejs/router/issues/226) -- **router:** allow functional components for routes ([096d864](https://github.com/vuejs/router/commit/096d86498e954345c6bd4d8e82fe54c37d3f869b)) -- **scroll:** scroll to the same location like regular links ([5f22d4f](https://github.com/vuejs/router/commit/5f22d4fa39171906802cc20ada00ec57bdfce880)) -- **warn:** warn if next was called multiple times ([dce2612](https://github.com/vuejs/router/commit/dce2612e495b1d5789cd993a54d24599967a8cf4)) - -# [4.0.0-alpha.10](https://github.com/vuejs/router/compare/v4.0.0-alpha.9...v4.0.0-alpha.10) (2020-05-05) - -### Bug Fixes - -- **scroll:** do not restore on push ([3f79195](https://github.com/vuejs/router/commit/3f7919585117048c379b6dee8af1cc1de5996af0)) - -### Features - -- **warn:** warn invalid hash ([fcf2365](https://github.com/vuejs/router/commit/fcf2365556dffa87153c13d31a684070f123ea0e)) -- allow numbers as params ([ef0920a](https://github.com/vuejs/router/commit/ef0920a86574bca10836214015c2317ed11a29b7)), closes [#206](https://github.com/vuejs/router/issues/206) -- **router:** allow global router classes ([388735b](https://github.com/vuejs/router/commit/388735bc752852e2a9a24f971207fd81fae45fcf)) -- **router:** go, back and forward can be awaited ([eb87757](https://github.com/vuejs/router/commit/eb87757ed189958c8c9955a10ece9306fa99f6d8)) -- **warn:** detect missing param in nested absolute paths ([f5b5949](https://github.com/vuejs/router/commit/f5b59493a4e27bf07bd5a0d2e109bc6750f6f1a9)) -- **warn:** warn for invalid path+params and redirect ([91f4de9](https://github.com/vuejs/router/commit/91f4de9aab99231fb39ed4cc5b4052979afda216)) -- **warn:** warn missing params in alias ([186e275](https://github.com/vuejs/router/commit/186e2755ec0488ff80bdde11a53b0ddc9ee9fc03)) -- **warn:** warn when params are provided alongside path ([8a8ddf1](https://github.com/vuejs/router/commit/8a8ddf1a5e5f2d29733da4fe25e4ddb447b0df30)) - -# [4.0.0-alpha.9](https://github.com/vuejs/router/compare/v4.0.0-alpha.8...v4.0.0-alpha.9) (2020-04-29) - -- Removed sourcemaps from build - -# [4.0.0-alpha.8](https://github.com/vuejs/router/compare/v4.0.0-alpha.7...v4.0.0-alpha.8) (2020-04-29) - -### Bug Fixes - -- default matcher options ([cea397b](https://github.com/vuejs/router/commit/cea397b7402cd27ff06013f846bf35966aff6952)) -- **guards:** preserve navigation options when redirecting ([9effd81](https://github.com/vuejs/router/commit/9effd816c51b58cb1103d878799aed6992f78454)) -- **html5:** correctly preserve current history.state ([0586394](https://github.com/vuejs/router/commit/05863948ee86e0f1c9c9ec31c02ad7af17923743)), closes [#180](https://github.com/vuejs/router/issues/180) -- **link:** make alias of empty child active ([cfe5993](https://github.com/vuejs/router/commit/cfe5993332cc7dc94c5de2f2edb7f2e15c9b7049)) -- encode hash ([85bb7e1](https://github.com/vuejs/router/commit/85bb7e11b1a4326f5048a823ae7d49654b308cdd)) -- **link:** preserve the alias path ([fffa585](https://github.com/vuejs/router/commit/fffa58585ac89e9fb6b648e61e499a9ee3a9e217)) -- **matcher:** merge params ([d8a6b25](https://github.com/vuejs/router/commit/d8a6b2591ac2e37388fb7f4ce8c70922389cedb5)), closes [#189](https://github.com/vuejs/router/issues/189) -- **router:** make redirect relative to target location ([e878e91](https://github.com/vuejs/router/commit/e878e91af217fde6d2e934857ce895e7abbd5920)) -- **router:** preserve navigation options with redirects ([9732758](https://github.com/vuejs/router/commit/9732758d076eef252f2940ffa44e44fa94e794a0)) -- **view:** render slot with no match ([5873296](https://github.com/vuejs/router/commit/5873296ec96df15f13b0cf02b685ebb36f4e0a41)) - -### Code Refactoring - -- Link and View renamed to RouterLink and RouterView ([030bbc4](https://github.com/vuejs/router/commit/030bbc4c3f68d29a9e9d23ee01603394427427a3)) - -### Features - -- **link:** make empty child active with adjacent children ([4b813b1](https://github.com/vuejs/router/commit/4b813b1ec387f8be9506f1400b7e83fd5794c7af)) -- **router:** add global pathOptions ([7383564](https://github.com/vuejs/router/commit/73835649f450ffc378b906c72aa5ae8a6a03feb2)) -- add navigation duplicated failure ([9570416](https://github.com/vuejs/router/commit/9570416c75f904a172af07bcf10956fe3385ec13)) -- add onBeforeRouteUpdate ([96c9503](https://github.com/vuejs/router/commit/96c95035653a52f94781808fccbf262a02a3cd79)) -- resolve relative paths ([eae833e](https://github.com/vuejs/router/commit/eae833e0fc1c8e549f2b4cd47b3dcb90484d17d5)) -- **router:** add back,forward,go ([5e927b5](https://github.com/vuejs/router/commit/5e927b5ab8a09c2941edbec7c6af145323c6d3eb)) -- **router:** add beforeResolve ([9697134](https://github.com/vuejs/router/commit/9697134c05f0f4c6fde48a773880946074e95666)) -- **scroll:** handle scroll on reload ([617f131](https://github.com/vuejs/router/commit/617f131d2473952072f345000c3d43556dfe9761)) - -### Performance Improvements - -- use index access for strings ([971fea4](https://github.com/vuejs/router/commit/971fea415fcce84ce86d8ace67b65115af3b7ac2)) - -### BREAKING CHANGES - -- exported components Link and View have been renamed to be - include the _Router_ prefix and to have the same export name as their component - name - -# [4.0.0-alpha.7](https://github.com/vuejs/router/compare/v4.0.0-alpha.6...v4.0.0-alpha.7) (2020-04-17) - -### Features - -- add `$route` and `$router` types ([a4f80aa](https://github.com/vuejs/router/commit/a4f80aaaafb1bf29a3f4d992e8c6a2bec0f70d62)) -- add guards types ([c7ccd5a](https://github.com/vuejs/router/commit/c7ccd5a0e67d88467fc661474308fbdf55b947ec)) -- refactor navigation to comply with vuejs/rfcs[#150](https://github.com/vuejs/router/issues/150) ([290c3be](https://github.com/vuejs/router/commit/290c3be1f6cb476016f23b77d6fc49987dd84751)) - -### BREAKING CHANGES - -- This follows the RFC at https://github.com/vuejs/rfcs/pull/150 - Summary: `router.afterEach` and `router.onError` are now the global equivalent of - `router.push`/`router.replace` as well as navigation through the interface - (`history.go()`). A navigation only rejects if there was an unexpected error. - A navigation failure will still resolve the promise returned by `router.push` - and be exposed as the resolved value. - -# [4.0.0-alpha.6](https://github.com/vuejs/router/compare/v4.0.0-alpha.5...v4.0.0-alpha.6) (2020-04-17) - -### Bug Fixes - -- **history:** allow base with / and base tag ([d7c71b5](https://github.com/vuejs/router/commit/d7c71b55ee4a11ecaf3a72f25eb126d118829d3f)), closes [#164](https://github.com/vuejs/router/issues/164) -- **history:** allow hash history with no origin ([760d216](https://github.com/vuejs/router/commit/760d21672051b6338d40f2cdfdac80dc16209e13)), closes [#163](https://github.com/vuejs/router/issues/163) -- **scroll:** only apply on browser ([cf53192](https://github.com/vuejs/router/commit/cf53192b77d619b1e43c8decda76d4083d9c17ea)) -- revert history navigation if navigation is cancelled ([d8a0d11](https://github.com/vuejs/router/commit/d8a0d117dbede9b177f06c8ebab201d12dfca0c0)) - -### Code Refactoring - -- **router:** merge createHref into resolve ([66b2db9](https://github.com/vuejs/router/commit/66b2db95b6b73433dc3abbe6c6f7f07959429d78)) - -### Features - -- add this.\$route ([92dc18d](https://github.com/vuejs/router/commit/92dc18d448ffeb57d9b3f3b303b8ec2991175eb5)) -- add this.\$router ([1807f30](https://github.com/vuejs/router/commit/1807f301053ac93db1e50991f67dcf532990d5c9)) -- **scroll:** handle scroll on popstate ([181efe9](https://github.com/vuejs/router/commit/181efe9f29a200b03e2d8f4759e7854047936824)) -- merge meta fields ([72a052f](https://github.com/vuejs/router/commit/72a052fdf4a198e3ac72779f1b7b8b80d0ac018d)) -- **guards:** support errors in navigation guards ([23ed08d](https://github.com/vuejs/router/commit/23ed08d983f308b7b118f2a235e58d29bf1994ec)) -- **router:** hasRoute ([ca02444](https://github.com/vuejs/router/commit/ca02444c91c8f6b21caf6a71dee5d0f2e3f7e51b)) - -### Reverts - -- Revert "test: only call browser.end on the last test" ([d3221f1](https://github.com/vuejs/router/commit/d3221f16978186b09531f7ea0cb5b92b20147181)) - -### BREAKING CHANGES - -- **router:** createHref is removed from the router. Instead, resolve - returns a location object with the corresponding `href` property - -# [4.0.0-alpha.5](https://github.com/vuejs/router/compare/v4.0.0-alpha.4...v4.0.0-alpha.5) (2020-04-08) - -### Bug Fixes - -- **link:** not active when matched is empty ([acd644d](https://github.com/vuejs/router/commit/acd644db70793da7719b321b2dcdd537ec358f9c)) -- check query and hash when navigating ([3862ad9](https://github.com/vuejs/router/commit/3862ad924bbc734a835577c3a3c71bc3550db29c)) -- ignore order of keys in query and params ([643bd15](https://github.com/vuejs/router/commit/643bd15ceaf9d6314434b15b169171b599b58e1c)) -- skip initial guards with static redirect ([c76bb93](https://github.com/vuejs/router/commit/c76bb938a2c9a1790be98b6ce44ccd153a342141)) -- **types:** add missing exported types ([ec241f7](https://github.com/vuejs/router/commit/ec241f7a93107815d9ffd25d36cbf00b47cb7318)), closes [#147](https://github.com/vuejs/router/issues/147) - -### Features - -- allow symbols as route record name ([f42ab3f](https://github.com/vuejs/router/commit/f42ab3fecfaecddcef0ccf8bb0f7f44ca24d6160)) -- **link:** activeClass and exactActiveClass props ([d53b383](https://github.com/vuejs/router/commit/d53b3832b50131cb83b8c567015780e60addb6c8)) -- **link:** allow `custom` prop ([874510b](https://github.com/vuejs/router/commit/874510be69c3b068970e8a90ae251cf487d6acf9)) - -### BREAKING CHANGES - -- Renamed types by removing suffix Normalized and using Raw instead - - `RouteLocation` -> `RouteLocationRaw` - - `RouteLocationNormalized` -> `RouteLocation` - - `RouteLocationNormalized` is now a location that can be displayed (not a static redirect) - - `RouteLocationNormalizedResolved` -> `RouteLocationNormalizedLoaded` - - `RouteRecord` -> `RouteRecordRaw` - - `RouteRecordNormalized` -> `RouteRecord` - - `RouteRecordNormalized` is now a record that is not a static redirect - -# [4.0.0-alpha.4](https://github.com/vuejs/router/compare/v4.0.0-alpha.3...v4.0.0-alpha.4) (2020-03-28) - -### Bug Fixes - -- **history:** use current history state when replacing ([5d80209](https://github.com/vuejs/router/commit/5d802094923851102557bfb2583835cc135e16b8)) -- export more types ([1583d48](https://github.com/vuejs/router/commit/1583d480fff2da1caa35c2dd7892c36b57dad734)), closes [#137](https://github.com/vuejs/router/issues/137) -- **guards:** free instances only if navigation is confirmed ([d0514e1](https://github.com/vuejs/router/commit/d0514e192839c54c4181f80286602e9d37459f4d)) -- **hash:** fix base position for hash routing ([ba40b8f](https://github.com/vuejs/router/commit/ba40b8f0cf2d6d85533e0e7e7daaadd088298f19)) -- initial location with base ([d05208b](https://github.com/vuejs/router/commit/d05208b6c9457931bda8205ba6d9f1d5e39a54c7)) -- **router:** prevent duplicated navigation on aliases ([e825586](https://github.com/vuejs/router/commit/e82558684c0b6b688065032df65604b2c245d395)) - -### Features - -- allow passing state to history ([ac1c96f](https://github.com/vuejs/router/commit/ac1c96f176dcad8aac03a86a1dccfbaab4b66520)) -- improve route access ([baf266c](https://github.com/vuejs/router/commit/baf266cd1bd6cafd32d244f185e340bee10af32c)) -- **history:** expose state on html5 ([3f83607](https://github.com/vuejs/router/commit/3f83607c8798960f49cdb5eed8fdfe8adc52fabf)) -- **matcher:** remove aliases alongside the original record ([26b71b2](https://github.com/vuejs/router/commit/26b71b285b743ab8af94b9297fa7037872ae0de6)) -- **router:** support custom parseQuery and stringifyQuery ([#136](https://github.com/vuejs/router/issues/136)) ([5dce7bc](https://github.com/vuejs/router/commit/5dce7bcbfbb4a80bd1edbe061a250fa646f2afd7)) -- **view:** add props option as boolean ([7fe1e7d](https://github.com/vuejs/router/commit/7fe1e7dc7406bddd0924bf7f01709b9113582472)) -- **view:** allow passing props as a function ([494fc5e](https://github.com/vuejs/router/commit/494fc5efb6add93c68ed467bb9a8dc7b3b149fff)) -- **view:** useView to customize router-view ([06b0c34](https://github.com/vuejs/router/commit/06b0c34ee5018aa9d76c0bfcd32ff2c12cd94277)) -- allow true in `next` ([d76c6aa](https://github.com/vuejs/router/commit/d76c6aae115110e2d9c4c072748bd9403080c8bd)) -- invoke guards with the right context ([7053413](https://github.com/vuejs/router/commit/7053413c93bc715d5c2179378367dc12f60a118d)) -- lazy loading ([6ecdc70](https://github.com/vuejs/router/commit/6ecdc70baa6361b8614368196ff2652560b6a0ba)) -- **view:** allow props as object in record ([fd4dc06](https://github.com/vuejs/router/commit/fd4dc0630bdf856f972ed6e9020b70a70ac582b4)) - -### BREAKING CHANGES - -- `useRoute` now retrieves a reactive RouteLocationNormalized instead of a Ref. - This means there is no need to use `.value` when accessing the route. You still need to wrap it with `toRefs` if you want to expose parts of the route: - ```js - setup () { - return { params: toRefs(useRoute()).params } - } - ``` - -# [4.0.0-alpha.3](https://github.com/vuejs/router/compare/v4.0.0-alpha.2...v4.0.0-alpha.3) (2020-03-14) - -### Bug Fixes - -- add missing type definitions - -# [4.0.0-alpha.2](https://github.com/vuejs/router/compare/v4.0.0-alpha.1...v4.0.0-alpha.2) (2020-03-14) - -### Bug Fixes - -- **history:** correct url when replacing current location ([704b45e](https://github.com/vuejs/router/commit/704b45ea52b10099a765c93ced37d03393a72d17)) -- **link:** allow attrs to override behavior ([4cae9db](https://github.com/vuejs/router/commit/4cae9dbede993a79577691e1df4444a8fe5ca3a0)) -- **link:** allow custom classes ([#134](https://github.com/vuejs/router/issues/134)) ([392c295](https://github.com/vuejs/router/commit/392c295552e5b7dbe1d494c1c3168571e3339153)), closes [#133](https://github.com/vuejs/router/issues/133) -- **link:** navigate to the alias path ([3284110](https://github.com/vuejs/router/commit/328411079e1aa8a5dc3903ae76a55d634946d9fd)) -- **link:** non active repeatable params ([0ccbc1e](https://github.com/vuejs/router/commit/0ccbc1e9af07a30a149ab14c007f63cbc35a8126)) - -### Features - -- add aliasOf to normalized records ([d9f3174](https://github.com/vuejs/router/commit/d9f31748802c39572254691108b0667cfd40e911)) -- handle active/exact in Link ([6f49dce](https://github.com/vuejs/router/commit/6f49dcea35a63785ae08d08787913ab8391cae67)) -- **matcher:** link aliases to their original record ([e9eb648](https://github.com/vuejs/router/commit/e9eb6481e21de61080a96f66fbd8640157d0fd27)) - -# [4.0.0-alpha.1](https://github.com/vuejs/router/compare/v4.0.0-alpha.0...v4.0.0-alpha.1) (2020-02-26) - -### Code Refactoring - -- rename createHistory and createHashHistory ([7dbebb6](https://github.com/vuejs/router/commit/7dbebb6e2d75ab4aa77019712f2ed251ad62464f)) - -### Features - -- add dynamic routing at router level ([a7943c6](https://github.com/vuejs/router/commit/a7943c64383bced7ff90ae92c0498827acdb71f6)) - -### BREAKING CHANGES - -- `createHistory` is now named `createWebHistory`. - `createHashHistory` is now named `createWebHashHistory`. - - Both createHistory and createHashHistory are renamed to - better reflect that they must be used in a browser environment while - createMemoryHistory doesn't. - -# [4.0.0-alpha.0](https://github.com/vuejs/router/compare/v0.0.11...v4.0.0-alpha.0) (2020-02-26) - -## Known issues - -### Breaking changes compared to vue-router@3.x - -- `mode: 'history'` -> `history: createHistory()` -- Catch all routes (`/*`) must now be defined using a parameter with a custom regex: `/:catchAll(.*)` - -### Missing features - -- `keep-alive` is not yet supported -- Partial support of per-component navigation guards. No `beforeRouteEnter` yet diff --git a/node_modules/vue-router/LICENSE b/node_modules/vue-router/LICENSE index 2d297f2..0c77562 100644 --- a/node_modules/vue-router/LICENSE +++ b/node_modules/vue-router/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2020 Eduardo San Martin Morote +Copyright (c) 2019-present Eduardo San Martin Morote Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/node_modules/vue-router/README.md b/node_modules/vue-router/README.md deleted file mode 100644 index 49b49ee..0000000 --- a/node_modules/vue-router/README.md +++ /dev/null @@ -1,112 +0,0 @@ -# vue-router [![release candidate](https://img.shields.io/npm/v/vue-router.svg)](https://www.npmjs.com/package/vue-router) [![CircleCI](https://badgen.net/circleci/github/vuejs/router/main)](https://circleci.com/gh/vuejs/router) - -> This is the repository for Vue Router 4 (for Vue 3) - -

Supporting Vue Router

- -Vue Router is part of the Vue Ecosystem and is an MIT-licensed open source project with its ongoing development made possible entirely by the support of Sponsors. If you would like to become a sponsor, please consider: - -- [Become a Sponsor on GitHub](https://github.com/sponsors/posva) -- [One-time donation via PayPal](https://paypal.me/posva) - - -

Platinum Sponsors

-

- - - - Finogeeks - - -

- -

Gold Sponsors

-

- - - - VueJobs - - -

- -

Silver Sponsors

-

- - - - VueMastery - - - - - - Prefect - - - - - - Bird Eats Bug - - -

- -

Bronze Sponsors

-

- - - - Stanislas Ormières - - - - - - Antony Konstantinidis - - - - - - Storyblok - - - - - - NuxtJS - - -

- - - ---- - -Get started with the [documentation](https://router.vuejs.org). - -## Quickstart - -- Via CDN: `` -- In-browser playground on [CodeSandbox](https://codesandbox.io/s/vue-router-4-reproduction-hb9lh) -- Add it to an existing Vue Project: - ```bash - npm install vue-router@4 - ``` - -## Changes from Vue Router 3 - -Please consult the [Migration Guide](https://router.vuejs.org/guide/migration/). - -## Contributing - -See [Contributing Guide](https://github.com/vuejs/router/blob/main/.github/contributing.md). - -## Special Thanks - - - BrowserStack Logo - - -Special thanks to [BrowserStack](https://www.browserstack.com) for letting the maintainers use their service to debug browser specific issues. diff --git a/node_modules/vue-router/dist/vue-router.cjs.js b/node_modules/vue-router/dist/vue-router.cjs.js index f7fef09..3937c61 100644 --- a/node_modules/vue-router/dist/vue-router.cjs.js +++ b/node_modules/vue-router/dist/vue-router.cjs.js @@ -1,3470 +1 @@ -/*! - * vue-router v4.0.15 - * (c) 2022 Eduardo San Martin Morote - * @license MIT - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var vue = require('vue'); -var devtoolsApi = require('@vue/devtools-api'); - -const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -const PolySymbol = (name) => -// vr = vue router -hasSymbol - ? Symbol('[vue-router]: ' + name ) - : ('[vue-router]: ' ) + name; -// rvlm = Router View Location Matched -/** - * RouteRecord being rendered by the closest ancestor Router View. Used for - * `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View - * Location Matched - * - * @internal - */ -const matchedRouteKey = /*#__PURE__*/ PolySymbol('router view location matched' ); -/** - * Allows overriding the router view depth to control which component in - * `matched` is rendered. rvd stands for Router View Depth - * - * @internal - */ -const viewDepthKey = /*#__PURE__*/ PolySymbol('router view depth' ); -/** - * Allows overriding the router instance returned by `useRouter` in tests. r - * stands for router - * - * @internal - */ -const routerKey = /*#__PURE__*/ PolySymbol('router' ); -/** - * Allows overriding the current route returned by `useRoute` in tests. rl - * stands for route location - * - * @internal - */ -const routeLocationKey = /*#__PURE__*/ PolySymbol('route location' ); -/** - * Allows overriding the current route used by router-view. Internally this is - * used when the `route` prop is passed. - * - * @internal - */ -const routerViewLocationKey = /*#__PURE__*/ PolySymbol('router view location' ); - -const isBrowser = typeof window !== 'undefined'; - -function isESModule(obj) { - return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module'); -} -const assign = Object.assign; -function applyToParams(fn, params) { - const newParams = {}; - for (const key in params) { - const value = params[key]; - newParams[key] = Array.isArray(value) ? value.map(fn) : fn(value); - } - return newParams; -} -const noop = () => { }; - -function warn(msg) { - // avoid using ...args as it breaks in older Edge builds - const args = Array.from(arguments).slice(1); - console.warn.apply(console, ['[Vue Router warn]: ' + msg].concat(args)); -} - -const TRAILING_SLASH_RE = /\/$/; -const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, ''); -/** - * Transforms an URI into a normalized history location - * - * @param parseQuery - * @param location - URI to normalize - * @param currentLocation - current absolute location. Allows resolving relative - * paths. Must start with `/`. Defaults to `/` - * @returns a normalized history location - */ -function parseURL(parseQuery, location, currentLocation = '/') { - let path, query = {}, searchString = '', hash = ''; - // Could use URL and URLSearchParams but IE 11 doesn't support it - const searchPos = location.indexOf('?'); - const hashPos = location.indexOf('#', searchPos > -1 ? searchPos : 0); - if (searchPos > -1) { - path = location.slice(0, searchPos); - searchString = location.slice(searchPos + 1, hashPos > -1 ? hashPos : location.length); - query = parseQuery(searchString); - } - if (hashPos > -1) { - path = path || location.slice(0, hashPos); - // keep the # character - hash = location.slice(hashPos, location.length); - } - // no search and no query - path = resolveRelativePath(path != null ? path : location, currentLocation); - // empty path means a relative query or hash `?foo=f`, `#thing` - return { - fullPath: path + (searchString && '?') + searchString + hash, - path, - query, - hash, - }; -} -/** - * Stringifies a URL object - * - * @param stringifyQuery - * @param location - */ -function stringifyURL(stringifyQuery, location) { - const query = location.query ? stringifyQuery(location.query) : ''; - return location.path + (query && '?') + query + (location.hash || ''); -} -/** - * Strips off the base from the beginning of a location.pathname in a non - * case-sensitive way. - * - * @param pathname - location.pathname - * @param base - base to strip off - */ -function stripBase(pathname, base) { - // no base or base is not found at the beginning - if (!base || !pathname.toLowerCase().startsWith(base.toLowerCase())) - return pathname; - return pathname.slice(base.length) || '/'; -} -/** - * Checks if two RouteLocation are equal. This means that both locations are - * pointing towards the same {@link RouteRecord} and that all `params`, `query` - * parameters and `hash` are the same - * - * @param a - first {@link RouteLocation} - * @param b - second {@link RouteLocation} - */ -function isSameRouteLocation(stringifyQuery, a, b) { - const aLastIndex = a.matched.length - 1; - const bLastIndex = b.matched.length - 1; - return (aLastIndex > -1 && - aLastIndex === bLastIndex && - isSameRouteRecord(a.matched[aLastIndex], b.matched[bLastIndex]) && - isSameRouteLocationParams(a.params, b.params) && - stringifyQuery(a.query) === stringifyQuery(b.query) && - a.hash === b.hash); -} -/** - * Check if two `RouteRecords` are equal. Takes into account aliases: they are - * considered equal to the `RouteRecord` they are aliasing. - * - * @param a - first {@link RouteRecord} - * @param b - second {@link RouteRecord} - */ -function isSameRouteRecord(a, b) { - // since the original record has an undefined value for aliasOf - // but all aliases point to the original record, this will always compare - // the original record - return (a.aliasOf || a) === (b.aliasOf || b); -} -function isSameRouteLocationParams(a, b) { - if (Object.keys(a).length !== Object.keys(b).length) - return false; - for (const key in a) { - if (!isSameRouteLocationParamsValue(a[key], b[key])) - return false; - } - return true; -} -function isSameRouteLocationParamsValue(a, b) { - return Array.isArray(a) - ? isEquivalentArray(a, b) - : Array.isArray(b) - ? isEquivalentArray(b, a) - : a === b; -} -/** - * Check if two arrays are the same or if an array with one single entry is the - * same as another primitive value. Used to check query and parameters - * - * @param a - array of values - * @param b - array of values or a single value - */ -function isEquivalentArray(a, b) { - return Array.isArray(b) - ? a.length === b.length && a.every((value, i) => value === b[i]) - : a.length === 1 && a[0] === b; -} -/** - * Resolves a relative path that starts with `.`. - * - * @param to - path location we are resolving - * @param from - currentLocation.path, should start with `/` - */ -function resolveRelativePath(to, from) { - if (to.startsWith('/')) - return to; - if (!from.startsWith('/')) { - warn(`Cannot resolve a relative location without an absolute path. Trying to resolve "${to}" from "${from}". It should look like "/${from}".`); - return to; - } - if (!to) - return from; - const fromSegments = from.split('/'); - const toSegments = to.split('/'); - let position = fromSegments.length - 1; - let toPosition; - let segment; - for (toPosition = 0; toPosition < toSegments.length; toPosition++) { - segment = toSegments[toPosition]; - // can't go below zero - if (position === 1 || segment === '.') - continue; - if (segment === '..') - position--; - // found something that is not relative path - else - break; - } - return (fromSegments.slice(0, position).join('/') + - '/' + - toSegments - .slice(toPosition - (toPosition === toSegments.length ? 1 : 0)) - .join('/')); -} - -var NavigationType; -(function (NavigationType) { - NavigationType["pop"] = "pop"; - NavigationType["push"] = "push"; -})(NavigationType || (NavigationType = {})); -var NavigationDirection; -(function (NavigationDirection) { - NavigationDirection["back"] = "back"; - NavigationDirection["forward"] = "forward"; - NavigationDirection["unknown"] = ""; -})(NavigationDirection || (NavigationDirection = {})); -/** - * Starting location for Histories - */ -const START = ''; -// Generic utils -/** - * Normalizes a base by removing any trailing slash and reading the base tag if - * present. - * - * @param base - base to normalize - */ -function normalizeBase(base) { - if (!base) { - if (isBrowser) { - // respect tag - const baseEl = document.querySelector('base'); - base = (baseEl && baseEl.getAttribute('href')) || '/'; - // strip full URL origin - base = base.replace(/^\w+:\/\/[^\/]+/, ''); - } - else { - base = '/'; - } - } - // ensure leading slash when it was removed by the regex above avoid leading - // slash with hash because the file could be read from the disk like file:// - // and the leading slash would cause problems - if (base[0] !== '/' && base[0] !== '#') - base = '/' + base; - // remove the trailing slash so all other method can just do `base + fullPath` - // to build an href - return removeTrailingSlash(base); -} -// remove any character before the hash -const BEFORE_HASH_RE = /^[^#]+#/; -function createHref(base, location) { - return base.replace(BEFORE_HASH_RE, '#') + location; -} - -function getElementPosition(el, offset) { - const docRect = document.documentElement.getBoundingClientRect(); - const elRect = el.getBoundingClientRect(); - return { - behavior: offset.behavior, - left: elRect.left - docRect.left - (offset.left || 0), - top: elRect.top - docRect.top - (offset.top || 0), - }; -} -const computeScrollPosition = () => ({ - left: window.pageXOffset, - top: window.pageYOffset, -}); -function scrollToPosition(position) { - let scrollToOptions; - if ('el' in position) { - const positionEl = position.el; - const isIdSelector = typeof positionEl === 'string' && positionEl.startsWith('#'); - /** - * `id`s can accept pretty much any characters, including CSS combinators - * like `>` or `~`. It's still possible to retrieve elements using - * `document.getElementById('~')` but it needs to be escaped when using - * `document.querySelector('#\\~')` for it to be valid. The only - * requirements for `id`s are them to be unique on the page and to not be - * empty (`id=""`). Because of that, when passing an id selector, it should - * be properly escaped for it to work with `querySelector`. We could check - * for the id selector to be simple (no CSS combinators `+ >~`) but that - * would make things inconsistent since they are valid characters for an - * `id` but would need to be escaped when using `querySelector`, breaking - * their usage and ending up in no selector returned. Selectors need to be - * escaped: - * - * - `#1-thing` becomes `#\31 -thing` - * - `#with~symbols` becomes `#with\\~symbols` - * - * - More information about the topic can be found at - * https://mathiasbynens.be/notes/html5-id-class. - * - Practical example: https://mathiasbynens.be/demo/html5-id - */ - if (typeof position.el === 'string') { - if (!isIdSelector || !document.getElementById(position.el.slice(1))) { - try { - const foundEl = document.querySelector(position.el); - if (isIdSelector && foundEl) { - warn(`The selector "${position.el}" should be passed as "el: document.querySelector('${position.el}')" because it starts with "#".`); - // return to avoid other warnings - return; - } - } - catch (err) { - warn(`The selector "${position.el}" is invalid. If you are using an id selector, make sure to escape it. You can find more information about escaping characters in selectors at https://mathiasbynens.be/notes/css-escapes or use CSS.escape (https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape).`); - // return to avoid other warnings - return; - } - } - } - const el = typeof positionEl === 'string' - ? isIdSelector - ? document.getElementById(positionEl.slice(1)) - : document.querySelector(positionEl) - : positionEl; - if (!el) { - warn(`Couldn't find element using selector "${position.el}" returned by scrollBehavior.`); - return; - } - scrollToOptions = getElementPosition(el, position); - } - else { - scrollToOptions = position; - } - if ('scrollBehavior' in document.documentElement.style) - window.scrollTo(scrollToOptions); - else { - window.scrollTo(scrollToOptions.left != null ? scrollToOptions.left : window.pageXOffset, scrollToOptions.top != null ? scrollToOptions.top : window.pageYOffset); - } -} -function getScrollKey(path, delta) { - const position = history.state ? history.state.position - delta : -1; - return position + path; -} -const scrollPositions = new Map(); -function saveScrollPosition(key, scrollPosition) { - scrollPositions.set(key, scrollPosition); -} -function getSavedScrollPosition(key) { - const scroll = scrollPositions.get(key); - // consume it so it's not used again - scrollPositions.delete(key); - return scroll; -} -// TODO: RFC about how to save scroll position -/** - * ScrollBehavior instance used by the router to compute and restore the scroll - * position when navigating. - */ -// export interface ScrollHandler { -// // returns a scroll position that can be saved in history -// compute(): ScrollPositionEntry -// // can take an extended ScrollPositionEntry -// scroll(position: ScrollPosition): void -// } -// export const scrollHandler: ScrollHandler = { -// compute: computeScroll, -// scroll: scrollToPosition, -// } - -let createBaseLocation = () => location.protocol + '//' + location.host; -/** - * Creates a normalized history location from a window.location object - * @param location - - */ -function createCurrentLocation(base, location) { - const { pathname, search, hash } = location; - // allows hash bases like #, /#, #/, #!, #!/, /#!/, or even /folder#end - const hashPos = base.indexOf('#'); - if (hashPos > -1) { - let slicePos = hash.includes(base.slice(hashPos)) - ? base.slice(hashPos).length - : 1; - let pathFromHash = hash.slice(slicePos); - // prepend the starting slash to hash so the url starts with /# - if (pathFromHash[0] !== '/') - pathFromHash = '/' + pathFromHash; - return stripBase(pathFromHash, ''); - } - const path = stripBase(pathname, base); - return path + search + hash; -} -function useHistoryListeners(base, historyState, currentLocation, replace) { - let listeners = []; - let teardowns = []; - // TODO: should it be a stack? a Dict. Check if the popstate listener - // can trigger twice - let pauseState = null; - const popStateHandler = ({ state, }) => { - const to = createCurrentLocation(base, location); - const from = currentLocation.value; - const fromState = historyState.value; - let delta = 0; - if (state) { - currentLocation.value = to; - historyState.value = state; - // ignore the popstate and reset the pauseState - if (pauseState && pauseState === from) { - pauseState = null; - return; - } - delta = fromState ? state.position - fromState.position : 0; - } - else { - replace(to); - } - // console.log({ deltaFromCurrent }) - // Here we could also revert the navigation by calling history.go(-delta) - // this listener will have to be adapted to not trigger again and to wait for the url - // to be updated before triggering the listeners. Some kind of validation function would also - // need to be passed to the listeners so the navigation can be accepted - // call all listeners - listeners.forEach(listener => { - listener(currentLocation.value, from, { - delta, - type: NavigationType.pop, - direction: delta - ? delta > 0 - ? NavigationDirection.forward - : NavigationDirection.back - : NavigationDirection.unknown, - }); - }); - }; - function pauseListeners() { - pauseState = currentLocation.value; - } - function listen(callback) { - // setup the listener and prepare teardown callbacks - listeners.push(callback); - const teardown = () => { - const index = listeners.indexOf(callback); - if (index > -1) - listeners.splice(index, 1); - }; - teardowns.push(teardown); - return teardown; - } - function beforeUnloadListener() { - const { history } = window; - if (!history.state) - return; - history.replaceState(assign({}, history.state, { scroll: computeScrollPosition() }), ''); - } - function destroy() { - for (const teardown of teardowns) - teardown(); - teardowns = []; - window.removeEventListener('popstate', popStateHandler); - window.removeEventListener('beforeunload', beforeUnloadListener); - } - // setup the listeners and prepare teardown callbacks - window.addEventListener('popstate', popStateHandler); - window.addEventListener('beforeunload', beforeUnloadListener); - return { - pauseListeners, - listen, - destroy, - }; -} -/** - * Creates a state object - */ -function buildState(back, current, forward, replaced = false, computeScroll = false) { - return { - back, - current, - forward, - replaced, - position: window.history.length, - scroll: computeScroll ? computeScrollPosition() : null, - }; -} -function useHistoryStateNavigation(base) { - const { history, location } = window; - // private variables - const currentLocation = { - value: createCurrentLocation(base, location), - }; - const historyState = { value: history.state }; - // build current history entry as this is a fresh navigation - if (!historyState.value) { - changeLocation(currentLocation.value, { - back: null, - current: currentLocation.value, - forward: null, - // the length is off by one, we need to decrease it - position: history.length - 1, - replaced: true, - // don't add a scroll as the user may have an anchor and we want - // scrollBehavior to be triggered without a saved position - scroll: null, - }, true); - } - function changeLocation(to, state, replace) { - /** - * if a base tag is provided and we are on a normal domain, we have to - * respect the provided `base` attribute because pushState() will use it and - * potentially erase anything before the `#` like at - * https://github.com/vuejs/router/issues/685 where a base of - * `/folder/#` but a base of `/` would erase the `/folder/` section. If - * there is no host, the `` tag makes no sense and if there isn't a - * base tag we can just use everything after the `#`. - */ - const hashIndex = base.indexOf('#'); - const url = hashIndex > -1 - ? (location.host && document.querySelector('base') - ? base - : base.slice(hashIndex)) + to - : createBaseLocation() + base + to; - try { - // BROWSER QUIRK - // NOTE: Safari throws a SecurityError when calling this function 100 times in 30 seconds - history[replace ? 'replaceState' : 'pushState'](state, '', url); - historyState.value = state; - } - catch (err) { - { - warn('Error with push/replace State', err); - } - // Force the navigation, this also resets the call count - location[replace ? 'replace' : 'assign'](url); - } - } - function replace(to, data) { - const state = assign({}, history.state, buildState(historyState.value.back, - // keep back and forward entries but override current position - to, historyState.value.forward, true), data, { position: historyState.value.position }); - changeLocation(to, state, true); - currentLocation.value = to; - } - function push(to, data) { - // Add to current entry the information of where we are going - // as well as saving the current position - const currentState = assign({}, - // use current history state to gracefully handle a wrong call to - // history.replaceState - // https://github.com/vuejs/router/issues/366 - historyState.value, history.state, { - forward: to, - scroll: computeScrollPosition(), - }); - if (!history.state) { - warn(`history.state seems to have been manually replaced without preserving the necessary values. Make sure to preserve existing history state if you are manually calling history.replaceState:\n\n` + - `history.replaceState(history.state, '', url)\n\n` + - `You can find more information at https://next.router.vuejs.org/guide/migration/#usage-of-history-state.`); - } - changeLocation(currentState.current, currentState, true); - const state = assign({}, buildState(currentLocation.value, to, null), { position: currentState.position + 1 }, data); - changeLocation(to, state, false); - currentLocation.value = to; - } - return { - location: currentLocation, - state: historyState, - push, - replace, - }; -} -/** - * Creates an HTML5 history. Most common history for single page applications. - * - * @param base - - */ -function createWebHistory(base) { - base = normalizeBase(base); - const historyNavigation = useHistoryStateNavigation(base); - const historyListeners = useHistoryListeners(base, historyNavigation.state, historyNavigation.location, historyNavigation.replace); - function go(delta, triggerListeners = true) { - if (!triggerListeners) - historyListeners.pauseListeners(); - history.go(delta); - } - const routerHistory = assign({ - // it's overridden right after - location: '', - base, - go, - createHref: createHref.bind(null, base), - }, historyNavigation, historyListeners); - Object.defineProperty(routerHistory, 'location', { - enumerable: true, - get: () => historyNavigation.location.value, - }); - Object.defineProperty(routerHistory, 'state', { - enumerable: true, - get: () => historyNavigation.state.value, - }); - return routerHistory; -} - -/** - * Creates a in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere. - * It's up to the user to replace that location with the starter location by either calling `router.push` or `router.replace`. - * - * @param base - Base applied to all urls, defaults to '/' - * @returns a history object that can be passed to the router constructor - */ -function createMemoryHistory(base = '') { - let listeners = []; - let queue = [START]; - let position = 0; - base = normalizeBase(base); - function setLocation(location) { - position++; - if (position === queue.length) { - // we are at the end, we can simply append a new entry - queue.push(location); - } - else { - // we are in the middle, we remove everything from here in the queue - queue.splice(position); - queue.push(location); - } - } - function triggerListeners(to, from, { direction, delta }) { - const info = { - direction, - delta, - type: NavigationType.pop, - }; - for (const callback of listeners) { - callback(to, from, info); - } - } - const routerHistory = { - // rewritten by Object.defineProperty - location: START, - // TODO: should be kept in queue - state: {}, - base, - createHref: createHref.bind(null, base), - replace(to) { - // remove current entry and decrement position - queue.splice(position--, 1); - setLocation(to); - }, - push(to, data) { - setLocation(to); - }, - listen(callback) { - listeners.push(callback); - return () => { - const index = listeners.indexOf(callback); - if (index > -1) - listeners.splice(index, 1); - }; - }, - destroy() { - listeners = []; - queue = [START]; - position = 0; - }, - go(delta, shouldTrigger = true) { - const from = this.location; - const direction = - // we are considering delta === 0 going forward, but in abstract mode - // using 0 for the delta doesn't make sense like it does in html5 where - // it reloads the page - delta < 0 ? NavigationDirection.back : NavigationDirection.forward; - position = Math.max(0, Math.min(position + delta, queue.length - 1)); - if (shouldTrigger) { - triggerListeners(this.location, from, { - direction, - delta, - }); - } - }, - }; - Object.defineProperty(routerHistory, 'location', { - enumerable: true, - get: () => queue[position], - }); - return routerHistory; -} - -/** - * Creates a hash history. Useful for web applications with no host (e.g. - * `file://`) or when configuring a server to handle any URL is not possible. - * - * @param base - optional base to provide. Defaults to `location.pathname + - * location.search` If there is a `` tag in the `head`, its value will be - * ignored in favor of this parameter **but note it affects all the - * history.pushState() calls**, meaning that if you use a `` tag, it's - * `href` value **has to match this parameter** (ignoring anything after the - * `#`). - * - * @example - * ```js - * // at https://example.com/folder - * createWebHashHistory() // gives a url of `https://example.com/folder#` - * createWebHashHistory('/folder/') // gives a url of `https://example.com/folder/#` - * // if the `#` is provided in the base, it won't be added by `createWebHashHistory` - * createWebHashHistory('/folder/#/app/') // gives a url of `https://example.com/folder/#/app/` - * // you should avoid doing this because it changes the original url and breaks copying urls - * createWebHashHistory('/other-folder/') // gives a url of `https://example.com/other-folder/#` - * - * // at file:///usr/etc/folder/index.html - * // for locations with no `host`, the base is ignored - * createWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#` - * ``` - */ -function createWebHashHistory(base) { - // Make sure this implementation is fine in terms of encoding, specially for IE11 - // for `file://`, directly use the pathname and ignore the base - // location.pathname contains an initial `/` even at the root: `https://example.com` - base = location.host ? base || location.pathname + location.search : ''; - // allow the user to provide a `#` in the middle: `/base/#/app` - if (!base.includes('#')) - base += '#'; - if (!base.endsWith('#/') && !base.endsWith('#')) { - warn(`A hash base must end with a "#":\n"${base}" should be "${base.replace(/#.*$/, '#')}".`); - } - return createWebHistory(base); -} - -function isRouteLocation(route) { - return typeof route === 'string' || (route && typeof route === 'object'); -} -function isRouteName(name) { - return typeof name === 'string' || typeof name === 'symbol'; -} - -/** - * Initial route location where the router is. Can be used in navigation guards - * to differentiate the initial navigation. - * - * @example - * ```js - * import { START_LOCATION } from 'vue-router' - * - * router.beforeEach((to, from) => { - * if (from === START_LOCATION) { - * // initial navigation - * } - * }) - * ``` - */ -const START_LOCATION_NORMALIZED = { - path: '/', - name: undefined, - params: {}, - query: {}, - hash: '', - fullPath: '/', - matched: [], - meta: {}, - redirectedFrom: undefined, -}; - -const NavigationFailureSymbol = /*#__PURE__*/ PolySymbol('navigation failure' ); -/** - * Enumeration with all possible types for navigation failures. Can be passed to - * {@link isNavigationFailure} to check for specific failures. - */ -exports.NavigationFailureType = void 0; -(function (NavigationFailureType) { - /** - * An aborted navigation is a navigation that failed because a navigation - * guard returned `false` or called `next(false)` - */ - NavigationFailureType[NavigationFailureType["aborted"] = 4] = "aborted"; - /** - * A cancelled navigation is a navigation that failed because a more recent - * navigation finished started (not necessarily finished). - */ - NavigationFailureType[NavigationFailureType["cancelled"] = 8] = "cancelled"; - /** - * A duplicated navigation is a navigation that failed because it was - * initiated while already being at the exact same location. - */ - NavigationFailureType[NavigationFailureType["duplicated"] = 16] = "duplicated"; -})(exports.NavigationFailureType || (exports.NavigationFailureType = {})); -// DEV only debug messages -const ErrorTypeMessages = { - [1 /* MATCHER_NOT_FOUND */]({ location, currentLocation }) { - return `No match for\n ${JSON.stringify(location)}${currentLocation - ? '\nwhile being at\n' + JSON.stringify(currentLocation) - : ''}`; - }, - [2 /* NAVIGATION_GUARD_REDIRECT */]({ from, to, }) { - return `Redirected from "${from.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`; - }, - [4 /* NAVIGATION_ABORTED */]({ from, to }) { - return `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`; - }, - [8 /* NAVIGATION_CANCELLED */]({ from, to }) { - return `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`; - }, - [16 /* NAVIGATION_DUPLICATED */]({ from, to }) { - return `Avoided redundant navigation to current location: "${from.fullPath}".`; - }, -}; -function createRouterError(type, params) { - // keep full error messages in cjs versions - { - return assign(new Error(ErrorTypeMessages[type](params)), { - type, - [NavigationFailureSymbol]: true, - }, params); - } -} -function isNavigationFailure(error, type) { - return (error instanceof Error && - NavigationFailureSymbol in error && - (type == null || !!(error.type & type))); -} -const propertiesToLog = ['params', 'query', 'hash']; -function stringifyRoute(to) { - if (typeof to === 'string') - return to; - if ('path' in to) - return to.path; - const location = {}; - for (const key of propertiesToLog) { - if (key in to) - location[key] = to[key]; - } - return JSON.stringify(location, null, 2); -} - -// default pattern for a param: non greedy everything but / -const BASE_PARAM_PATTERN = '[^/]+?'; -const BASE_PATH_PARSER_OPTIONS = { - sensitive: false, - strict: false, - start: true, - end: true, -}; -// Special Regex characters that must be escaped in static tokens -const REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g; -/** - * Creates a path parser from an array of Segments (a segment is an array of Tokens) - * - * @param segments - array of segments returned by tokenizePath - * @param extraOptions - optional options for the regexp - * @returns a PathParser - */ -function tokensToParser(segments, extraOptions) { - const options = assign({}, BASE_PATH_PARSER_OPTIONS, extraOptions); - // the amount of scores is the same as the length of segments except for the root segment "/" - const score = []; - // the regexp as a string - let pattern = options.start ? '^' : ''; - // extracted keys - const keys = []; - for (const segment of segments) { - // the root segment needs special treatment - const segmentScores = segment.length ? [] : [90 /* Root */]; - // allow trailing slash - if (options.strict && !segment.length) - pattern += '/'; - for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) { - const token = segment[tokenIndex]; - // resets the score if we are inside a sub segment /:a-other-:b - let subSegmentScore = 40 /* Segment */ + - (options.sensitive ? 0.25 /* BonusCaseSensitive */ : 0); - if (token.type === 0 /* Static */) { - // prepend the slash if we are starting a new segment - if (!tokenIndex) - pattern += '/'; - pattern += token.value.replace(REGEX_CHARS_RE, '\\$&'); - subSegmentScore += 40 /* Static */; - } - else if (token.type === 1 /* Param */) { - const { value, repeatable, optional, regexp } = token; - keys.push({ - name: value, - repeatable, - optional, - }); - const re = regexp ? regexp : BASE_PARAM_PATTERN; - // the user provided a custom regexp /:id(\\d+) - if (re !== BASE_PARAM_PATTERN) { - subSegmentScore += 10 /* BonusCustomRegExp */; - // make sure the regexp is valid before using it - try { - new RegExp(`(${re})`); - } - catch (err) { - throw new Error(`Invalid custom RegExp for param "${value}" (${re}): ` + - err.message); - } - } - // when we repeat we must take care of the repeating leading slash - let subPattern = repeatable ? `((?:${re})(?:/(?:${re}))*)` : `(${re})`; - // prepend the slash if we are starting a new segment - if (!tokenIndex) - subPattern = - // avoid an optional / if there are more segments e.g. /:p?-static - // or /:p?-:p2 - optional && segment.length < 2 - ? `(?:/${subPattern})` - : '/' + subPattern; - if (optional) - subPattern += '?'; - pattern += subPattern; - subSegmentScore += 20 /* Dynamic */; - if (optional) - subSegmentScore += -8 /* BonusOptional */; - if (repeatable) - subSegmentScore += -20 /* BonusRepeatable */; - if (re === '.*') - subSegmentScore += -50 /* BonusWildcard */; - } - segmentScores.push(subSegmentScore); - } - // an empty array like /home/ -> [[{home}], []] - // if (!segment.length) pattern += '/' - score.push(segmentScores); - } - // only apply the strict bonus to the last score - if (options.strict && options.end) { - const i = score.length - 1; - score[i][score[i].length - 1] += 0.7000000000000001 /* BonusStrict */; - } - // TODO: dev only warn double trailing slash - if (!options.strict) - pattern += '/?'; - if (options.end) - pattern += '$'; - // allow paths like /dynamic to only match dynamic or dynamic/... but not dynamic_something_else - else if (options.strict) - pattern += '(?:/|$)'; - const re = new RegExp(pattern, options.sensitive ? '' : 'i'); - function parse(path) { - const match = path.match(re); - const params = {}; - if (!match) - return null; - for (let i = 1; i < match.length; i++) { - const value = match[i] || ''; - const key = keys[i - 1]; - params[key.name] = value && key.repeatable ? value.split('/') : value; - } - return params; - } - function stringify(params) { - let path = ''; - // for optional parameters to allow to be empty - let avoidDuplicatedSlash = false; - for (const segment of segments) { - if (!avoidDuplicatedSlash || !path.endsWith('/')) - path += '/'; - avoidDuplicatedSlash = false; - for (const token of segment) { - if (token.type === 0 /* Static */) { - path += token.value; - } - else if (token.type === 1 /* Param */) { - const { value, repeatable, optional } = token; - const param = value in params ? params[value] : ''; - if (Array.isArray(param) && !repeatable) - throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`); - const text = Array.isArray(param) ? param.join('/') : param; - if (!text) { - if (optional) { - // if we have more than one optional param like /:a?-static and there are more segments, we don't need to - // care about the optional param - if (segment.length < 2 && segments.length > 1) { - // remove the last slash as we could be at the end - if (path.endsWith('/')) - path = path.slice(0, -1); - // do not append a slash on the next iteration - else - avoidDuplicatedSlash = true; - } - } - else - throw new Error(`Missing required param "${value}"`); - } - path += text; - } - } - } - return path; - } - return { - re, - score, - keys, - parse, - stringify, - }; -} -/** - * Compares an array of numbers as used in PathParser.score and returns a - * number. This function can be used to `sort` an array - * - * @param a - first array of numbers - * @param b - second array of numbers - * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b - * should be sorted first - */ -function compareScoreArray(a, b) { - let i = 0; - while (i < a.length && i < b.length) { - const diff = b[i] - a[i]; - // only keep going if diff === 0 - if (diff) - return diff; - i++; - } - // if the last subsegment was Static, the shorter segments should be sorted first - // otherwise sort the longest segment first - if (a.length < b.length) { - return a.length === 1 && a[0] === 40 /* Static */ + 40 /* Segment */ - ? -1 - : 1; - } - else if (a.length > b.length) { - return b.length === 1 && b[0] === 40 /* Static */ + 40 /* Segment */ - ? 1 - : -1; - } - return 0; -} -/** - * Compare function that can be used with `sort` to sort an array of PathParser - * - * @param a - first PathParser - * @param b - second PathParser - * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b - */ -function comparePathParserScore(a, b) { - let i = 0; - const aScore = a.score; - const bScore = b.score; - while (i < aScore.length && i < bScore.length) { - const comp = compareScoreArray(aScore[i], bScore[i]); - // do not return if both are equal - if (comp) - return comp; - i++; - } - // if a and b share the same score entries but b has more, sort b first - return bScore.length - aScore.length; - // this is the ternary version - // return aScore.length < bScore.length - // ? 1 - // : aScore.length > bScore.length - // ? -1 - // : 0 -} - -const ROOT_TOKEN = { - type: 0 /* Static */, - value: '', -}; -const VALID_PARAM_RE = /[a-zA-Z0-9_]/; -// After some profiling, the cache seems to be unnecessary because tokenizePath -// (the slowest part of adding a route) is very fast -// const tokenCache = new Map() -function tokenizePath(path) { - if (!path) - return [[]]; - if (path === '/') - return [[ROOT_TOKEN]]; - if (!path.startsWith('/')) { - throw new Error(`Route paths should start with a "/": "${path}" should be "/${path}".` - ); - } - // if (tokenCache.has(path)) return tokenCache.get(path)! - function crash(message) { - throw new Error(`ERR (${state})/"${buffer}": ${message}`); - } - let state = 0 /* Static */; - let previousState = state; - const tokens = []; - // the segment will always be valid because we get into the initial state - // with the leading / - let segment; - function finalizeSegment() { - if (segment) - tokens.push(segment); - segment = []; - } - // index on the path - let i = 0; - // char at index - let char; - // buffer of the value read - let buffer = ''; - // custom regexp for a param - let customRe = ''; - function consumeBuffer() { - if (!buffer) - return; - if (state === 0 /* Static */) { - segment.push({ - type: 0 /* Static */, - value: buffer, - }); - } - else if (state === 1 /* Param */ || - state === 2 /* ParamRegExp */ || - state === 3 /* ParamRegExpEnd */) { - if (segment.length > 1 && (char === '*' || char === '+')) - crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`); - segment.push({ - type: 1 /* Param */, - value: buffer, - regexp: customRe, - repeatable: char === '*' || char === '+', - optional: char === '*' || char === '?', - }); - } - else { - crash('Invalid state to consume buffer'); - } - buffer = ''; - } - function addCharToBuffer() { - buffer += char; - } - while (i < path.length) { - char = path[i++]; - if (char === '\\' && state !== 2 /* ParamRegExp */) { - previousState = state; - state = 4 /* EscapeNext */; - continue; - } - switch (state) { - case 0 /* Static */: - if (char === '/') { - if (buffer) { - consumeBuffer(); - } - finalizeSegment(); - } - else if (char === ':') { - consumeBuffer(); - state = 1 /* Param */; - } - else { - addCharToBuffer(); - } - break; - case 4 /* EscapeNext */: - addCharToBuffer(); - state = previousState; - break; - case 1 /* Param */: - if (char === '(') { - state = 2 /* ParamRegExp */; - } - else if (VALID_PARAM_RE.test(char)) { - addCharToBuffer(); - } - else { - consumeBuffer(); - state = 0 /* Static */; - // go back one character if we were not modifying - if (char !== '*' && char !== '?' && char !== '+') - i--; - } - break; - case 2 /* ParamRegExp */: - // TODO: is it worth handling nested regexp? like :p(?:prefix_([^/]+)_suffix) - // it already works by escaping the closing ) - // https://paths.esm.dev/?p=AAMeJbiAwQEcDKbAoAAkP60PG2R6QAvgNaA6AFACM2ABuQBB# - // is this really something people need since you can also write - // /prefix_:p()_suffix - if (char === ')') { - // handle the escaped ) - if (customRe[customRe.length - 1] == '\\') - customRe = customRe.slice(0, -1) + char; - else - state = 3 /* ParamRegExpEnd */; - } - else { - customRe += char; - } - break; - case 3 /* ParamRegExpEnd */: - // same as finalizing a param - consumeBuffer(); - state = 0 /* Static */; - // go back one character if we were not modifying - if (char !== '*' && char !== '?' && char !== '+') - i--; - customRe = ''; - break; - default: - crash('Unknown state'); - break; - } - } - if (state === 2 /* ParamRegExp */) - crash(`Unfinished custom RegExp for param "${buffer}"`); - consumeBuffer(); - finalizeSegment(); - // tokenCache.set(path, tokens) - return tokens; -} - -function createRouteRecordMatcher(record, parent, options) { - const parser = tokensToParser(tokenizePath(record.path), options); - // warn against params with the same name - { - const existingKeys = new Set(); - for (const key of parser.keys) { - if (existingKeys.has(key.name)) - warn(`Found duplicated params with name "${key.name}" for path "${record.path}". Only the last one will be available on "$route.params".`); - existingKeys.add(key.name); - } - } - const matcher = assign(parser, { - record, - parent, - // these needs to be populated by the parent - children: [], - alias: [], - }); - if (parent) { - // both are aliases or both are not aliases - // we don't want to mix them because the order is used when - // passing originalRecord in Matcher.addRoute - if (!matcher.record.aliasOf === !parent.record.aliasOf) - parent.children.push(matcher); - } - return matcher; -} - -/** - * Creates a Router Matcher. - * - * @internal - * @param routes - array of initial routes - * @param globalOptions - global route options - */ -function createRouterMatcher(routes, globalOptions) { - // normalized ordered array of matchers - const matchers = []; - const matcherMap = new Map(); - globalOptions = mergeOptions({ strict: false, end: true, sensitive: false }, globalOptions); - function getRecordMatcher(name) { - return matcherMap.get(name); - } - function addRoute(record, parent, originalRecord) { - // used later on to remove by name - const isRootAdd = !originalRecord; - const mainNormalizedRecord = normalizeRouteRecord(record); - // we might be the child of an alias - mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record; - const options = mergeOptions(globalOptions, record); - // generate an array of records to correctly handle aliases - const normalizedRecords = [ - mainNormalizedRecord, - ]; - if ('alias' in record) { - const aliases = typeof record.alias === 'string' ? [record.alias] : record.alias; - for (const alias of aliases) { - normalizedRecords.push(assign({}, mainNormalizedRecord, { - // this allows us to hold a copy of the `components` option - // so that async components cache is hold on the original record - components: originalRecord - ? originalRecord.record.components - : mainNormalizedRecord.components, - path: alias, - // we might be the child of an alias - aliasOf: originalRecord - ? originalRecord.record - : mainNormalizedRecord, - // the aliases are always of the same kind as the original since they - // are defined on the same record - })); - } - } - let matcher; - let originalMatcher; - for (const normalizedRecord of normalizedRecords) { - const { path } = normalizedRecord; - // Build up the path for nested routes if the child isn't an absolute - // route. Only add the / delimiter if the child path isn't empty and if the - // parent path doesn't have a trailing slash - if (parent && path[0] !== '/') { - const parentPath = parent.record.path; - const connectingSlash = parentPath[parentPath.length - 1] === '/' ? '' : '/'; - normalizedRecord.path = - parent.record.path + (path && connectingSlash + path); - } - if (normalizedRecord.path === '*') { - throw new Error('Catch all routes ("*") must now be defined using a param with a custom regexp.\n' + - 'See more at https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes.'); - } - // create the object before hand so it can be passed to children - matcher = createRouteRecordMatcher(normalizedRecord, parent, options); - if (parent && path[0] === '/') - checkMissingParamsInAbsolutePath(matcher, parent); - // if we are an alias we must tell the original record that we exist - // so we can be removed - if (originalRecord) { - originalRecord.alias.push(matcher); - { - checkSameParams(originalRecord, matcher); - } - } - else { - // otherwise, the first record is the original and others are aliases - originalMatcher = originalMatcher || matcher; - if (originalMatcher !== matcher) - originalMatcher.alias.push(matcher); - // remove the route if named and only for the top record (avoid in nested calls) - // this works because the original record is the first one - if (isRootAdd && record.name && !isAliasRecord(matcher)) - removeRoute(record.name); - } - if ('children' in mainNormalizedRecord) { - const children = mainNormalizedRecord.children; - for (let i = 0; i < children.length; i++) { - addRoute(children[i], matcher, originalRecord && originalRecord.children[i]); - } - } - // if there was no original record, then the first one was not an alias and all - // other alias (if any) need to reference this record when adding children - originalRecord = originalRecord || matcher; - // TODO: add normalized records for more flexibility - // if (parent && isAliasRecord(originalRecord)) { - // parent.children.push(originalRecord) - // } - insertMatcher(matcher); - } - return originalMatcher - ? () => { - // since other matchers are aliases, they should be removed by the original matcher - removeRoute(originalMatcher); - } - : noop; - } - function removeRoute(matcherRef) { - if (isRouteName(matcherRef)) { - const matcher = matcherMap.get(matcherRef); - if (matcher) { - matcherMap.delete(matcherRef); - matchers.splice(matchers.indexOf(matcher), 1); - matcher.children.forEach(removeRoute); - matcher.alias.forEach(removeRoute); - } - } - else { - const index = matchers.indexOf(matcherRef); - if (index > -1) { - matchers.splice(index, 1); - if (matcherRef.record.name) - matcherMap.delete(matcherRef.record.name); - matcherRef.children.forEach(removeRoute); - matcherRef.alias.forEach(removeRoute); - } - } - } - function getRoutes() { - return matchers; - } - function insertMatcher(matcher) { - let i = 0; - while (i < matchers.length && - comparePathParserScore(matcher, matchers[i]) >= 0 && - // Adding children with empty path should still appear before the parent - // https://github.com/vuejs/router/issues/1124 - (matcher.record.path !== matchers[i].record.path || - !isRecordChildOf(matcher, matchers[i]))) - i++; - matchers.splice(i, 0, matcher); - // only add the original record to the name map - if (matcher.record.name && !isAliasRecord(matcher)) - matcherMap.set(matcher.record.name, matcher); - } - function resolve(location, currentLocation) { - let matcher; - let params = {}; - let path; - let name; - if ('name' in location && location.name) { - matcher = matcherMap.get(location.name); - if (!matcher) - throw createRouterError(1 /* MATCHER_NOT_FOUND */, { - location, - }); - name = matcher.record.name; - params = assign( - // paramsFromLocation is a new object - paramsFromLocation(currentLocation.params, - // only keep params that exist in the resolved location - // TODO: only keep optional params coming from a parent record - matcher.keys.filter(k => !k.optional).map(k => k.name)), location.params); - // throws if cannot be stringified - path = matcher.stringify(params); - } - else if ('path' in location) { - // no need to resolve the path with the matcher as it was provided - // this also allows the user to control the encoding - path = location.path; - if (!path.startsWith('/')) { - warn(`The Matcher cannot resolve relative paths but received "${path}". Unless you directly called \`matcher.resolve("${path}")\`, this is probably a bug in vue-router. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/router.`); - } - matcher = matchers.find(m => m.re.test(path)); - // matcher should have a value after the loop - if (matcher) { - // TODO: dev warning of unused params if provided - // we know the matcher works because we tested the regexp - params = matcher.parse(path); - name = matcher.record.name; - } - // location is a relative path - } - else { - // match by name or path of current route - matcher = currentLocation.name - ? matcherMap.get(currentLocation.name) - : matchers.find(m => m.re.test(currentLocation.path)); - if (!matcher) - throw createRouterError(1 /* MATCHER_NOT_FOUND */, { - location, - currentLocation, - }); - name = matcher.record.name; - // since we are navigating to the same location, we don't need to pick the - // params like when `name` is provided - params = assign({}, currentLocation.params, location.params); - path = matcher.stringify(params); - } - const matched = []; - let parentMatcher = matcher; - while (parentMatcher) { - // reversed order so parents are at the beginning - matched.unshift(parentMatcher.record); - parentMatcher = parentMatcher.parent; - } - return { - name, - path, - params, - matched, - meta: mergeMetaFields(matched), - }; - } - // add initial routes - routes.forEach(route => addRoute(route)); - return { addRoute, resolve, removeRoute, getRoutes, getRecordMatcher }; -} -function paramsFromLocation(params, keys) { - const newParams = {}; - for (const key of keys) { - if (key in params) - newParams[key] = params[key]; - } - return newParams; -} -/** - * Normalizes a RouteRecordRaw. Creates a copy - * - * @param record - * @returns the normalized version - */ -function normalizeRouteRecord(record) { - return { - path: record.path, - redirect: record.redirect, - name: record.name, - meta: record.meta || {}, - aliasOf: undefined, - beforeEnter: record.beforeEnter, - props: normalizeRecordProps(record), - children: record.children || [], - instances: {}, - leaveGuards: new Set(), - updateGuards: new Set(), - enterCallbacks: {}, - components: 'components' in record - ? record.components || {} - : { default: record.component }, - }; -} -/** - * Normalize the optional `props` in a record to always be an object similar to - * components. Also accept a boolean for components. - * @param record - */ -function normalizeRecordProps(record) { - const propsObject = {}; - // props does not exist on redirect records but we can set false directly - const props = record.props || false; - if ('component' in record) { - propsObject.default = props; - } - else { - // NOTE: we could also allow a function to be applied to every component. - // Would need user feedback for use cases - for (const name in record.components) - propsObject[name] = typeof props === 'boolean' ? props : props[name]; - } - return propsObject; -} -/** - * Checks if a record or any of its parent is an alias - * @param record - */ -function isAliasRecord(record) { - while (record) { - if (record.record.aliasOf) - return true; - record = record.parent; - } - return false; -} -/** - * Merge meta fields of an array of records - * - * @param matched - array of matched records - */ -function mergeMetaFields(matched) { - return matched.reduce((meta, record) => assign(meta, record.meta), {}); -} -function mergeOptions(defaults, partialOptions) { - const options = {}; - for (const key in defaults) { - options[key] = key in partialOptions ? partialOptions[key] : defaults[key]; - } - return options; -} -function isSameParam(a, b) { - return (a.name === b.name && - a.optional === b.optional && - a.repeatable === b.repeatable); -} -/** - * Check if a path and its alias have the same required params - * - * @param a - original record - * @param b - alias record - */ -function checkSameParams(a, b) { - for (const key of a.keys) { - if (!key.optional && !b.keys.find(isSameParam.bind(null, key))) - return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`); - } - for (const key of b.keys) { - if (!key.optional && !a.keys.find(isSameParam.bind(null, key))) - return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`); - } -} -function checkMissingParamsInAbsolutePath(record, parent) { - for (const key of parent.keys) { - if (!record.keys.find(isSameParam.bind(null, key))) - return warn(`Absolute path "${record.record.path}" should have the exact same param named "${key.name}" as its parent "${parent.record.path}".`); - } -} -function isRecordChildOf(record, parent) { - return parent.children.some(child => child === record || isRecordChildOf(record, child)); -} - -/** - * Encoding Rules ␣ = Space Path: ␣ " < > # ? { } Query: ␣ " < > # & = Hash: ␣ " - * < > ` - * - * On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2) - * defines some extra characters to be encoded. Most browsers do not encode them - * in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to - * also encode `!'()*`. Leaving unencoded only ASCII alphanumeric(`a-zA-Z0-9`) - * plus `-._~`. This extra safety should be applied to query by patching the - * string returned by encodeURIComponent encodeURI also encodes `[\]^`. `\` - * should be encoded to avoid ambiguity. Browsers (IE, FF, C) transform a `\` - * into a `/` if directly typed in. The _backtick_ (`````) should also be - * encoded everywhere because some browsers like FF encode it when directly - * written while others don't. Safari and IE don't encode ``"<>{}``` in hash. - */ -// const EXTRA_RESERVED_RE = /[!'()*]/g -// const encodeReservedReplacer = (c: string) => '%' + c.charCodeAt(0).toString(16) -const HASH_RE = /#/g; // %23 -const AMPERSAND_RE = /&/g; // %26 -const SLASH_RE = /\//g; // %2F -const EQUAL_RE = /=/g; // %3D -const IM_RE = /\?/g; // %3F -const PLUS_RE = /\+/g; // %2B -/** - * NOTE: It's not clear to me if we should encode the + symbol in queries, it - * seems to be less flexible than not doing so and I can't find out the legacy - * systems requiring this for regular requests like text/html. In the standard, - * the encoding of the plus character is only mentioned for - * application/x-www-form-urlencoded - * (https://url.spec.whatwg.org/#urlencoded-parsing) and most browsers seems lo - * leave the plus character as is in queries. To be more flexible, we allow the - * plus character on the query but it can also be manually encoded by the user. - * - * Resources: - * - https://url.spec.whatwg.org/#urlencoded-parsing - * - https://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20 - */ -const ENC_BRACKET_OPEN_RE = /%5B/g; // [ -const ENC_BRACKET_CLOSE_RE = /%5D/g; // ] -const ENC_CARET_RE = /%5E/g; // ^ -const ENC_BACKTICK_RE = /%60/g; // ` -const ENC_CURLY_OPEN_RE = /%7B/g; // { -const ENC_PIPE_RE = /%7C/g; // | -const ENC_CURLY_CLOSE_RE = /%7D/g; // } -const ENC_SPACE_RE = /%20/g; // } -/** - * Encode characters that need to be encoded on the path, search and hash - * sections of the URL. - * - * @internal - * @param text - string to encode - * @returns encoded string - */ -function commonEncode(text) { - return encodeURI('' + text) - .replace(ENC_PIPE_RE, '|') - .replace(ENC_BRACKET_OPEN_RE, '[') - .replace(ENC_BRACKET_CLOSE_RE, ']'); -} -/** - * Encode characters that need to be encoded on the hash section of the URL. - * - * @param text - string to encode - * @returns encoded string - */ -function encodeHash(text) { - return commonEncode(text) - .replace(ENC_CURLY_OPEN_RE, '{') - .replace(ENC_CURLY_CLOSE_RE, '}') - .replace(ENC_CARET_RE, '^'); -} -/** - * Encode characters that need to be encoded query values on the query - * section of the URL. - * - * @param text - string to encode - * @returns encoded string - */ -function encodeQueryValue(text) { - return (commonEncode(text) - // Encode the space as +, encode the + to differentiate it from the space - .replace(PLUS_RE, '%2B') - .replace(ENC_SPACE_RE, '+') - .replace(HASH_RE, '%23') - .replace(AMPERSAND_RE, '%26') - .replace(ENC_BACKTICK_RE, '`') - .replace(ENC_CURLY_OPEN_RE, '{') - .replace(ENC_CURLY_CLOSE_RE, '}') - .replace(ENC_CARET_RE, '^')); -} -/** - * Like `encodeQueryValue` but also encodes the `=` character. - * - * @param text - string to encode - */ -function encodeQueryKey(text) { - return encodeQueryValue(text).replace(EQUAL_RE, '%3D'); -} -/** - * Encode characters that need to be encoded on the path section of the URL. - * - * @param text - string to encode - * @returns encoded string - */ -function encodePath(text) { - return commonEncode(text).replace(HASH_RE, '%23').replace(IM_RE, '%3F'); -} -/** - * Encode characters that need to be encoded on the path section of the URL as a - * param. This function encodes everything {@link encodePath} does plus the - * slash (`/`) character. If `text` is `null` or `undefined`, returns an empty - * string instead. - * - * @param text - string to encode - * @returns encoded string - */ -function encodeParam(text) { - return text == null ? '' : encodePath(text).replace(SLASH_RE, '%2F'); -} -/** - * Decode text using `decodeURIComponent`. Returns the original text if it - * fails. - * - * @param text - string to decode - * @returns decoded string - */ -function decode(text) { - try { - return decodeURIComponent('' + text); - } - catch (err) { - warn(`Error decoding "${text}". Using original value`); - } - return '' + text; -} - -/** - * Transforms a queryString into a {@link LocationQuery} object. Accept both, a - * version with the leading `?` and without Should work as URLSearchParams - - * @internal - * - * @param search - search string to parse - * @returns a query object - */ -function parseQuery(search) { - const query = {}; - // avoid creating an object with an empty key and empty value - // because of split('&') - if (search === '' || search === '?') - return query; - const hasLeadingIM = search[0] === '?'; - const searchParams = (hasLeadingIM ? search.slice(1) : search).split('&'); - for (let i = 0; i < searchParams.length; ++i) { - // pre decode the + into space - const searchParam = searchParams[i].replace(PLUS_RE, ' '); - // allow the = character - const eqPos = searchParam.indexOf('='); - const key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos)); - const value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1)); - if (key in query) { - // an extra variable for ts types - let currentValue = query[key]; - if (!Array.isArray(currentValue)) { - currentValue = query[key] = [currentValue]; - } - currentValue.push(value); - } - else { - query[key] = value; - } - } - return query; -} -/** - * Stringifies a {@link LocationQueryRaw} object. Like `URLSearchParams`, it - * doesn't prepend a `?` - * - * @internal - * - * @param query - query object to stringify - * @returns string version of the query without the leading `?` - */ -function stringifyQuery(query) { - let search = ''; - for (let key in query) { - const value = query[key]; - key = encodeQueryKey(key); - if (value == null) { - // only null adds the value - if (value !== undefined) { - search += (search.length ? '&' : '') + key; - } - continue; - } - // keep null values - const values = Array.isArray(value) - ? value.map(v => v && encodeQueryValue(v)) - : [value && encodeQueryValue(value)]; - values.forEach(value => { - // skip undefined values in arrays as if they were not present - // smaller code than using filter - if (value !== undefined) { - // only append & with non-empty search - search += (search.length ? '&' : '') + key; - if (value != null) - search += '=' + value; - } - }); - } - return search; -} -/** - * Transforms a {@link LocationQueryRaw} into a {@link LocationQuery} by casting - * numbers into strings, removing keys with an undefined value and replacing - * undefined with null in arrays - * - * @param query - query object to normalize - * @returns a normalized query object - */ -function normalizeQuery(query) { - const normalizedQuery = {}; - for (const key in query) { - const value = query[key]; - if (value !== undefined) { - normalizedQuery[key] = Array.isArray(value) - ? value.map(v => (v == null ? null : '' + v)) - : value == null - ? value - : '' + value; - } - } - return normalizedQuery; -} - -/** - * Create a list of callbacks that can be reset. Used to create before and after navigation guards list - */ -function useCallbacks() { - let handlers = []; - function add(handler) { - handlers.push(handler); - return () => { - const i = handlers.indexOf(handler); - if (i > -1) - handlers.splice(i, 1); - }; - } - function reset() { - handlers = []; - } - return { - add, - list: () => handlers, - reset, - }; -} - -function registerGuard(record, name, guard) { - const removeFromList = () => { - record[name].delete(guard); - }; - vue.onUnmounted(removeFromList); - vue.onDeactivated(removeFromList); - vue.onActivated(() => { - record[name].add(guard); - }); - record[name].add(guard); -} -/** - * Add a navigation guard that triggers whenever the component for the current - * location is about to be left. Similar to {@link beforeRouteLeave} but can be - * used in any component. The guard is removed when the component is unmounted. - * - * @param leaveGuard - {@link NavigationGuard} - */ -function onBeforeRouteLeave(leaveGuard) { - if (!vue.getCurrentInstance()) { - warn('getCurrentInstance() returned null. onBeforeRouteLeave() must be called at the top of a setup function'); - return; - } - const activeRecord = vue.inject(matchedRouteKey, - // to avoid warning - {}).value; - if (!activeRecord) { - warn('No active route record was found when calling `onBeforeRouteLeave()`. Make sure you call this function inside of a component child of . Maybe you called it inside of App.vue?'); - return; - } - registerGuard(activeRecord, 'leaveGuards', leaveGuard); -} -/** - * Add a navigation guard that triggers whenever the current location is about - * to be updated. Similar to {@link beforeRouteUpdate} but can be used in any - * component. The guard is removed when the component is unmounted. - * - * @param updateGuard - {@link NavigationGuard} - */ -function onBeforeRouteUpdate(updateGuard) { - if (!vue.getCurrentInstance()) { - warn('getCurrentInstance() returned null. onBeforeRouteUpdate() must be called at the top of a setup function'); - return; - } - const activeRecord = vue.inject(matchedRouteKey, - // to avoid warning - {}).value; - if (!activeRecord) { - warn('No active route record was found when calling `onBeforeRouteUpdate()`. Make sure you call this function inside of a component child of . Maybe you called it inside of App.vue?'); - return; - } - registerGuard(activeRecord, 'updateGuards', updateGuard); -} -function guardToPromiseFn(guard, to, from, record, name) { - // keep a reference to the enterCallbackArray to prevent pushing callbacks if a new navigation took place - const enterCallbackArray = record && - // name is defined if record is because of the function overload - (record.enterCallbacks[name] = record.enterCallbacks[name] || []); - return () => new Promise((resolve, reject) => { - const next = (valid) => { - if (valid === false) - reject(createRouterError(4 /* NAVIGATION_ABORTED */, { - from, - to, - })); - else if (valid instanceof Error) { - reject(valid); - } - else if (isRouteLocation(valid)) { - reject(createRouterError(2 /* NAVIGATION_GUARD_REDIRECT */, { - from: to, - to: valid, - })); - } - else { - if (enterCallbackArray && - // since enterCallbackArray is truthy, both record and name also are - record.enterCallbacks[name] === enterCallbackArray && - typeof valid === 'function') - enterCallbackArray.push(valid); - resolve(); - } - }; - // wrapping with Promise.resolve allows it to work with both async and sync guards - const guardReturn = guard.call(record && record.instances[name], to, from, canOnlyBeCalledOnce(next, to, from) ); - let guardCall = Promise.resolve(guardReturn); - if (guard.length < 3) - guardCall = guardCall.then(next); - if (guard.length > 2) { - const message = `The "next" callback was never called inside of ${guard.name ? '"' + guard.name + '"' : ''}:\n${guard.toString()}\n. If you are returning a value instead of calling "next", make sure to remove the "next" parameter from your function.`; - if (typeof guardReturn === 'object' && 'then' in guardReturn) { - guardCall = guardCall.then(resolvedValue => { - // @ts-expect-error: _called is added at canOnlyBeCalledOnce - if (!next._called) { - warn(message); - return Promise.reject(new Error('Invalid navigation guard')); - } - return resolvedValue; - }); - // TODO: test me! - } - else if (guardReturn !== undefined) { - // @ts-expect-error: _called is added at canOnlyBeCalledOnce - if (!next._called) { - warn(message); - reject(new Error('Invalid navigation guard')); - return; - } - } - } - guardCall.catch(err => reject(err)); - }); -} -function canOnlyBeCalledOnce(next, to, from) { - let called = 0; - return function () { - if (called++ === 1) - warn(`The "next" callback was called more than once in one navigation guard when going from "${from.fullPath}" to "${to.fullPath}". It should be called exactly one time in each navigation guard. This will fail in production.`); - // @ts-expect-error: we put it in the original one because it's easier to check - next._called = true; - if (called === 1) - next.apply(null, arguments); - }; -} -function extractComponentsGuards(matched, guardType, to, from) { - const guards = []; - for (const record of matched) { - for (const name in record.components) { - let rawComponent = record.components[name]; - { - if (!rawComponent || - (typeof rawComponent !== 'object' && - typeof rawComponent !== 'function')) { - warn(`Component "${name}" in record with path "${record.path}" is not` + - ` a valid component. Received "${String(rawComponent)}".`); - // throw to ensure we stop here but warn to ensure the message isn't - // missed by the user - throw new Error('Invalid route component'); - } - else if ('then' in rawComponent) { - // warn if user wrote import('/component.vue') instead of () => - // import('./component.vue') - warn(`Component "${name}" in record with path "${record.path}" is a ` + - `Promise instead of a function that returns a Promise. Did you ` + - `write "import('./MyPage.vue')" instead of ` + - `"() => import('./MyPage.vue')" ? This will break in ` + - `production if not fixed.`); - const promise = rawComponent; - rawComponent = () => promise; - } - else if (rawComponent.__asyncLoader && - // warn only once per component - !rawComponent.__warnedDefineAsync) { - rawComponent.__warnedDefineAsync = true; - warn(`Component "${name}" in record with path "${record.path}" is defined ` + - `using "defineAsyncComponent()". ` + - `Write "() => import('./MyPage.vue')" instead of ` + - `"defineAsyncComponent(() => import('./MyPage.vue'))".`); - } - } - // skip update and leave guards if the route component is not mounted - if (guardType !== 'beforeRouteEnter' && !record.instances[name]) - continue; - if (isRouteComponent(rawComponent)) { - // __vccOpts is added by vue-class-component and contain the regular options - const options = rawComponent.__vccOpts || rawComponent; - const guard = options[guardType]; - guard && guards.push(guardToPromiseFn(guard, to, from, record, name)); - } - else { - // start requesting the chunk already - let componentPromise = rawComponent(); - if (!('catch' in componentPromise)) { - warn(`Component "${name}" in record with path "${record.path}" is a function that does not return a Promise. If you were passing a functional component, make sure to add a "displayName" to the component. This will break in production if not fixed.`); - componentPromise = Promise.resolve(componentPromise); - } - guards.push(() => componentPromise.then(resolved => { - if (!resolved) - return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}"`)); - const resolvedComponent = isESModule(resolved) - ? resolved.default - : resolved; - // replace the function with the resolved component - record.components[name] = resolvedComponent; - // __vccOpts is added by vue-class-component and contain the regular options - const options = resolvedComponent.__vccOpts || resolvedComponent; - const guard = options[guardType]; - return guard && guardToPromiseFn(guard, to, from, record, name)(); - })); - } - } - } - return guards; -} -/** - * Allows differentiating lazy components from functional components and vue-class-component - * - * @param component - */ -function isRouteComponent(component) { - return (typeof component === 'object' || - 'displayName' in component || - 'props' in component || - '__vccOpts' in component); -} - -// TODO: we could allow currentRoute as a prop to expose `isActive` and -// `isExactActive` behavior should go through an RFC -function useLink(props) { - const router = vue.inject(routerKey); - const currentRoute = vue.inject(routeLocationKey); - const route = vue.computed(() => router.resolve(vue.unref(props.to))); - const activeRecordIndex = vue.computed(() => { - const { matched } = route.value; - const { length } = matched; - const routeMatched = matched[length - 1]; - const currentMatched = currentRoute.matched; - if (!routeMatched || !currentMatched.length) - return -1; - const index = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched)); - if (index > -1) - return index; - // possible parent record - const parentRecordPath = getOriginalPath(matched[length - 2]); - return ( - // we are dealing with nested routes - length > 1 && - // if the parent and matched route have the same path, this link is - // referring to the empty child. Or we currently are on a different - // child of the same parent - getOriginalPath(routeMatched) === parentRecordPath && - // avoid comparing the child with its parent - currentMatched[currentMatched.length - 1].path !== parentRecordPath - ? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2])) - : index); - }); - const isActive = vue.computed(() => activeRecordIndex.value > -1 && - includesParams(currentRoute.params, route.value.params)); - const isExactActive = vue.computed(() => activeRecordIndex.value > -1 && - activeRecordIndex.value === currentRoute.matched.length - 1 && - isSameRouteLocationParams(currentRoute.params, route.value.params)); - function navigate(e = {}) { - if (guardEvent(e)) { - return router[vue.unref(props.replace) ? 'replace' : 'push'](vue.unref(props.to) - // avoid uncaught errors are they are logged anyway - ).catch(noop); - } - return Promise.resolve(); - } - // devtools only - if (isBrowser) { - const instance = vue.getCurrentInstance(); - if (instance) { - const linkContextDevtools = { - route: route.value, - isActive: isActive.value, - isExactActive: isExactActive.value, - }; - // @ts-expect-error: this is internal - instance.__vrl_devtools = instance.__vrl_devtools || []; - // @ts-expect-error: this is internal - instance.__vrl_devtools.push(linkContextDevtools); - vue.watchEffect(() => { - linkContextDevtools.route = route.value; - linkContextDevtools.isActive = isActive.value; - linkContextDevtools.isExactActive = isExactActive.value; - }, { flush: 'post' }); - } - } - return { - route, - href: vue.computed(() => route.value.href), - isActive, - isExactActive, - navigate, - }; -} -const RouterLinkImpl = /*#__PURE__*/ vue.defineComponent({ - name: 'RouterLink', - props: { - to: { - type: [String, Object], - required: true, - }, - replace: Boolean, - activeClass: String, - // inactiveClass: String, - exactActiveClass: String, - custom: Boolean, - ariaCurrentValue: { - type: String, - default: 'page', - }, - }, - useLink, - setup(props, { slots }) { - const link = vue.reactive(useLink(props)); - const { options } = vue.inject(routerKey); - const elClass = vue.computed(() => ({ - [getLinkClass(props.activeClass, options.linkActiveClass, 'router-link-active')]: link.isActive, - // [getLinkClass( - // props.inactiveClass, - // options.linkInactiveClass, - // 'router-link-inactive' - // )]: !link.isExactActive, - [getLinkClass(props.exactActiveClass, options.linkExactActiveClass, 'router-link-exact-active')]: link.isExactActive, - })); - return () => { - const children = slots.default && slots.default(link); - return props.custom - ? children - : vue.h('a', { - 'aria-current': link.isExactActive - ? props.ariaCurrentValue - : null, - href: link.href, - // this would override user added attrs but Vue will still add - // the listener so we end up triggering both - onClick: link.navigate, - class: elClass.value, - }, children); - }; - }, -}); -// export the public type for h/tsx inference -// also to avoid inline import() in generated d.ts files -/** - * Component to render a link that triggers a navigation on click. - */ -const RouterLink = RouterLinkImpl; -function guardEvent(e) { - // don't redirect with control keys - if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) - return; - // don't redirect when preventDefault called - if (e.defaultPrevented) - return; - // don't redirect on right click - if (e.button !== undefined && e.button !== 0) - return; - // don't redirect if `target="_blank"` - // @ts-expect-error getAttribute does exist - if (e.currentTarget && e.currentTarget.getAttribute) { - // @ts-expect-error getAttribute exists - const target = e.currentTarget.getAttribute('target'); - if (/\b_blank\b/i.test(target)) - return; - } - // this may be a Weex event which doesn't have this method - if (e.preventDefault) - e.preventDefault(); - return true; -} -function includesParams(outer, inner) { - for (const key in inner) { - const innerValue = inner[key]; - const outerValue = outer[key]; - if (typeof innerValue === 'string') { - if (innerValue !== outerValue) - return false; - } - else { - if (!Array.isArray(outerValue) || - outerValue.length !== innerValue.length || - innerValue.some((value, i) => value !== outerValue[i])) - return false; - } - } - return true; -} -/** - * Get the original path value of a record by following its aliasOf - * @param record - */ -function getOriginalPath(record) { - return record ? (record.aliasOf ? record.aliasOf.path : record.path) : ''; -} -/** - * Utility class to get the active class based on defaults. - * @param propClass - * @param globalClass - * @param defaultClass - */ -const getLinkClass = (propClass, globalClass, defaultClass) => propClass != null - ? propClass - : globalClass != null - ? globalClass - : defaultClass; - -const RouterViewImpl = /*#__PURE__*/ vue.defineComponent({ - name: 'RouterView', - // #674 we manually inherit them - inheritAttrs: false, - props: { - name: { - type: String, - default: 'default', - }, - route: Object, - }, - // Better compat for @vue/compat users - // https://github.com/vuejs/router/issues/1315 - compatConfig: { MODE: 3 }, - setup(props, { attrs, slots }) { - warnDeprecatedUsage(); - const injectedRoute = vue.inject(routerViewLocationKey); - const routeToDisplay = vue.computed(() => props.route || injectedRoute.value); - const depth = vue.inject(viewDepthKey, 0); - const matchedRouteRef = vue.computed(() => routeToDisplay.value.matched[depth]); - vue.provide(viewDepthKey, depth + 1); - vue.provide(matchedRouteKey, matchedRouteRef); - vue.provide(routerViewLocationKey, routeToDisplay); - const viewRef = vue.ref(); - // watch at the same time the component instance, the route record we are - // rendering, and the name - vue.watch(() => [viewRef.value, matchedRouteRef.value, props.name], ([instance, to, name], [oldInstance, from, oldName]) => { - // copy reused instances - if (to) { - // this will update the instance for new instances as well as reused - // instances when navigating to a new route - to.instances[name] = instance; - // the component instance is reused for a different route or name so - // we copy any saved update or leave guards. With async setup, the - // mounting component will mount before the matchedRoute changes, - // making instance === oldInstance, so we check if guards have been - // added before. This works because we remove guards when - // unmounting/deactivating components - if (from && from !== to && instance && instance === oldInstance) { - if (!to.leaveGuards.size) { - to.leaveGuards = from.leaveGuards; - } - if (!to.updateGuards.size) { - to.updateGuards = from.updateGuards; - } - } - } - // trigger beforeRouteEnter next callbacks - if (instance && - to && - // if there is no instance but to and from are the same this might be - // the first visit - (!from || !isSameRouteRecord(to, from) || !oldInstance)) { - (to.enterCallbacks[name] || []).forEach(callback => callback(instance)); - } - }, { flush: 'post' }); - return () => { - const route = routeToDisplay.value; - const matchedRoute = matchedRouteRef.value; - const ViewComponent = matchedRoute && matchedRoute.components[props.name]; - // we need the value at the time we render because when we unmount, we - // navigated to a different location so the value is different - const currentName = props.name; - if (!ViewComponent) { - return normalizeSlot(slots.default, { Component: ViewComponent, route }); - } - // props from route configuration - const routePropsOption = matchedRoute.props[props.name]; - const routeProps = routePropsOption - ? routePropsOption === true - ? route.params - : typeof routePropsOption === 'function' - ? routePropsOption(route) - : routePropsOption - : null; - const onVnodeUnmounted = vnode => { - // remove the instance reference to prevent leak - if (vnode.component.isUnmounted) { - matchedRoute.instances[currentName] = null; - } - }; - const component = vue.h(ViewComponent, assign({}, routeProps, attrs, { - onVnodeUnmounted, - ref: viewRef, - })); - if (isBrowser && - component.ref) { - // TODO: can display if it's an alias, its props - const info = { - depth, - name: matchedRoute.name, - path: matchedRoute.path, - meta: matchedRoute.meta, - }; - const internalInstances = Array.isArray(component.ref) - ? component.ref.map(r => r.i) - : [component.ref.i]; - internalInstances.forEach(instance => { - // @ts-expect-error - instance.__vrv_devtools = info; - }); - } - return ( - // pass the vnode to the slot as a prop. - // h and both accept vnodes - normalizeSlot(slots.default, { Component: component, route }) || - component); - }; - }, -}); -function normalizeSlot(slot, data) { - if (!slot) - return null; - const slotContent = slot(data); - return slotContent.length === 1 ? slotContent[0] : slotContent; -} -// export the public type for h/tsx inference -// also to avoid inline import() in generated d.ts files -/** - * Component to display the current route the user is at. - */ -const RouterView = RouterViewImpl; -// warn against deprecated usage with & -// due to functional component being no longer eager in Vue 3 -function warnDeprecatedUsage() { - const instance = vue.getCurrentInstance(); - const parentName = instance.parent && instance.parent.type.name; - if (parentName && - (parentName === 'KeepAlive' || parentName.includes('Transition'))) { - const comp = parentName === 'KeepAlive' ? 'keep-alive' : 'transition'; - warn(` can no longer be used directly inside or .\n` + - `Use slot props instead:\n\n` + - `\n` + - ` <${comp}>\n` + - ` \n` + - ` \n` + - ``); - } -} - -function formatRouteLocation(routeLocation, tooltip) { - const copy = assign({}, routeLocation, { - // remove variables that can contain vue instances - matched: routeLocation.matched.map(matched => omit(matched, ['instances', 'children', 'aliasOf'])), - }); - return { - _custom: { - type: null, - readOnly: true, - display: routeLocation.fullPath, - tooltip, - value: copy, - }, - }; -} -function formatDisplay(display) { - return { - _custom: { - display, - }, - }; -} -// to support multiple router instances -let routerId = 0; -function addDevtools(app, router, matcher) { - // Take over router.beforeEach and afterEach - // make sure we are not registering the devtool twice - if (router.__hasDevtools) - return; - router.__hasDevtools = true; - // increment to support multiple router instances - const id = routerId++; - devtoolsApi.setupDevtoolsPlugin({ - id: 'org.vuejs.router' + (id ? '.' + id : ''), - label: 'Vue Router', - packageName: 'vue-router', - homepage: 'https://router.vuejs.org', - logo: 'https://router.vuejs.org/logo.png', - componentStateTypes: ['Routing'], - app, - }, api => { - // display state added by the router - api.on.inspectComponent((payload, ctx) => { - if (payload.instanceData) { - payload.instanceData.state.push({ - type: 'Routing', - key: '$route', - editable: false, - value: formatRouteLocation(router.currentRoute.value, 'Current Route'), - }); - } - }); - // mark router-link as active and display tags on router views - api.on.visitComponentTree(({ treeNode: node, componentInstance }) => { - if (componentInstance.__vrv_devtools) { - const info = componentInstance.__vrv_devtools; - node.tags.push({ - label: (info.name ? `${info.name.toString()}: ` : '') + info.path, - textColor: 0, - tooltip: 'This component is rendered by <router-view>', - backgroundColor: PINK_500, - }); - } - // if multiple useLink are used - if (Array.isArray(componentInstance.__vrl_devtools)) { - componentInstance.__devtoolsApi = api; - componentInstance.__vrl_devtools.forEach(devtoolsData => { - let backgroundColor = ORANGE_400; - let tooltip = ''; - if (devtoolsData.isExactActive) { - backgroundColor = LIME_500; - tooltip = 'This is exactly active'; - } - else if (devtoolsData.isActive) { - backgroundColor = BLUE_600; - tooltip = 'This link is active'; - } - node.tags.push({ - label: devtoolsData.route.path, - textColor: 0, - tooltip, - backgroundColor, - }); - }); - } - }); - vue.watch(router.currentRoute, () => { - // refresh active state - refreshRoutesView(); - api.notifyComponentUpdate(); - api.sendInspectorTree(routerInspectorId); - api.sendInspectorState(routerInspectorId); - }); - const navigationsLayerId = 'router:navigations:' + id; - api.addTimelineLayer({ - id: navigationsLayerId, - label: `Router${id ? ' ' + id : ''} Navigations`, - color: 0x40a8c4, - }); - // const errorsLayerId = 'router:errors' - // api.addTimelineLayer({ - // id: errorsLayerId, - // label: 'Router Errors', - // color: 0xea5455, - // }) - router.onError((error, to) => { - api.addTimelineEvent({ - layerId: navigationsLayerId, - event: { - title: 'Error during Navigation', - subtitle: to.fullPath, - logType: 'error', - time: api.now(), - data: { error }, - groupId: to.meta.__navigationId, - }, - }); - }); - // attached to `meta` and used to group events - let navigationId = 0; - router.beforeEach((to, from) => { - const data = { - guard: formatDisplay('beforeEach'), - from: formatRouteLocation(from, 'Current Location during this navigation'), - to: formatRouteLocation(to, 'Target location'), - }; - // Used to group navigations together, hide from devtools - Object.defineProperty(to.meta, '__navigationId', { - value: navigationId++, - }); - api.addTimelineEvent({ - layerId: navigationsLayerId, - event: { - time: api.now(), - title: 'Start of navigation', - subtitle: to.fullPath, - data, - groupId: to.meta.__navigationId, - }, - }); - }); - router.afterEach((to, from, failure) => { - const data = { - guard: formatDisplay('afterEach'), - }; - if (failure) { - data.failure = { - _custom: { - type: Error, - readOnly: true, - display: failure ? failure.message : '', - tooltip: 'Navigation Failure', - value: failure, - }, - }; - data.status = formatDisplay('❌'); - } - else { - data.status = formatDisplay('✅'); - } - // we set here to have the right order - data.from = formatRouteLocation(from, 'Current Location during this navigation'); - data.to = formatRouteLocation(to, 'Target location'); - api.addTimelineEvent({ - layerId: navigationsLayerId, - event: { - title: 'End of navigation', - subtitle: to.fullPath, - time: api.now(), - data, - logType: failure ? 'warning' : 'default', - groupId: to.meta.__navigationId, - }, - }); - }); - /** - * Inspector of Existing routes - */ - const routerInspectorId = 'router-inspector:' + id; - api.addInspector({ - id: routerInspectorId, - label: 'Routes' + (id ? ' ' + id : ''), - icon: 'book', - treeFilterPlaceholder: 'Search routes', - }); - function refreshRoutesView() { - // the routes view isn't active - if (!activeRoutesPayload) - return; - const payload = activeRoutesPayload; - // children routes will appear as nested - let routes = matcher.getRoutes().filter(route => !route.parent); - // reset match state to false - routes.forEach(resetMatchStateOnRouteRecord); - // apply a match state if there is a payload - if (payload.filter) { - routes = routes.filter(route => - // save matches state based on the payload - isRouteMatching(route, payload.filter.toLowerCase())); - } - // mark active routes - routes.forEach(route => markRouteRecordActive(route, router.currentRoute.value)); - payload.rootNodes = routes.map(formatRouteRecordForInspector); - } - let activeRoutesPayload; - api.on.getInspectorTree(payload => { - activeRoutesPayload = payload; - if (payload.app === app && payload.inspectorId === routerInspectorId) { - refreshRoutesView(); - } - }); - /** - * Display information about the currently selected route record - */ - api.on.getInspectorState(payload => { - if (payload.app === app && payload.inspectorId === routerInspectorId) { - const routes = matcher.getRoutes(); - const route = routes.find(route => route.record.__vd_id === payload.nodeId); - if (route) { - payload.state = { - options: formatRouteRecordMatcherForStateInspector(route), - }; - } - } - }); - api.sendInspectorTree(routerInspectorId); - api.sendInspectorState(routerInspectorId); - }); -} -function modifierForKey(key) { - if (key.optional) { - return key.repeatable ? '*' : '?'; - } - else { - return key.repeatable ? '+' : ''; - } -} -function formatRouteRecordMatcherForStateInspector(route) { - const { record } = route; - const fields = [ - { editable: false, key: 'path', value: record.path }, - ]; - if (record.name != null) { - fields.push({ - editable: false, - key: 'name', - value: record.name, - }); - } - fields.push({ editable: false, key: 'regexp', value: route.re }); - if (route.keys.length) { - fields.push({ - editable: false, - key: 'keys', - value: { - _custom: { - type: null, - readOnly: true, - display: route.keys - .map(key => `${key.name}${modifierForKey(key)}`) - .join(' '), - tooltip: 'Param keys', - value: route.keys, - }, - }, - }); - } - if (record.redirect != null) { - fields.push({ - editable: false, - key: 'redirect', - value: record.redirect, - }); - } - if (route.alias.length) { - fields.push({ - editable: false, - key: 'aliases', - value: route.alias.map(alias => alias.record.path), - }); - } - fields.push({ - key: 'score', - editable: false, - value: { - _custom: { - type: null, - readOnly: true, - display: route.score.map(score => score.join(', ')).join(' | '), - tooltip: 'Score used to sort routes', - value: route.score, - }, - }, - }); - return fields; -} -/** - * Extracted from tailwind palette - */ -const PINK_500 = 0xec4899; -const BLUE_600 = 0x2563eb; -const LIME_500 = 0x84cc16; -const CYAN_400 = 0x22d3ee; -const ORANGE_400 = 0xfb923c; -// const GRAY_100 = 0xf4f4f5 -const DARK = 0x666666; -function formatRouteRecordForInspector(route) { - const tags = []; - const { record } = route; - if (record.name != null) { - tags.push({ - label: String(record.name), - textColor: 0, - backgroundColor: CYAN_400, - }); - } - if (record.aliasOf) { - tags.push({ - label: 'alias', - textColor: 0, - backgroundColor: ORANGE_400, - }); - } - if (route.__vd_match) { - tags.push({ - label: 'matches', - textColor: 0, - backgroundColor: PINK_500, - }); - } - if (route.__vd_exactActive) { - tags.push({ - label: 'exact', - textColor: 0, - backgroundColor: LIME_500, - }); - } - if (route.__vd_active) { - tags.push({ - label: 'active', - textColor: 0, - backgroundColor: BLUE_600, - }); - } - if (record.redirect) { - tags.push({ - label: 'redirect: ' + - (typeof record.redirect === 'string' ? record.redirect : 'Object'), - textColor: 0xffffff, - backgroundColor: DARK, - }); - } - // add an id to be able to select it. Using the `path` is not possible because - // empty path children would collide with their parents - let id = record.__vd_id; - if (id == null) { - id = String(routeRecordId++); - record.__vd_id = id; - } - return { - id, - label: record.path, - tags, - children: route.children.map(formatRouteRecordForInspector), - }; -} -// incremental id for route records and inspector state -let routeRecordId = 0; -const EXTRACT_REGEXP_RE = /^\/(.*)\/([a-z]*)$/; -function markRouteRecordActive(route, currentRoute) { - // no route will be active if matched is empty - // reset the matching state - const isExactActive = currentRoute.matched.length && - isSameRouteRecord(currentRoute.matched[currentRoute.matched.length - 1], route.record); - route.__vd_exactActive = route.__vd_active = isExactActive; - if (!isExactActive) { - route.__vd_active = currentRoute.matched.some(match => isSameRouteRecord(match, route.record)); - } - route.children.forEach(childRoute => markRouteRecordActive(childRoute, currentRoute)); -} -function resetMatchStateOnRouteRecord(route) { - route.__vd_match = false; - route.children.forEach(resetMatchStateOnRouteRecord); -} -function isRouteMatching(route, filter) { - const found = String(route.re).match(EXTRACT_REGEXP_RE); - route.__vd_match = false; - if (!found || found.length < 3) { - return false; - } - // use a regexp without $ at the end to match nested routes better - const nonEndingRE = new RegExp(found[1].replace(/\$$/, ''), found[2]); - if (nonEndingRE.test(filter)) { - // mark children as matches - route.children.forEach(child => isRouteMatching(child, filter)); - // exception case: `/` - if (route.record.path !== '/' || filter === '/') { - route.__vd_match = route.re.test(filter); - return true; - } - // hide the / route - return false; - } - const path = route.record.path.toLowerCase(); - const decodedPath = decode(path); - // also allow partial matching on the path - if (!filter.startsWith('/') && - (decodedPath.includes(filter) || path.includes(filter))) - return true; - if (decodedPath.startsWith(filter) || path.startsWith(filter)) - return true; - if (route.record.name && String(route.record.name).includes(filter)) - return true; - return route.children.some(child => isRouteMatching(child, filter)); -} -function omit(obj, keys) { - const ret = {}; - for (const key in obj) { - if (!keys.includes(key)) { - // @ts-expect-error - ret[key] = obj[key]; - } - } - return ret; -} - -/** - * Creates a Router instance that can be used by a Vue app. - * - * @param options - {@link RouterOptions} - */ -function createRouter(options) { - const matcher = createRouterMatcher(options.routes, options); - const parseQuery$1 = options.parseQuery || parseQuery; - const stringifyQuery$1 = options.stringifyQuery || stringifyQuery; - const routerHistory = options.history; - if (!routerHistory) - throw new Error('Provide the "history" option when calling "createRouter()":' + - ' https://next.router.vuejs.org/api/#history.'); - const beforeGuards = useCallbacks(); - const beforeResolveGuards = useCallbacks(); - const afterGuards = useCallbacks(); - const currentRoute = vue.shallowRef(START_LOCATION_NORMALIZED); - let pendingLocation = START_LOCATION_NORMALIZED; - // leave the scrollRestoration if no scrollBehavior is provided - if (isBrowser && options.scrollBehavior && 'scrollRestoration' in history) { - history.scrollRestoration = 'manual'; - } - const normalizeParams = applyToParams.bind(null, paramValue => '' + paramValue); - const encodeParams = applyToParams.bind(null, encodeParam); - const decodeParams = - // @ts-expect-error: intentionally avoid the type check - applyToParams.bind(null, decode); - function addRoute(parentOrRoute, route) { - let parent; - let record; - if (isRouteName(parentOrRoute)) { - parent = matcher.getRecordMatcher(parentOrRoute); - record = route; - } - else { - record = parentOrRoute; - } - return matcher.addRoute(record, parent); - } - function removeRoute(name) { - const recordMatcher = matcher.getRecordMatcher(name); - if (recordMatcher) { - matcher.removeRoute(recordMatcher); - } - else { - warn(`Cannot remove non-existent route "${String(name)}"`); - } - } - function getRoutes() { - return matcher.getRoutes().map(routeMatcher => routeMatcher.record); - } - function hasRoute(name) { - return !!matcher.getRecordMatcher(name); - } - function resolve(rawLocation, currentLocation) { - // const objectLocation = routerLocationAsObject(rawLocation) - // we create a copy to modify it later - currentLocation = assign({}, currentLocation || currentRoute.value); - if (typeof rawLocation === 'string') { - const locationNormalized = parseURL(parseQuery$1, rawLocation, currentLocation.path); - const matchedRoute = matcher.resolve({ path: locationNormalized.path }, currentLocation); - const href = routerHistory.createHref(locationNormalized.fullPath); - { - if (href.startsWith('//')) - warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`); - else if (!matchedRoute.matched.length) { - warn(`No match found for location with path "${rawLocation}"`); - } - } - // locationNormalized is always a new object - return assign(locationNormalized, matchedRoute, { - params: decodeParams(matchedRoute.params), - hash: decode(locationNormalized.hash), - redirectedFrom: undefined, - href, - }); - } - let matcherLocation; - // path could be relative in object as well - if ('path' in rawLocation) { - if ('params' in rawLocation && - !('name' in rawLocation) && - // @ts-expect-error: the type is never - Object.keys(rawLocation.params).length) { - warn(`Path "${ - // @ts-expect-error: the type is never - rawLocation.path}" was passed with params but they will be ignored. Use a named route alongside params instead.`); - } - matcherLocation = assign({}, rawLocation, { - path: parseURL(parseQuery$1, rawLocation.path, currentLocation.path).path, - }); - } - else { - // remove any nullish param - const targetParams = assign({}, rawLocation.params); - for (const key in targetParams) { - if (targetParams[key] == null) { - delete targetParams[key]; - } - } - // pass encoded values to the matcher so it can produce encoded path and fullPath - matcherLocation = assign({}, rawLocation, { - params: encodeParams(rawLocation.params), - }); - // current location params are decoded, we need to encode them in case the - // matcher merges the params - currentLocation.params = encodeParams(currentLocation.params); - } - const matchedRoute = matcher.resolve(matcherLocation, currentLocation); - const hash = rawLocation.hash || ''; - if (hash && !hash.startsWith('#')) { - warn(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`); - } - // decoding them) the matcher might have merged current location params so - // we need to run the decoding again - matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params)); - const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, { - hash: encodeHash(hash), - path: matchedRoute.path, - })); - const href = routerHistory.createHref(fullPath); - { - if (href.startsWith('//')) { - warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`); - } - else if (!matchedRoute.matched.length) { - warn(`No match found for location with path "${'path' in rawLocation ? rawLocation.path : rawLocation}"`); - } - } - return assign({ - fullPath, - // keep the hash encoded so fullPath is effectively path + encodedQuery + - // hash - hash, - query: - // if the user is using a custom query lib like qs, we might have - // nested objects, so we keep the query as is, meaning it can contain - // numbers at `$route.query`, but at the point, the user will have to - // use their own type anyway. - // https://github.com/vuejs/router/issues/328#issuecomment-649481567 - stringifyQuery$1 === stringifyQuery - ? normalizeQuery(rawLocation.query) - : (rawLocation.query || {}), - }, matchedRoute, { - redirectedFrom: undefined, - href, - }); - } - function locationAsObject(to) { - return typeof to === 'string' - ? parseURL(parseQuery$1, to, currentRoute.value.path) - : assign({}, to); - } - function checkCanceledNavigation(to, from) { - if (pendingLocation !== to) { - return createRouterError(8 /* NAVIGATION_CANCELLED */, { - from, - to, - }); - } - } - function push(to) { - return pushWithRedirect(to); - } - function replace(to) { - return push(assign(locationAsObject(to), { replace: true })); - } - function handleRedirectRecord(to) { - const lastMatched = to.matched[to.matched.length - 1]; - if (lastMatched && lastMatched.redirect) { - const { redirect } = lastMatched; - let newTargetLocation = typeof redirect === 'function' ? redirect(to) : redirect; - if (typeof newTargetLocation === 'string') { - newTargetLocation = - newTargetLocation.includes('?') || newTargetLocation.includes('#') - ? (newTargetLocation = locationAsObject(newTargetLocation)) - : // force empty params - { path: newTargetLocation }; - // @ts-expect-error: force empty params when a string is passed to let - // the router parse them again - newTargetLocation.params = {}; - } - if (!('path' in newTargetLocation) && - !('name' in newTargetLocation)) { - warn(`Invalid redirect found:\n${JSON.stringify(newTargetLocation, null, 2)}\n when navigating to "${to.fullPath}". A redirect must contain a name or path. This will break in production.`); - throw new Error('Invalid redirect'); - } - return assign({ - query: to.query, - hash: to.hash, - params: to.params, - }, newTargetLocation); - } - } - function pushWithRedirect(to, redirectedFrom) { - const targetLocation = (pendingLocation = resolve(to)); - const from = currentRoute.value; - const data = to.state; - const force = to.force; - // to could be a string where `replace` is a function - const replace = to.replace === true; - const shouldRedirect = handleRedirectRecord(targetLocation); - if (shouldRedirect) - return pushWithRedirect(assign(locationAsObject(shouldRedirect), { - state: data, - force, - replace, - }), - // keep original redirectedFrom if it exists - redirectedFrom || targetLocation); - // if it was a redirect we already called `pushWithRedirect` above - const toLocation = targetLocation; - toLocation.redirectedFrom = redirectedFrom; - let failure; - if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) { - failure = createRouterError(16 /* NAVIGATION_DUPLICATED */, { to: toLocation, from }); - // trigger scroll to allow scrolling to the same anchor - handleScroll(from, from, - // this is a push, the only way for it to be triggered from a - // history.listen is with a redirect, which makes it become a push - true, - // This cannot be the first navigation because the initial location - // cannot be manually navigated to - false); - } - return (failure ? Promise.resolve(failure) : navigate(toLocation, from)) - .catch((error) => isNavigationFailure(error) - ? // navigation redirects still mark the router as ready - isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */) - ? error - : markAsReady(error) // also returns the error - : // reject any unknown error - triggerError(error, toLocation, from)) - .then((failure) => { - if (failure) { - if (isNavigationFailure(failure, 2 /* NAVIGATION_GUARD_REDIRECT */)) { - if (// we are redirecting to the same location we were already at - isSameRouteLocation(stringifyQuery$1, resolve(failure.to), toLocation) && - // and we have done it a couple of times - redirectedFrom && - // @ts-expect-error: added only in dev - (redirectedFrom._count = redirectedFrom._count - ? // @ts-expect-error - redirectedFrom._count + 1 - : 1) > 10) { - warn(`Detected an infinite redirection in a navigation guard when going from "${from.fullPath}" to "${toLocation.fullPath}". Aborting to avoid a Stack Overflow. This will break in production if not fixed.`); - return Promise.reject(new Error('Infinite redirect in navigation guard')); - } - return pushWithRedirect( - // keep options - assign(locationAsObject(failure.to), { - state: data, - force, - replace, - }), - // preserve the original redirectedFrom if any - redirectedFrom || toLocation); - } - } - else { - // if we fail we don't finalize the navigation - failure = finalizeNavigation(toLocation, from, true, replace, data); - } - triggerAfterEach(toLocation, from, failure); - return failure; - }); - } - /** - * Helper to reject and skip all navigation guards if a new navigation happened - * @param to - * @param from - */ - function checkCanceledNavigationAndReject(to, from) { - const error = checkCanceledNavigation(to, from); - return error ? Promise.reject(error) : Promise.resolve(); - } - // TODO: refactor the whole before guards by internally using router.beforeEach - function navigate(to, from) { - let guards; - const [leavingRecords, updatingRecords, enteringRecords] = extractChangingRecords(to, from); - // all components here have been resolved once because we are leaving - guards = extractComponentsGuards(leavingRecords.reverse(), 'beforeRouteLeave', to, from); - // leavingRecords is already reversed - for (const record of leavingRecords) { - record.leaveGuards.forEach(guard => { - guards.push(guardToPromiseFn(guard, to, from)); - }); - } - const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from); - guards.push(canceledNavigationCheck); - // run the queue of per route beforeRouteLeave guards - return (runGuardQueue(guards) - .then(() => { - // check global guards beforeEach - guards = []; - for (const guard of beforeGuards.list()) { - guards.push(guardToPromiseFn(guard, to, from)); - } - guards.push(canceledNavigationCheck); - return runGuardQueue(guards); - }) - .then(() => { - // check in components beforeRouteUpdate - guards = extractComponentsGuards(updatingRecords, 'beforeRouteUpdate', to, from); - for (const record of updatingRecords) { - record.updateGuards.forEach(guard => { - guards.push(guardToPromiseFn(guard, to, from)); - }); - } - guards.push(canceledNavigationCheck); - // run the queue of per route beforeEnter guards - return runGuardQueue(guards); - }) - .then(() => { - // check the route beforeEnter - guards = []; - for (const record of to.matched) { - // do not trigger beforeEnter on reused views - if (record.beforeEnter && !from.matched.includes(record)) { - if (Array.isArray(record.beforeEnter)) { - for (const beforeEnter of record.beforeEnter) - guards.push(guardToPromiseFn(beforeEnter, to, from)); - } - else { - guards.push(guardToPromiseFn(record.beforeEnter, to, from)); - } - } - } - guards.push(canceledNavigationCheck); - // run the queue of per route beforeEnter guards - return runGuardQueue(guards); - }) - .then(() => { - // NOTE: at this point to.matched is normalized and does not contain any () => Promise - // clear existing enterCallbacks, these are added by extractComponentsGuards - to.matched.forEach(record => (record.enterCallbacks = {})); - // check in-component beforeRouteEnter - guards = extractComponentsGuards(enteringRecords, 'beforeRouteEnter', to, from); - guards.push(canceledNavigationCheck); - // run the queue of per route beforeEnter guards - return runGuardQueue(guards); - }) - .then(() => { - // check global guards beforeResolve - guards = []; - for (const guard of beforeResolveGuards.list()) { - guards.push(guardToPromiseFn(guard, to, from)); - } - guards.push(canceledNavigationCheck); - return runGuardQueue(guards); - }) - // catch any navigation canceled - .catch(err => isNavigationFailure(err, 8 /* NAVIGATION_CANCELLED */) - ? err - : Promise.reject(err))); - } - function triggerAfterEach(to, from, failure) { - // navigation is confirmed, call afterGuards - // TODO: wrap with error handlers - for (const guard of afterGuards.list()) - guard(to, from, failure); - } - /** - * - Cleans up any navigation guards - * - Changes the url if necessary - * - Calls the scrollBehavior - */ - function finalizeNavigation(toLocation, from, isPush, replace, data) { - // a more recent navigation took place - const error = checkCanceledNavigation(toLocation, from); - if (error) - return error; - // only consider as push if it's not the first navigation - const isFirstNavigation = from === START_LOCATION_NORMALIZED; - const state = !isBrowser ? {} : history.state; - // change URL only if the user did a push/replace and if it's not the initial navigation because - // it's just reflecting the url - if (isPush) { - // on the initial navigation, we want to reuse the scroll position from - // history state if it exists - if (replace || isFirstNavigation) - routerHistory.replace(toLocation.fullPath, assign({ - scroll: isFirstNavigation && state && state.scroll, - }, data)); - else - routerHistory.push(toLocation.fullPath, data); - } - // accept current navigation - currentRoute.value = toLocation; - handleScroll(toLocation, from, isPush, isFirstNavigation); - markAsReady(); - } - let removeHistoryListener; - // attach listener to history to trigger navigations - function setupListeners() { - // avoid setting up listeners twice due to an invalid first navigation - if (removeHistoryListener) - return; - removeHistoryListener = routerHistory.listen((to, _from, info) => { - // cannot be a redirect route because it was in history - const toLocation = resolve(to); - // due to dynamic routing, and to hash history with manual navigation - // (manually changing the url or calling history.hash = '#/somewhere'), - // there could be a redirect record in history - const shouldRedirect = handleRedirectRecord(toLocation); - if (shouldRedirect) { - pushWithRedirect(assign(shouldRedirect, { replace: true }), toLocation).catch(noop); - return; - } - pendingLocation = toLocation; - const from = currentRoute.value; - // TODO: should be moved to web history? - if (isBrowser) { - saveScrollPosition(getScrollKey(from.fullPath, info.delta), computeScrollPosition()); - } - navigate(toLocation, from) - .catch((error) => { - if (isNavigationFailure(error, 4 /* NAVIGATION_ABORTED */ | 8 /* NAVIGATION_CANCELLED */)) { - return error; - } - if (isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */)) { - // Here we could call if (info.delta) routerHistory.go(-info.delta, - // false) but this is bug prone as we have no way to wait the - // navigation to be finished before calling pushWithRedirect. Using - // a setTimeout of 16ms seems to work but there is not guarantee for - // it to work on every browser. So Instead we do not restore the - // history entry and trigger a new navigation as requested by the - // navigation guard. - // the error is already handled by router.push we just want to avoid - // logging the error - pushWithRedirect(error.to, toLocation - // avoid an uncaught rejection, let push call triggerError - ) - .then(failure => { - // manual change in hash history #916 ending up in the URL not - // changing but it was changed by the manual url change, so we - // need to manually change it ourselves - if (isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ | - 16 /* NAVIGATION_DUPLICATED */) && - !info.delta && - info.type === NavigationType.pop) { - routerHistory.go(-1, false); - } - }) - .catch(noop); - // avoid the then branch - return Promise.reject(); - } - // do not restore history on unknown direction - if (info.delta) - routerHistory.go(-info.delta, false); - // unrecognized error, transfer to the global handler - return triggerError(error, toLocation, from); - }) - .then((failure) => { - failure = - failure || - finalizeNavigation( - // after navigation, all matched components are resolved - toLocation, from, false); - // revert the navigation - if (failure) { - if (info.delta) { - routerHistory.go(-info.delta, false); - } - else if (info.type === NavigationType.pop && - isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ | 16 /* NAVIGATION_DUPLICATED */)) { - // manual change in hash history #916 - // it's like a push but lacks the information of the direction - routerHistory.go(-1, false); - } - } - triggerAfterEach(toLocation, from, failure); - }) - .catch(noop); - }); - } - // Initialization and Errors - let readyHandlers = useCallbacks(); - let errorHandlers = useCallbacks(); - let ready; - /** - * Trigger errorHandlers added via onError and throws the error as well - * - * @param error - error to throw - * @param to - location we were navigating to when the error happened - * @param from - location we were navigating from when the error happened - * @returns the error as a rejected promise - */ - function triggerError(error, to, from) { - markAsReady(error); - const list = errorHandlers.list(); - if (list.length) { - list.forEach(handler => handler(error, to, from)); - } - else { - { - warn('uncaught error during route navigation:'); - } - console.error(error); - } - return Promise.reject(error); - } - function isReady() { - if (ready && currentRoute.value !== START_LOCATION_NORMALIZED) - return Promise.resolve(); - return new Promise((resolve, reject) => { - readyHandlers.add([resolve, reject]); - }); - } - function markAsReady(err) { - if (!ready) { - // still not ready if an error happened - ready = !err; - setupListeners(); - readyHandlers - .list() - .forEach(([resolve, reject]) => (err ? reject(err) : resolve())); - readyHandlers.reset(); - } - return err; - } - // Scroll behavior - function handleScroll(to, from, isPush, isFirstNavigation) { - const { scrollBehavior } = options; - if (!isBrowser || !scrollBehavior) - return Promise.resolve(); - const scrollPosition = (!isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0))) || - ((isFirstNavigation || !isPush) && - history.state && - history.state.scroll) || - null; - return vue.nextTick() - .then(() => scrollBehavior(to, from, scrollPosition)) - .then(position => position && scrollToPosition(position)) - .catch(err => triggerError(err, to, from)); - } - const go = (delta) => routerHistory.go(delta); - let started; - const installedApps = new Set(); - const router = { - currentRoute, - addRoute, - removeRoute, - hasRoute, - getRoutes, - resolve, - options, - push, - replace, - go, - back: () => go(-1), - forward: () => go(1), - beforeEach: beforeGuards.add, - beforeResolve: beforeResolveGuards.add, - afterEach: afterGuards.add, - onError: errorHandlers.add, - isReady, - install(app) { - const router = this; - app.component('RouterLink', RouterLink); - app.component('RouterView', RouterView); - app.config.globalProperties.$router = router; - Object.defineProperty(app.config.globalProperties, '$route', { - enumerable: true, - get: () => vue.unref(currentRoute), - }); - // this initial navigation is only necessary on client, on server it doesn't - // make sense because it will create an extra unnecessary navigation and could - // lead to problems - if (isBrowser && - // used for the initial navigation client side to avoid pushing - // multiple times when the router is used in multiple apps - !started && - currentRoute.value === START_LOCATION_NORMALIZED) { - // see above - started = true; - push(routerHistory.location).catch(err => { - warn('Unexpected error when starting the router:', err); - }); - } - const reactiveRoute = {}; - for (const key in START_LOCATION_NORMALIZED) { - // @ts-expect-error: the key matches - reactiveRoute[key] = vue.computed(() => currentRoute.value[key]); - } - app.provide(routerKey, router); - app.provide(routeLocationKey, vue.reactive(reactiveRoute)); - app.provide(routerViewLocationKey, currentRoute); - const unmountApp = app.unmount; - installedApps.add(app); - app.unmount = function () { - installedApps.delete(app); - // the router is not attached to an app anymore - if (installedApps.size < 1) { - // invalidate the current navigation - pendingLocation = START_LOCATION_NORMALIZED; - removeHistoryListener && removeHistoryListener(); - removeHistoryListener = null; - currentRoute.value = START_LOCATION_NORMALIZED; - started = false; - ready = false; - } - unmountApp(); - }; - if (isBrowser) { - addDevtools(app, router, matcher); - } - }, - }; - return router; -} -function runGuardQueue(guards) { - return guards.reduce((promise, guard) => promise.then(() => guard()), Promise.resolve()); -} -function extractChangingRecords(to, from) { - const leavingRecords = []; - const updatingRecords = []; - const enteringRecords = []; - const len = Math.max(from.matched.length, to.matched.length); - for (let i = 0; i < len; i++) { - const recordFrom = from.matched[i]; - if (recordFrom) { - if (to.matched.find(record => isSameRouteRecord(record, recordFrom))) - updatingRecords.push(recordFrom); - else - leavingRecords.push(recordFrom); - } - const recordTo = to.matched[i]; - if (recordTo) { - // the type doesn't matter because we are comparing per reference - if (!from.matched.find(record => isSameRouteRecord(record, recordTo))) { - enteringRecords.push(recordTo); - } - } - } - return [leavingRecords, updatingRecords, enteringRecords]; -} - -/** - * Returns the router instance. Equivalent to using `$router` inside - * templates. - */ -function useRouter() { - return vue.inject(routerKey); -} -/** - * Returns the current route location. Equivalent to using `$route` inside - * templates. - */ -function useRoute() { - return vue.inject(routeLocationKey); -} - -exports.RouterLink = RouterLink; -exports.RouterView = RouterView; -exports.START_LOCATION = START_LOCATION_NORMALIZED; -exports.createMemoryHistory = createMemoryHistory; -exports.createRouter = createRouter; -exports.createRouterMatcher = createRouterMatcher; -exports.createWebHashHistory = createWebHashHistory; -exports.createWebHistory = createWebHistory; -exports.isNavigationFailure = isNavigationFailure; -exports.matchedRouteKey = matchedRouteKey; -exports.onBeforeRouteLeave = onBeforeRouteLeave; -exports.onBeforeRouteUpdate = onBeforeRouteUpdate; -exports.parseQuery = parseQuery; -exports.routeLocationKey = routeLocationKey; -exports.routerKey = routerKey; -exports.routerViewLocationKey = routerViewLocationKey; -exports.stringifyQuery = stringifyQuery; -exports.useLink = useLink; -exports.useRoute = useRoute; -exports.useRouter = useRouter; -exports.viewDepthKey = viewDepthKey; +module.exports = require('../dist/vue-router.cjs') \ No newline at end of file diff --git a/node_modules/vue-router/dist/vue-router.cjs.prod.js b/node_modules/vue-router/dist/vue-router.cjs.prod.js index 118f7ca..b6d8d59 100644 --- a/node_modules/vue-router/dist/vue-router.cjs.prod.js +++ b/node_modules/vue-router/dist/vue-router.cjs.prod.js @@ -1,2748 +1 @@ -/*! - * vue-router v4.0.15 - * (c) 2022 Eduardo San Martin Morote - * @license MIT - */ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var vue = require('vue'); -require('@vue/devtools-api'); - -const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -const PolySymbol = (name) => -// vr = vue router -hasSymbol - ? Symbol(name) - : ('_vr_') + name; -// rvlm = Router View Location Matched -/** - * RouteRecord being rendered by the closest ancestor Router View. Used for - * `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View - * Location Matched - * - * @internal - */ -const matchedRouteKey = /*#__PURE__*/ PolySymbol('rvlm'); -/** - * Allows overriding the router view depth to control which component in - * `matched` is rendered. rvd stands for Router View Depth - * - * @internal - */ -const viewDepthKey = /*#__PURE__*/ PolySymbol('rvd'); -/** - * Allows overriding the router instance returned by `useRouter` in tests. r - * stands for router - * - * @internal - */ -const routerKey = /*#__PURE__*/ PolySymbol('r'); -/** - * Allows overriding the current route returned by `useRoute` in tests. rl - * stands for route location - * - * @internal - */ -const routeLocationKey = /*#__PURE__*/ PolySymbol('rl'); -/** - * Allows overriding the current route used by router-view. Internally this is - * used when the `route` prop is passed. - * - * @internal - */ -const routerViewLocationKey = /*#__PURE__*/ PolySymbol('rvl'); - -const isBrowser = typeof window !== 'undefined'; - -function isESModule(obj) { - return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module'); -} -const assign = Object.assign; -function applyToParams(fn, params) { - const newParams = {}; - for (const key in params) { - const value = params[key]; - newParams[key] = Array.isArray(value) ? value.map(fn) : fn(value); - } - return newParams; -} -const noop = () => { }; - -const TRAILING_SLASH_RE = /\/$/; -const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, ''); -/** - * Transforms an URI into a normalized history location - * - * @param parseQuery - * @param location - URI to normalize - * @param currentLocation - current absolute location. Allows resolving relative - * paths. Must start with `/`. Defaults to `/` - * @returns a normalized history location - */ -function parseURL(parseQuery, location, currentLocation = '/') { - let path, query = {}, searchString = '', hash = ''; - // Could use URL and URLSearchParams but IE 11 doesn't support it - const searchPos = location.indexOf('?'); - const hashPos = location.indexOf('#', searchPos > -1 ? searchPos : 0); - if (searchPos > -1) { - path = location.slice(0, searchPos); - searchString = location.slice(searchPos + 1, hashPos > -1 ? hashPos : location.length); - query = parseQuery(searchString); - } - if (hashPos > -1) { - path = path || location.slice(0, hashPos); - // keep the # character - hash = location.slice(hashPos, location.length); - } - // no search and no query - path = resolveRelativePath(path != null ? path : location, currentLocation); - // empty path means a relative query or hash `?foo=f`, `#thing` - return { - fullPath: path + (searchString && '?') + searchString + hash, - path, - query, - hash, - }; -} -/** - * Stringifies a URL object - * - * @param stringifyQuery - * @param location - */ -function stringifyURL(stringifyQuery, location) { - const query = location.query ? stringifyQuery(location.query) : ''; - return location.path + (query && '?') + query + (location.hash || ''); -} -/** - * Strips off the base from the beginning of a location.pathname in a non - * case-sensitive way. - * - * @param pathname - location.pathname - * @param base - base to strip off - */ -function stripBase(pathname, base) { - // no base or base is not found at the beginning - if (!base || !pathname.toLowerCase().startsWith(base.toLowerCase())) - return pathname; - return pathname.slice(base.length) || '/'; -} -/** - * Checks if two RouteLocation are equal. This means that both locations are - * pointing towards the same {@link RouteRecord} and that all `params`, `query` - * parameters and `hash` are the same - * - * @param a - first {@link RouteLocation} - * @param b - second {@link RouteLocation} - */ -function isSameRouteLocation(stringifyQuery, a, b) { - const aLastIndex = a.matched.length - 1; - const bLastIndex = b.matched.length - 1; - return (aLastIndex > -1 && - aLastIndex === bLastIndex && - isSameRouteRecord(a.matched[aLastIndex], b.matched[bLastIndex]) && - isSameRouteLocationParams(a.params, b.params) && - stringifyQuery(a.query) === stringifyQuery(b.query) && - a.hash === b.hash); -} -/** - * Check if two `RouteRecords` are equal. Takes into account aliases: they are - * considered equal to the `RouteRecord` they are aliasing. - * - * @param a - first {@link RouteRecord} - * @param b - second {@link RouteRecord} - */ -function isSameRouteRecord(a, b) { - // since the original record has an undefined value for aliasOf - // but all aliases point to the original record, this will always compare - // the original record - return (a.aliasOf || a) === (b.aliasOf || b); -} -function isSameRouteLocationParams(a, b) { - if (Object.keys(a).length !== Object.keys(b).length) - return false; - for (const key in a) { - if (!isSameRouteLocationParamsValue(a[key], b[key])) - return false; - } - return true; -} -function isSameRouteLocationParamsValue(a, b) { - return Array.isArray(a) - ? isEquivalentArray(a, b) - : Array.isArray(b) - ? isEquivalentArray(b, a) - : a === b; -} -/** - * Check if two arrays are the same or if an array with one single entry is the - * same as another primitive value. Used to check query and parameters - * - * @param a - array of values - * @param b - array of values or a single value - */ -function isEquivalentArray(a, b) { - return Array.isArray(b) - ? a.length === b.length && a.every((value, i) => value === b[i]) - : a.length === 1 && a[0] === b; -} -/** - * Resolves a relative path that starts with `.`. - * - * @param to - path location we are resolving - * @param from - currentLocation.path, should start with `/` - */ -function resolveRelativePath(to, from) { - if (to.startsWith('/')) - return to; - if (!to) - return from; - const fromSegments = from.split('/'); - const toSegments = to.split('/'); - let position = fromSegments.length - 1; - let toPosition; - let segment; - for (toPosition = 0; toPosition < toSegments.length; toPosition++) { - segment = toSegments[toPosition]; - // can't go below zero - if (position === 1 || segment === '.') - continue; - if (segment === '..') - position--; - // found something that is not relative path - else - break; - } - return (fromSegments.slice(0, position).join('/') + - '/' + - toSegments - .slice(toPosition - (toPosition === toSegments.length ? 1 : 0)) - .join('/')); -} - -var NavigationType; -(function (NavigationType) { - NavigationType["pop"] = "pop"; - NavigationType["push"] = "push"; -})(NavigationType || (NavigationType = {})); -var NavigationDirection; -(function (NavigationDirection) { - NavigationDirection["back"] = "back"; - NavigationDirection["forward"] = "forward"; - NavigationDirection["unknown"] = ""; -})(NavigationDirection || (NavigationDirection = {})); -/** - * Starting location for Histories - */ -const START = ''; -// Generic utils -/** - * Normalizes a base by removing any trailing slash and reading the base tag if - * present. - * - * @param base - base to normalize - */ -function normalizeBase(base) { - if (!base) { - if (isBrowser) { - // respect tag - const baseEl = document.querySelector('base'); - base = (baseEl && baseEl.getAttribute('href')) || '/'; - // strip full URL origin - base = base.replace(/^\w+:\/\/[^\/]+/, ''); - } - else { - base = '/'; - } - } - // ensure leading slash when it was removed by the regex above avoid leading - // slash with hash because the file could be read from the disk like file:// - // and the leading slash would cause problems - if (base[0] !== '/' && base[0] !== '#') - base = '/' + base; - // remove the trailing slash so all other method can just do `base + fullPath` - // to build an href - return removeTrailingSlash(base); -} -// remove any character before the hash -const BEFORE_HASH_RE = /^[^#]+#/; -function createHref(base, location) { - return base.replace(BEFORE_HASH_RE, '#') + location; -} - -function getElementPosition(el, offset) { - const docRect = document.documentElement.getBoundingClientRect(); - const elRect = el.getBoundingClientRect(); - return { - behavior: offset.behavior, - left: elRect.left - docRect.left - (offset.left || 0), - top: elRect.top - docRect.top - (offset.top || 0), - }; -} -const computeScrollPosition = () => ({ - left: window.pageXOffset, - top: window.pageYOffset, -}); -function scrollToPosition(position) { - let scrollToOptions; - if ('el' in position) { - const positionEl = position.el; - const isIdSelector = typeof positionEl === 'string' && positionEl.startsWith('#'); - const el = typeof positionEl === 'string' - ? isIdSelector - ? document.getElementById(positionEl.slice(1)) - : document.querySelector(positionEl) - : positionEl; - if (!el) { - return; - } - scrollToOptions = getElementPosition(el, position); - } - else { - scrollToOptions = position; - } - if ('scrollBehavior' in document.documentElement.style) - window.scrollTo(scrollToOptions); - else { - window.scrollTo(scrollToOptions.left != null ? scrollToOptions.left : window.pageXOffset, scrollToOptions.top != null ? scrollToOptions.top : window.pageYOffset); - } -} -function getScrollKey(path, delta) { - const position = history.state ? history.state.position - delta : -1; - return position + path; -} -const scrollPositions = new Map(); -function saveScrollPosition(key, scrollPosition) { - scrollPositions.set(key, scrollPosition); -} -function getSavedScrollPosition(key) { - const scroll = scrollPositions.get(key); - // consume it so it's not used again - scrollPositions.delete(key); - return scroll; -} -// TODO: RFC about how to save scroll position -/** - * ScrollBehavior instance used by the router to compute and restore the scroll - * position when navigating. - */ -// export interface ScrollHandler { -// // returns a scroll position that can be saved in history -// compute(): ScrollPositionEntry -// // can take an extended ScrollPositionEntry -// scroll(position: ScrollPosition): void -// } -// export const scrollHandler: ScrollHandler = { -// compute: computeScroll, -// scroll: scrollToPosition, -// } - -let createBaseLocation = () => location.protocol + '//' + location.host; -/** - * Creates a normalized history location from a window.location object - * @param location - - */ -function createCurrentLocation(base, location) { - const { pathname, search, hash } = location; - // allows hash bases like #, /#, #/, #!, #!/, /#!/, or even /folder#end - const hashPos = base.indexOf('#'); - if (hashPos > -1) { - let slicePos = hash.includes(base.slice(hashPos)) - ? base.slice(hashPos).length - : 1; - let pathFromHash = hash.slice(slicePos); - // prepend the starting slash to hash so the url starts with /# - if (pathFromHash[0] !== '/') - pathFromHash = '/' + pathFromHash; - return stripBase(pathFromHash, ''); - } - const path = stripBase(pathname, base); - return path + search + hash; -} -function useHistoryListeners(base, historyState, currentLocation, replace) { - let listeners = []; - let teardowns = []; - // TODO: should it be a stack? a Dict. Check if the popstate listener - // can trigger twice - let pauseState = null; - const popStateHandler = ({ state, }) => { - const to = createCurrentLocation(base, location); - const from = currentLocation.value; - const fromState = historyState.value; - let delta = 0; - if (state) { - currentLocation.value = to; - historyState.value = state; - // ignore the popstate and reset the pauseState - if (pauseState && pauseState === from) { - pauseState = null; - return; - } - delta = fromState ? state.position - fromState.position : 0; - } - else { - replace(to); - } - // console.log({ deltaFromCurrent }) - // Here we could also revert the navigation by calling history.go(-delta) - // this listener will have to be adapted to not trigger again and to wait for the url - // to be updated before triggering the listeners. Some kind of validation function would also - // need to be passed to the listeners so the navigation can be accepted - // call all listeners - listeners.forEach(listener => { - listener(currentLocation.value, from, { - delta, - type: NavigationType.pop, - direction: delta - ? delta > 0 - ? NavigationDirection.forward - : NavigationDirection.back - : NavigationDirection.unknown, - }); - }); - }; - function pauseListeners() { - pauseState = currentLocation.value; - } - function listen(callback) { - // setup the listener and prepare teardown callbacks - listeners.push(callback); - const teardown = () => { - const index = listeners.indexOf(callback); - if (index > -1) - listeners.splice(index, 1); - }; - teardowns.push(teardown); - return teardown; - } - function beforeUnloadListener() { - const { history } = window; - if (!history.state) - return; - history.replaceState(assign({}, history.state, { scroll: computeScrollPosition() }), ''); - } - function destroy() { - for (const teardown of teardowns) - teardown(); - teardowns = []; - window.removeEventListener('popstate', popStateHandler); - window.removeEventListener('beforeunload', beforeUnloadListener); - } - // setup the listeners and prepare teardown callbacks - window.addEventListener('popstate', popStateHandler); - window.addEventListener('beforeunload', beforeUnloadListener); - return { - pauseListeners, - listen, - destroy, - }; -} -/** - * Creates a state object - */ -function buildState(back, current, forward, replaced = false, computeScroll = false) { - return { - back, - current, - forward, - replaced, - position: window.history.length, - scroll: computeScroll ? computeScrollPosition() : null, - }; -} -function useHistoryStateNavigation(base) { - const { history, location } = window; - // private variables - const currentLocation = { - value: createCurrentLocation(base, location), - }; - const historyState = { value: history.state }; - // build current history entry as this is a fresh navigation - if (!historyState.value) { - changeLocation(currentLocation.value, { - back: null, - current: currentLocation.value, - forward: null, - // the length is off by one, we need to decrease it - position: history.length - 1, - replaced: true, - // don't add a scroll as the user may have an anchor and we want - // scrollBehavior to be triggered without a saved position - scroll: null, - }, true); - } - function changeLocation(to, state, replace) { - /** - * if a base tag is provided and we are on a normal domain, we have to - * respect the provided `base` attribute because pushState() will use it and - * potentially erase anything before the `#` like at - * https://github.com/vuejs/router/issues/685 where a base of - * `/folder/#` but a base of `/` would erase the `/folder/` section. If - * there is no host, the `` tag makes no sense and if there isn't a - * base tag we can just use everything after the `#`. - */ - const hashIndex = base.indexOf('#'); - const url = hashIndex > -1 - ? (location.host && document.querySelector('base') - ? base - : base.slice(hashIndex)) + to - : createBaseLocation() + base + to; - try { - // BROWSER QUIRK - // NOTE: Safari throws a SecurityError when calling this function 100 times in 30 seconds - history[replace ? 'replaceState' : 'pushState'](state, '', url); - historyState.value = state; - } - catch (err) { - { - console.error(err); - } - // Force the navigation, this also resets the call count - location[replace ? 'replace' : 'assign'](url); - } - } - function replace(to, data) { - const state = assign({}, history.state, buildState(historyState.value.back, - // keep back and forward entries but override current position - to, historyState.value.forward, true), data, { position: historyState.value.position }); - changeLocation(to, state, true); - currentLocation.value = to; - } - function push(to, data) { - // Add to current entry the information of where we are going - // as well as saving the current position - const currentState = assign({}, - // use current history state to gracefully handle a wrong call to - // history.replaceState - // https://github.com/vuejs/router/issues/366 - historyState.value, history.state, { - forward: to, - scroll: computeScrollPosition(), - }); - changeLocation(currentState.current, currentState, true); - const state = assign({}, buildState(currentLocation.value, to, null), { position: currentState.position + 1 }, data); - changeLocation(to, state, false); - currentLocation.value = to; - } - return { - location: currentLocation, - state: historyState, - push, - replace, - }; -} -/** - * Creates an HTML5 history. Most common history for single page applications. - * - * @param base - - */ -function createWebHistory(base) { - base = normalizeBase(base); - const historyNavigation = useHistoryStateNavigation(base); - const historyListeners = useHistoryListeners(base, historyNavigation.state, historyNavigation.location, historyNavigation.replace); - function go(delta, triggerListeners = true) { - if (!triggerListeners) - historyListeners.pauseListeners(); - history.go(delta); - } - const routerHistory = assign({ - // it's overridden right after - location: '', - base, - go, - createHref: createHref.bind(null, base), - }, historyNavigation, historyListeners); - Object.defineProperty(routerHistory, 'location', { - enumerable: true, - get: () => historyNavigation.location.value, - }); - Object.defineProperty(routerHistory, 'state', { - enumerable: true, - get: () => historyNavigation.state.value, - }); - return routerHistory; -} - -/** - * Creates a in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere. - * It's up to the user to replace that location with the starter location by either calling `router.push` or `router.replace`. - * - * @param base - Base applied to all urls, defaults to '/' - * @returns a history object that can be passed to the router constructor - */ -function createMemoryHistory(base = '') { - let listeners = []; - let queue = [START]; - let position = 0; - base = normalizeBase(base); - function setLocation(location) { - position++; - if (position === queue.length) { - // we are at the end, we can simply append a new entry - queue.push(location); - } - else { - // we are in the middle, we remove everything from here in the queue - queue.splice(position); - queue.push(location); - } - } - function triggerListeners(to, from, { direction, delta }) { - const info = { - direction, - delta, - type: NavigationType.pop, - }; - for (const callback of listeners) { - callback(to, from, info); - } - } - const routerHistory = { - // rewritten by Object.defineProperty - location: START, - // TODO: should be kept in queue - state: {}, - base, - createHref: createHref.bind(null, base), - replace(to) { - // remove current entry and decrement position - queue.splice(position--, 1); - setLocation(to); - }, - push(to, data) { - setLocation(to); - }, - listen(callback) { - listeners.push(callback); - return () => { - const index = listeners.indexOf(callback); - if (index > -1) - listeners.splice(index, 1); - }; - }, - destroy() { - listeners = []; - queue = [START]; - position = 0; - }, - go(delta, shouldTrigger = true) { - const from = this.location; - const direction = - // we are considering delta === 0 going forward, but in abstract mode - // using 0 for the delta doesn't make sense like it does in html5 where - // it reloads the page - delta < 0 ? NavigationDirection.back : NavigationDirection.forward; - position = Math.max(0, Math.min(position + delta, queue.length - 1)); - if (shouldTrigger) { - triggerListeners(this.location, from, { - direction, - delta, - }); - } - }, - }; - Object.defineProperty(routerHistory, 'location', { - enumerable: true, - get: () => queue[position], - }); - return routerHistory; -} - -/** - * Creates a hash history. Useful for web applications with no host (e.g. - * `file://`) or when configuring a server to handle any URL is not possible. - * - * @param base - optional base to provide. Defaults to `location.pathname + - * location.search` If there is a `` tag in the `head`, its value will be - * ignored in favor of this parameter **but note it affects all the - * history.pushState() calls**, meaning that if you use a `` tag, it's - * `href` value **has to match this parameter** (ignoring anything after the - * `#`). - * - * @example - * ```js - * // at https://example.com/folder - * createWebHashHistory() // gives a url of `https://example.com/folder#` - * createWebHashHistory('/folder/') // gives a url of `https://example.com/folder/#` - * // if the `#` is provided in the base, it won't be added by `createWebHashHistory` - * createWebHashHistory('/folder/#/app/') // gives a url of `https://example.com/folder/#/app/` - * // you should avoid doing this because it changes the original url and breaks copying urls - * createWebHashHistory('/other-folder/') // gives a url of `https://example.com/other-folder/#` - * - * // at file:///usr/etc/folder/index.html - * // for locations with no `host`, the base is ignored - * createWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#` - * ``` - */ -function createWebHashHistory(base) { - // Make sure this implementation is fine in terms of encoding, specially for IE11 - // for `file://`, directly use the pathname and ignore the base - // location.pathname contains an initial `/` even at the root: `https://example.com` - base = location.host ? base || location.pathname + location.search : ''; - // allow the user to provide a `#` in the middle: `/base/#/app` - if (!base.includes('#')) - base += '#'; - return createWebHistory(base); -} - -function isRouteLocation(route) { - return typeof route === 'string' || (route && typeof route === 'object'); -} -function isRouteName(name) { - return typeof name === 'string' || typeof name === 'symbol'; -} - -/** - * Initial route location where the router is. Can be used in navigation guards - * to differentiate the initial navigation. - * - * @example - * ```js - * import { START_LOCATION } from 'vue-router' - * - * router.beforeEach((to, from) => { - * if (from === START_LOCATION) { - * // initial navigation - * } - * }) - * ``` - */ -const START_LOCATION_NORMALIZED = { - path: '/', - name: undefined, - params: {}, - query: {}, - hash: '', - fullPath: '/', - matched: [], - meta: {}, - redirectedFrom: undefined, -}; - -const NavigationFailureSymbol = /*#__PURE__*/ PolySymbol('nf'); -/** - * Enumeration with all possible types for navigation failures. Can be passed to - * {@link isNavigationFailure} to check for specific failures. - */ -exports.NavigationFailureType = void 0; -(function (NavigationFailureType) { - /** - * An aborted navigation is a navigation that failed because a navigation - * guard returned `false` or called `next(false)` - */ - NavigationFailureType[NavigationFailureType["aborted"] = 4] = "aborted"; - /** - * A cancelled navigation is a navigation that failed because a more recent - * navigation finished started (not necessarily finished). - */ - NavigationFailureType[NavigationFailureType["cancelled"] = 8] = "cancelled"; - /** - * A duplicated navigation is a navigation that failed because it was - * initiated while already being at the exact same location. - */ - NavigationFailureType[NavigationFailureType["duplicated"] = 16] = "duplicated"; -})(exports.NavigationFailureType || (exports.NavigationFailureType = {})); -// DEV only debug messages -const ErrorTypeMessages = { - [1 /* MATCHER_NOT_FOUND */]({ location, currentLocation }) { - return `No match for\n ${JSON.stringify(location)}${currentLocation - ? '\nwhile being at\n' + JSON.stringify(currentLocation) - : ''}`; - }, - [2 /* NAVIGATION_GUARD_REDIRECT */]({ from, to, }) { - return `Redirected from "${from.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`; - }, - [4 /* NAVIGATION_ABORTED */]({ from, to }) { - return `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`; - }, - [8 /* NAVIGATION_CANCELLED */]({ from, to }) { - return `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`; - }, - [16 /* NAVIGATION_DUPLICATED */]({ from, to }) { - return `Avoided redundant navigation to current location: "${from.fullPath}".`; - }, -}; -function createRouterError(type, params) { - // keep full error messages in cjs versions - { - return assign(new Error(ErrorTypeMessages[type](params)), { - type, - [NavigationFailureSymbol]: true, - }, params); - } -} -function isNavigationFailure(error, type) { - return (error instanceof Error && - NavigationFailureSymbol in error && - (type == null || !!(error.type & type))); -} -const propertiesToLog = ['params', 'query', 'hash']; -function stringifyRoute(to) { - if (typeof to === 'string') - return to; - if ('path' in to) - return to.path; - const location = {}; - for (const key of propertiesToLog) { - if (key in to) - location[key] = to[key]; - } - return JSON.stringify(location, null, 2); -} - -// default pattern for a param: non greedy everything but / -const BASE_PARAM_PATTERN = '[^/]+?'; -const BASE_PATH_PARSER_OPTIONS = { - sensitive: false, - strict: false, - start: true, - end: true, -}; -// Special Regex characters that must be escaped in static tokens -const REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g; -/** - * Creates a path parser from an array of Segments (a segment is an array of Tokens) - * - * @param segments - array of segments returned by tokenizePath - * @param extraOptions - optional options for the regexp - * @returns a PathParser - */ -function tokensToParser(segments, extraOptions) { - const options = assign({}, BASE_PATH_PARSER_OPTIONS, extraOptions); - // the amount of scores is the same as the length of segments except for the root segment "/" - const score = []; - // the regexp as a string - let pattern = options.start ? '^' : ''; - // extracted keys - const keys = []; - for (const segment of segments) { - // the root segment needs special treatment - const segmentScores = segment.length ? [] : [90 /* Root */]; - // allow trailing slash - if (options.strict && !segment.length) - pattern += '/'; - for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) { - const token = segment[tokenIndex]; - // resets the score if we are inside a sub segment /:a-other-:b - let subSegmentScore = 40 /* Segment */ + - (options.sensitive ? 0.25 /* BonusCaseSensitive */ : 0); - if (token.type === 0 /* Static */) { - // prepend the slash if we are starting a new segment - if (!tokenIndex) - pattern += '/'; - pattern += token.value.replace(REGEX_CHARS_RE, '\\$&'); - subSegmentScore += 40 /* Static */; - } - else if (token.type === 1 /* Param */) { - const { value, repeatable, optional, regexp } = token; - keys.push({ - name: value, - repeatable, - optional, - }); - const re = regexp ? regexp : BASE_PARAM_PATTERN; - // the user provided a custom regexp /:id(\\d+) - if (re !== BASE_PARAM_PATTERN) { - subSegmentScore += 10 /* BonusCustomRegExp */; - // make sure the regexp is valid before using it - try { - new RegExp(`(${re})`); - } - catch (err) { - throw new Error(`Invalid custom RegExp for param "${value}" (${re}): ` + - err.message); - } - } - // when we repeat we must take care of the repeating leading slash - let subPattern = repeatable ? `((?:${re})(?:/(?:${re}))*)` : `(${re})`; - // prepend the slash if we are starting a new segment - if (!tokenIndex) - subPattern = - // avoid an optional / if there are more segments e.g. /:p?-static - // or /:p?-:p2 - optional && segment.length < 2 - ? `(?:/${subPattern})` - : '/' + subPattern; - if (optional) - subPattern += '?'; - pattern += subPattern; - subSegmentScore += 20 /* Dynamic */; - if (optional) - subSegmentScore += -8 /* BonusOptional */; - if (repeatable) - subSegmentScore += -20 /* BonusRepeatable */; - if (re === '.*') - subSegmentScore += -50 /* BonusWildcard */; - } - segmentScores.push(subSegmentScore); - } - // an empty array like /home/ -> [[{home}], []] - // if (!segment.length) pattern += '/' - score.push(segmentScores); - } - // only apply the strict bonus to the last score - if (options.strict && options.end) { - const i = score.length - 1; - score[i][score[i].length - 1] += 0.7000000000000001 /* BonusStrict */; - } - // TODO: dev only warn double trailing slash - if (!options.strict) - pattern += '/?'; - if (options.end) - pattern += '$'; - // allow paths like /dynamic to only match dynamic or dynamic/... but not dynamic_something_else - else if (options.strict) - pattern += '(?:/|$)'; - const re = new RegExp(pattern, options.sensitive ? '' : 'i'); - function parse(path) { - const match = path.match(re); - const params = {}; - if (!match) - return null; - for (let i = 1; i < match.length; i++) { - const value = match[i] || ''; - const key = keys[i - 1]; - params[key.name] = value && key.repeatable ? value.split('/') : value; - } - return params; - } - function stringify(params) { - let path = ''; - // for optional parameters to allow to be empty - let avoidDuplicatedSlash = false; - for (const segment of segments) { - if (!avoidDuplicatedSlash || !path.endsWith('/')) - path += '/'; - avoidDuplicatedSlash = false; - for (const token of segment) { - if (token.type === 0 /* Static */) { - path += token.value; - } - else if (token.type === 1 /* Param */) { - const { value, repeatable, optional } = token; - const param = value in params ? params[value] : ''; - if (Array.isArray(param) && !repeatable) - throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`); - const text = Array.isArray(param) ? param.join('/') : param; - if (!text) { - if (optional) { - // if we have more than one optional param like /:a?-static and there are more segments, we don't need to - // care about the optional param - if (segment.length < 2 && segments.length > 1) { - // remove the last slash as we could be at the end - if (path.endsWith('/')) - path = path.slice(0, -1); - // do not append a slash on the next iteration - else - avoidDuplicatedSlash = true; - } - } - else - throw new Error(`Missing required param "${value}"`); - } - path += text; - } - } - } - return path; - } - return { - re, - score, - keys, - parse, - stringify, - }; -} -/** - * Compares an array of numbers as used in PathParser.score and returns a - * number. This function can be used to `sort` an array - * - * @param a - first array of numbers - * @param b - second array of numbers - * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b - * should be sorted first - */ -function compareScoreArray(a, b) { - let i = 0; - while (i < a.length && i < b.length) { - const diff = b[i] - a[i]; - // only keep going if diff === 0 - if (diff) - return diff; - i++; - } - // if the last subsegment was Static, the shorter segments should be sorted first - // otherwise sort the longest segment first - if (a.length < b.length) { - return a.length === 1 && a[0] === 40 /* Static */ + 40 /* Segment */ - ? -1 - : 1; - } - else if (a.length > b.length) { - return b.length === 1 && b[0] === 40 /* Static */ + 40 /* Segment */ - ? 1 - : -1; - } - return 0; -} -/** - * Compare function that can be used with `sort` to sort an array of PathParser - * - * @param a - first PathParser - * @param b - second PathParser - * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b - */ -function comparePathParserScore(a, b) { - let i = 0; - const aScore = a.score; - const bScore = b.score; - while (i < aScore.length && i < bScore.length) { - const comp = compareScoreArray(aScore[i], bScore[i]); - // do not return if both are equal - if (comp) - return comp; - i++; - } - // if a and b share the same score entries but b has more, sort b first - return bScore.length - aScore.length; - // this is the ternary version - // return aScore.length < bScore.length - // ? 1 - // : aScore.length > bScore.length - // ? -1 - // : 0 -} - -const ROOT_TOKEN = { - type: 0 /* Static */, - value: '', -}; -const VALID_PARAM_RE = /[a-zA-Z0-9_]/; -// After some profiling, the cache seems to be unnecessary because tokenizePath -// (the slowest part of adding a route) is very fast -// const tokenCache = new Map() -function tokenizePath(path) { - if (!path) - return [[]]; - if (path === '/') - return [[ROOT_TOKEN]]; - if (!path.startsWith('/')) { - throw new Error(`Invalid path "${path}"`); - } - // if (tokenCache.has(path)) return tokenCache.get(path)! - function crash(message) { - throw new Error(`ERR (${state})/"${buffer}": ${message}`); - } - let state = 0 /* Static */; - let previousState = state; - const tokens = []; - // the segment will always be valid because we get into the initial state - // with the leading / - let segment; - function finalizeSegment() { - if (segment) - tokens.push(segment); - segment = []; - } - // index on the path - let i = 0; - // char at index - let char; - // buffer of the value read - let buffer = ''; - // custom regexp for a param - let customRe = ''; - function consumeBuffer() { - if (!buffer) - return; - if (state === 0 /* Static */) { - segment.push({ - type: 0 /* Static */, - value: buffer, - }); - } - else if (state === 1 /* Param */ || - state === 2 /* ParamRegExp */ || - state === 3 /* ParamRegExpEnd */) { - if (segment.length > 1 && (char === '*' || char === '+')) - crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`); - segment.push({ - type: 1 /* Param */, - value: buffer, - regexp: customRe, - repeatable: char === '*' || char === '+', - optional: char === '*' || char === '?', - }); - } - else { - crash('Invalid state to consume buffer'); - } - buffer = ''; - } - function addCharToBuffer() { - buffer += char; - } - while (i < path.length) { - char = path[i++]; - if (char === '\\' && state !== 2 /* ParamRegExp */) { - previousState = state; - state = 4 /* EscapeNext */; - continue; - } - switch (state) { - case 0 /* Static */: - if (char === '/') { - if (buffer) { - consumeBuffer(); - } - finalizeSegment(); - } - else if (char === ':') { - consumeBuffer(); - state = 1 /* Param */; - } - else { - addCharToBuffer(); - } - break; - case 4 /* EscapeNext */: - addCharToBuffer(); - state = previousState; - break; - case 1 /* Param */: - if (char === '(') { - state = 2 /* ParamRegExp */; - } - else if (VALID_PARAM_RE.test(char)) { - addCharToBuffer(); - } - else { - consumeBuffer(); - state = 0 /* Static */; - // go back one character if we were not modifying - if (char !== '*' && char !== '?' && char !== '+') - i--; - } - break; - case 2 /* ParamRegExp */: - // TODO: is it worth handling nested regexp? like :p(?:prefix_([^/]+)_suffix) - // it already works by escaping the closing ) - // https://paths.esm.dev/?p=AAMeJbiAwQEcDKbAoAAkP60PG2R6QAvgNaA6AFACM2ABuQBB# - // is this really something people need since you can also write - // /prefix_:p()_suffix - if (char === ')') { - // handle the escaped ) - if (customRe[customRe.length - 1] == '\\') - customRe = customRe.slice(0, -1) + char; - else - state = 3 /* ParamRegExpEnd */; - } - else { - customRe += char; - } - break; - case 3 /* ParamRegExpEnd */: - // same as finalizing a param - consumeBuffer(); - state = 0 /* Static */; - // go back one character if we were not modifying - if (char !== '*' && char !== '?' && char !== '+') - i--; - customRe = ''; - break; - default: - crash('Unknown state'); - break; - } - } - if (state === 2 /* ParamRegExp */) - crash(`Unfinished custom RegExp for param "${buffer}"`); - consumeBuffer(); - finalizeSegment(); - // tokenCache.set(path, tokens) - return tokens; -} - -function createRouteRecordMatcher(record, parent, options) { - const parser = tokensToParser(tokenizePath(record.path), options); - const matcher = assign(parser, { - record, - parent, - // these needs to be populated by the parent - children: [], - alias: [], - }); - if (parent) { - // both are aliases or both are not aliases - // we don't want to mix them because the order is used when - // passing originalRecord in Matcher.addRoute - if (!matcher.record.aliasOf === !parent.record.aliasOf) - parent.children.push(matcher); - } - return matcher; -} - -/** - * Creates a Router Matcher. - * - * @internal - * @param routes - array of initial routes - * @param globalOptions - global route options - */ -function createRouterMatcher(routes, globalOptions) { - // normalized ordered array of matchers - const matchers = []; - const matcherMap = new Map(); - globalOptions = mergeOptions({ strict: false, end: true, sensitive: false }, globalOptions); - function getRecordMatcher(name) { - return matcherMap.get(name); - } - function addRoute(record, parent, originalRecord) { - // used later on to remove by name - const isRootAdd = !originalRecord; - const mainNormalizedRecord = normalizeRouteRecord(record); - // we might be the child of an alias - mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record; - const options = mergeOptions(globalOptions, record); - // generate an array of records to correctly handle aliases - const normalizedRecords = [ - mainNormalizedRecord, - ]; - if ('alias' in record) { - const aliases = typeof record.alias === 'string' ? [record.alias] : record.alias; - for (const alias of aliases) { - normalizedRecords.push(assign({}, mainNormalizedRecord, { - // this allows us to hold a copy of the `components` option - // so that async components cache is hold on the original record - components: originalRecord - ? originalRecord.record.components - : mainNormalizedRecord.components, - path: alias, - // we might be the child of an alias - aliasOf: originalRecord - ? originalRecord.record - : mainNormalizedRecord, - // the aliases are always of the same kind as the original since they - // are defined on the same record - })); - } - } - let matcher; - let originalMatcher; - for (const normalizedRecord of normalizedRecords) { - const { path } = normalizedRecord; - // Build up the path for nested routes if the child isn't an absolute - // route. Only add the / delimiter if the child path isn't empty and if the - // parent path doesn't have a trailing slash - if (parent && path[0] !== '/') { - const parentPath = parent.record.path; - const connectingSlash = parentPath[parentPath.length - 1] === '/' ? '' : '/'; - normalizedRecord.path = - parent.record.path + (path && connectingSlash + path); - } - // create the object before hand so it can be passed to children - matcher = createRouteRecordMatcher(normalizedRecord, parent, options); - // if we are an alias we must tell the original record that we exist - // so we can be removed - if (originalRecord) { - originalRecord.alias.push(matcher); - } - else { - // otherwise, the first record is the original and others are aliases - originalMatcher = originalMatcher || matcher; - if (originalMatcher !== matcher) - originalMatcher.alias.push(matcher); - // remove the route if named and only for the top record (avoid in nested calls) - // this works because the original record is the first one - if (isRootAdd && record.name && !isAliasRecord(matcher)) - removeRoute(record.name); - } - if ('children' in mainNormalizedRecord) { - const children = mainNormalizedRecord.children; - for (let i = 0; i < children.length; i++) { - addRoute(children[i], matcher, originalRecord && originalRecord.children[i]); - } - } - // if there was no original record, then the first one was not an alias and all - // other alias (if any) need to reference this record when adding children - originalRecord = originalRecord || matcher; - // TODO: add normalized records for more flexibility - // if (parent && isAliasRecord(originalRecord)) { - // parent.children.push(originalRecord) - // } - insertMatcher(matcher); - } - return originalMatcher - ? () => { - // since other matchers are aliases, they should be removed by the original matcher - removeRoute(originalMatcher); - } - : noop; - } - function removeRoute(matcherRef) { - if (isRouteName(matcherRef)) { - const matcher = matcherMap.get(matcherRef); - if (matcher) { - matcherMap.delete(matcherRef); - matchers.splice(matchers.indexOf(matcher), 1); - matcher.children.forEach(removeRoute); - matcher.alias.forEach(removeRoute); - } - } - else { - const index = matchers.indexOf(matcherRef); - if (index > -1) { - matchers.splice(index, 1); - if (matcherRef.record.name) - matcherMap.delete(matcherRef.record.name); - matcherRef.children.forEach(removeRoute); - matcherRef.alias.forEach(removeRoute); - } - } - } - function getRoutes() { - return matchers; - } - function insertMatcher(matcher) { - let i = 0; - while (i < matchers.length && - comparePathParserScore(matcher, matchers[i]) >= 0 && - // Adding children with empty path should still appear before the parent - // https://github.com/vuejs/router/issues/1124 - (matcher.record.path !== matchers[i].record.path || - !isRecordChildOf(matcher, matchers[i]))) - i++; - matchers.splice(i, 0, matcher); - // only add the original record to the name map - if (matcher.record.name && !isAliasRecord(matcher)) - matcherMap.set(matcher.record.name, matcher); - } - function resolve(location, currentLocation) { - let matcher; - let params = {}; - let path; - let name; - if ('name' in location && location.name) { - matcher = matcherMap.get(location.name); - if (!matcher) - throw createRouterError(1 /* MATCHER_NOT_FOUND */, { - location, - }); - name = matcher.record.name; - params = assign( - // paramsFromLocation is a new object - paramsFromLocation(currentLocation.params, - // only keep params that exist in the resolved location - // TODO: only keep optional params coming from a parent record - matcher.keys.filter(k => !k.optional).map(k => k.name)), location.params); - // throws if cannot be stringified - path = matcher.stringify(params); - } - else if ('path' in location) { - // no need to resolve the path with the matcher as it was provided - // this also allows the user to control the encoding - path = location.path; - matcher = matchers.find(m => m.re.test(path)); - // matcher should have a value after the loop - if (matcher) { - // TODO: dev warning of unused params if provided - // we know the matcher works because we tested the regexp - params = matcher.parse(path); - name = matcher.record.name; - } - // location is a relative path - } - else { - // match by name or path of current route - matcher = currentLocation.name - ? matcherMap.get(currentLocation.name) - : matchers.find(m => m.re.test(currentLocation.path)); - if (!matcher) - throw createRouterError(1 /* MATCHER_NOT_FOUND */, { - location, - currentLocation, - }); - name = matcher.record.name; - // since we are navigating to the same location, we don't need to pick the - // params like when `name` is provided - params = assign({}, currentLocation.params, location.params); - path = matcher.stringify(params); - } - const matched = []; - let parentMatcher = matcher; - while (parentMatcher) { - // reversed order so parents are at the beginning - matched.unshift(parentMatcher.record); - parentMatcher = parentMatcher.parent; - } - return { - name, - path, - params, - matched, - meta: mergeMetaFields(matched), - }; - } - // add initial routes - routes.forEach(route => addRoute(route)); - return { addRoute, resolve, removeRoute, getRoutes, getRecordMatcher }; -} -function paramsFromLocation(params, keys) { - const newParams = {}; - for (const key of keys) { - if (key in params) - newParams[key] = params[key]; - } - return newParams; -} -/** - * Normalizes a RouteRecordRaw. Creates a copy - * - * @param record - * @returns the normalized version - */ -function normalizeRouteRecord(record) { - return { - path: record.path, - redirect: record.redirect, - name: record.name, - meta: record.meta || {}, - aliasOf: undefined, - beforeEnter: record.beforeEnter, - props: normalizeRecordProps(record), - children: record.children || [], - instances: {}, - leaveGuards: new Set(), - updateGuards: new Set(), - enterCallbacks: {}, - components: 'components' in record - ? record.components || {} - : { default: record.component }, - }; -} -/** - * Normalize the optional `props` in a record to always be an object similar to - * components. Also accept a boolean for components. - * @param record - */ -function normalizeRecordProps(record) { - const propsObject = {}; - // props does not exist on redirect records but we can set false directly - const props = record.props || false; - if ('component' in record) { - propsObject.default = props; - } - else { - // NOTE: we could also allow a function to be applied to every component. - // Would need user feedback for use cases - for (const name in record.components) - propsObject[name] = typeof props === 'boolean' ? props : props[name]; - } - return propsObject; -} -/** - * Checks if a record or any of its parent is an alias - * @param record - */ -function isAliasRecord(record) { - while (record) { - if (record.record.aliasOf) - return true; - record = record.parent; - } - return false; -} -/** - * Merge meta fields of an array of records - * - * @param matched - array of matched records - */ -function mergeMetaFields(matched) { - return matched.reduce((meta, record) => assign(meta, record.meta), {}); -} -function mergeOptions(defaults, partialOptions) { - const options = {}; - for (const key in defaults) { - options[key] = key in partialOptions ? partialOptions[key] : defaults[key]; - } - return options; -} -function isRecordChildOf(record, parent) { - return parent.children.some(child => child === record || isRecordChildOf(record, child)); -} - -/** - * Encoding Rules ␣ = Space Path: ␣ " < > # ? { } Query: ␣ " < > # & = Hash: ␣ " - * < > ` - * - * On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2) - * defines some extra characters to be encoded. Most browsers do not encode them - * in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to - * also encode `!'()*`. Leaving unencoded only ASCII alphanumeric(`a-zA-Z0-9`) - * plus `-._~`. This extra safety should be applied to query by patching the - * string returned by encodeURIComponent encodeURI also encodes `[\]^`. `\` - * should be encoded to avoid ambiguity. Browsers (IE, FF, C) transform a `\` - * into a `/` if directly typed in. The _backtick_ (`````) should also be - * encoded everywhere because some browsers like FF encode it when directly - * written while others don't. Safari and IE don't encode ``"<>{}``` in hash. - */ -// const EXTRA_RESERVED_RE = /[!'()*]/g -// const encodeReservedReplacer = (c: string) => '%' + c.charCodeAt(0).toString(16) -const HASH_RE = /#/g; // %23 -const AMPERSAND_RE = /&/g; // %26 -const SLASH_RE = /\//g; // %2F -const EQUAL_RE = /=/g; // %3D -const IM_RE = /\?/g; // %3F -const PLUS_RE = /\+/g; // %2B -/** - * NOTE: It's not clear to me if we should encode the + symbol in queries, it - * seems to be less flexible than not doing so and I can't find out the legacy - * systems requiring this for regular requests like text/html. In the standard, - * the encoding of the plus character is only mentioned for - * application/x-www-form-urlencoded - * (https://url.spec.whatwg.org/#urlencoded-parsing) and most browsers seems lo - * leave the plus character as is in queries. To be more flexible, we allow the - * plus character on the query but it can also be manually encoded by the user. - * - * Resources: - * - https://url.spec.whatwg.org/#urlencoded-parsing - * - https://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20 - */ -const ENC_BRACKET_OPEN_RE = /%5B/g; // [ -const ENC_BRACKET_CLOSE_RE = /%5D/g; // ] -const ENC_CARET_RE = /%5E/g; // ^ -const ENC_BACKTICK_RE = /%60/g; // ` -const ENC_CURLY_OPEN_RE = /%7B/g; // { -const ENC_PIPE_RE = /%7C/g; // | -const ENC_CURLY_CLOSE_RE = /%7D/g; // } -const ENC_SPACE_RE = /%20/g; // } -/** - * Encode characters that need to be encoded on the path, search and hash - * sections of the URL. - * - * @internal - * @param text - string to encode - * @returns encoded string - */ -function commonEncode(text) { - return encodeURI('' + text) - .replace(ENC_PIPE_RE, '|') - .replace(ENC_BRACKET_OPEN_RE, '[') - .replace(ENC_BRACKET_CLOSE_RE, ']'); -} -/** - * Encode characters that need to be encoded on the hash section of the URL. - * - * @param text - string to encode - * @returns encoded string - */ -function encodeHash(text) { - return commonEncode(text) - .replace(ENC_CURLY_OPEN_RE, '{') - .replace(ENC_CURLY_CLOSE_RE, '}') - .replace(ENC_CARET_RE, '^'); -} -/** - * Encode characters that need to be encoded query values on the query - * section of the URL. - * - * @param text - string to encode - * @returns encoded string - */ -function encodeQueryValue(text) { - return (commonEncode(text) - // Encode the space as +, encode the + to differentiate it from the space - .replace(PLUS_RE, '%2B') - .replace(ENC_SPACE_RE, '+') - .replace(HASH_RE, '%23') - .replace(AMPERSAND_RE, '%26') - .replace(ENC_BACKTICK_RE, '`') - .replace(ENC_CURLY_OPEN_RE, '{') - .replace(ENC_CURLY_CLOSE_RE, '}') - .replace(ENC_CARET_RE, '^')); -} -/** - * Like `encodeQueryValue` but also encodes the `=` character. - * - * @param text - string to encode - */ -function encodeQueryKey(text) { - return encodeQueryValue(text).replace(EQUAL_RE, '%3D'); -} -/** - * Encode characters that need to be encoded on the path section of the URL. - * - * @param text - string to encode - * @returns encoded string - */ -function encodePath(text) { - return commonEncode(text).replace(HASH_RE, '%23').replace(IM_RE, '%3F'); -} -/** - * Encode characters that need to be encoded on the path section of the URL as a - * param. This function encodes everything {@link encodePath} does plus the - * slash (`/`) character. If `text` is `null` or `undefined`, returns an empty - * string instead. - * - * @param text - string to encode - * @returns encoded string - */ -function encodeParam(text) { - return text == null ? '' : encodePath(text).replace(SLASH_RE, '%2F'); -} -/** - * Decode text using `decodeURIComponent`. Returns the original text if it - * fails. - * - * @param text - string to decode - * @returns decoded string - */ -function decode(text) { - try { - return decodeURIComponent('' + text); - } - catch (err) { - } - return '' + text; -} - -/** - * Transforms a queryString into a {@link LocationQuery} object. Accept both, a - * version with the leading `?` and without Should work as URLSearchParams - - * @internal - * - * @param search - search string to parse - * @returns a query object - */ -function parseQuery(search) { - const query = {}; - // avoid creating an object with an empty key and empty value - // because of split('&') - if (search === '' || search === '?') - return query; - const hasLeadingIM = search[0] === '?'; - const searchParams = (hasLeadingIM ? search.slice(1) : search).split('&'); - for (let i = 0; i < searchParams.length; ++i) { - // pre decode the + into space - const searchParam = searchParams[i].replace(PLUS_RE, ' '); - // allow the = character - const eqPos = searchParam.indexOf('='); - const key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos)); - const value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1)); - if (key in query) { - // an extra variable for ts types - let currentValue = query[key]; - if (!Array.isArray(currentValue)) { - currentValue = query[key] = [currentValue]; - } - currentValue.push(value); - } - else { - query[key] = value; - } - } - return query; -} -/** - * Stringifies a {@link LocationQueryRaw} object. Like `URLSearchParams`, it - * doesn't prepend a `?` - * - * @internal - * - * @param query - query object to stringify - * @returns string version of the query without the leading `?` - */ -function stringifyQuery(query) { - let search = ''; - for (let key in query) { - const value = query[key]; - key = encodeQueryKey(key); - if (value == null) { - // only null adds the value - if (value !== undefined) { - search += (search.length ? '&' : '') + key; - } - continue; - } - // keep null values - const values = Array.isArray(value) - ? value.map(v => v && encodeQueryValue(v)) - : [value && encodeQueryValue(value)]; - values.forEach(value => { - // skip undefined values in arrays as if they were not present - // smaller code than using filter - if (value !== undefined) { - // only append & with non-empty search - search += (search.length ? '&' : '') + key; - if (value != null) - search += '=' + value; - } - }); - } - return search; -} -/** - * Transforms a {@link LocationQueryRaw} into a {@link LocationQuery} by casting - * numbers into strings, removing keys with an undefined value and replacing - * undefined with null in arrays - * - * @param query - query object to normalize - * @returns a normalized query object - */ -function normalizeQuery(query) { - const normalizedQuery = {}; - for (const key in query) { - const value = query[key]; - if (value !== undefined) { - normalizedQuery[key] = Array.isArray(value) - ? value.map(v => (v == null ? null : '' + v)) - : value == null - ? value - : '' + value; - } - } - return normalizedQuery; -} - -/** - * Create a list of callbacks that can be reset. Used to create before and after navigation guards list - */ -function useCallbacks() { - let handlers = []; - function add(handler) { - handlers.push(handler); - return () => { - const i = handlers.indexOf(handler); - if (i > -1) - handlers.splice(i, 1); - }; - } - function reset() { - handlers = []; - } - return { - add, - list: () => handlers, - reset, - }; -} - -function registerGuard(record, name, guard) { - const removeFromList = () => { - record[name].delete(guard); - }; - vue.onUnmounted(removeFromList); - vue.onDeactivated(removeFromList); - vue.onActivated(() => { - record[name].add(guard); - }); - record[name].add(guard); -} -/** - * Add a navigation guard that triggers whenever the component for the current - * location is about to be left. Similar to {@link beforeRouteLeave} but can be - * used in any component. The guard is removed when the component is unmounted. - * - * @param leaveGuard - {@link NavigationGuard} - */ -function onBeforeRouteLeave(leaveGuard) { - const activeRecord = vue.inject(matchedRouteKey, - // to avoid warning - {}).value; - if (!activeRecord) { - return; - } - registerGuard(activeRecord, 'leaveGuards', leaveGuard); -} -/** - * Add a navigation guard that triggers whenever the current location is about - * to be updated. Similar to {@link beforeRouteUpdate} but can be used in any - * component. The guard is removed when the component is unmounted. - * - * @param updateGuard - {@link NavigationGuard} - */ -function onBeforeRouteUpdate(updateGuard) { - const activeRecord = vue.inject(matchedRouteKey, - // to avoid warning - {}).value; - if (!activeRecord) { - return; - } - registerGuard(activeRecord, 'updateGuards', updateGuard); -} -function guardToPromiseFn(guard, to, from, record, name) { - // keep a reference to the enterCallbackArray to prevent pushing callbacks if a new navigation took place - const enterCallbackArray = record && - // name is defined if record is because of the function overload - (record.enterCallbacks[name] = record.enterCallbacks[name] || []); - return () => new Promise((resolve, reject) => { - const next = (valid) => { - if (valid === false) - reject(createRouterError(4 /* NAVIGATION_ABORTED */, { - from, - to, - })); - else if (valid instanceof Error) { - reject(valid); - } - else if (isRouteLocation(valid)) { - reject(createRouterError(2 /* NAVIGATION_GUARD_REDIRECT */, { - from: to, - to: valid, - })); - } - else { - if (enterCallbackArray && - // since enterCallbackArray is truthy, both record and name also are - record.enterCallbacks[name] === enterCallbackArray && - typeof valid === 'function') - enterCallbackArray.push(valid); - resolve(); - } - }; - // wrapping with Promise.resolve allows it to work with both async and sync guards - const guardReturn = guard.call(record && record.instances[name], to, from, next); - let guardCall = Promise.resolve(guardReturn); - if (guard.length < 3) - guardCall = guardCall.then(next); - guardCall.catch(err => reject(err)); - }); -} -function extractComponentsGuards(matched, guardType, to, from) { - const guards = []; - for (const record of matched) { - for (const name in record.components) { - let rawComponent = record.components[name]; - // skip update and leave guards if the route component is not mounted - if (guardType !== 'beforeRouteEnter' && !record.instances[name]) - continue; - if (isRouteComponent(rawComponent)) { - // __vccOpts is added by vue-class-component and contain the regular options - const options = rawComponent.__vccOpts || rawComponent; - const guard = options[guardType]; - guard && guards.push(guardToPromiseFn(guard, to, from, record, name)); - } - else { - // start requesting the chunk already - let componentPromise = rawComponent(); - guards.push(() => componentPromise.then(resolved => { - if (!resolved) - return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}"`)); - const resolvedComponent = isESModule(resolved) - ? resolved.default - : resolved; - // replace the function with the resolved component - record.components[name] = resolvedComponent; - // __vccOpts is added by vue-class-component and contain the regular options - const options = resolvedComponent.__vccOpts || resolvedComponent; - const guard = options[guardType]; - return guard && guardToPromiseFn(guard, to, from, record, name)(); - })); - } - } - } - return guards; -} -/** - * Allows differentiating lazy components from functional components and vue-class-component - * - * @param component - */ -function isRouteComponent(component) { - return (typeof component === 'object' || - 'displayName' in component || - 'props' in component || - '__vccOpts' in component); -} - -// TODO: we could allow currentRoute as a prop to expose `isActive` and -// `isExactActive` behavior should go through an RFC -function useLink(props) { - const router = vue.inject(routerKey); - const currentRoute = vue.inject(routeLocationKey); - const route = vue.computed(() => router.resolve(vue.unref(props.to))); - const activeRecordIndex = vue.computed(() => { - const { matched } = route.value; - const { length } = matched; - const routeMatched = matched[length - 1]; - const currentMatched = currentRoute.matched; - if (!routeMatched || !currentMatched.length) - return -1; - const index = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched)); - if (index > -1) - return index; - // possible parent record - const parentRecordPath = getOriginalPath(matched[length - 2]); - return ( - // we are dealing with nested routes - length > 1 && - // if the parent and matched route have the same path, this link is - // referring to the empty child. Or we currently are on a different - // child of the same parent - getOriginalPath(routeMatched) === parentRecordPath && - // avoid comparing the child with its parent - currentMatched[currentMatched.length - 1].path !== parentRecordPath - ? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2])) - : index); - }); - const isActive = vue.computed(() => activeRecordIndex.value > -1 && - includesParams(currentRoute.params, route.value.params)); - const isExactActive = vue.computed(() => activeRecordIndex.value > -1 && - activeRecordIndex.value === currentRoute.matched.length - 1 && - isSameRouteLocationParams(currentRoute.params, route.value.params)); - function navigate(e = {}) { - if (guardEvent(e)) { - return router[vue.unref(props.replace) ? 'replace' : 'push'](vue.unref(props.to) - // avoid uncaught errors are they are logged anyway - ).catch(noop); - } - return Promise.resolve(); - } - return { - route, - href: vue.computed(() => route.value.href), - isActive, - isExactActive, - navigate, - }; -} -const RouterLinkImpl = /*#__PURE__*/ vue.defineComponent({ - name: 'RouterLink', - props: { - to: { - type: [String, Object], - required: true, - }, - replace: Boolean, - activeClass: String, - // inactiveClass: String, - exactActiveClass: String, - custom: Boolean, - ariaCurrentValue: { - type: String, - default: 'page', - }, - }, - useLink, - setup(props, { slots }) { - const link = vue.reactive(useLink(props)); - const { options } = vue.inject(routerKey); - const elClass = vue.computed(() => ({ - [getLinkClass(props.activeClass, options.linkActiveClass, 'router-link-active')]: link.isActive, - // [getLinkClass( - // props.inactiveClass, - // options.linkInactiveClass, - // 'router-link-inactive' - // )]: !link.isExactActive, - [getLinkClass(props.exactActiveClass, options.linkExactActiveClass, 'router-link-exact-active')]: link.isExactActive, - })); - return () => { - const children = slots.default && slots.default(link); - return props.custom - ? children - : vue.h('a', { - 'aria-current': link.isExactActive - ? props.ariaCurrentValue - : null, - href: link.href, - // this would override user added attrs but Vue will still add - // the listener so we end up triggering both - onClick: link.navigate, - class: elClass.value, - }, children); - }; - }, -}); -// export the public type for h/tsx inference -// also to avoid inline import() in generated d.ts files -/** - * Component to render a link that triggers a navigation on click. - */ -const RouterLink = RouterLinkImpl; -function guardEvent(e) { - // don't redirect with control keys - if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) - return; - // don't redirect when preventDefault called - if (e.defaultPrevented) - return; - // don't redirect on right click - if (e.button !== undefined && e.button !== 0) - return; - // don't redirect if `target="_blank"` - // @ts-expect-error getAttribute does exist - if (e.currentTarget && e.currentTarget.getAttribute) { - // @ts-expect-error getAttribute exists - const target = e.currentTarget.getAttribute('target'); - if (/\b_blank\b/i.test(target)) - return; - } - // this may be a Weex event which doesn't have this method - if (e.preventDefault) - e.preventDefault(); - return true; -} -function includesParams(outer, inner) { - for (const key in inner) { - const innerValue = inner[key]; - const outerValue = outer[key]; - if (typeof innerValue === 'string') { - if (innerValue !== outerValue) - return false; - } - else { - if (!Array.isArray(outerValue) || - outerValue.length !== innerValue.length || - innerValue.some((value, i) => value !== outerValue[i])) - return false; - } - } - return true; -} -/** - * Get the original path value of a record by following its aliasOf - * @param record - */ -function getOriginalPath(record) { - return record ? (record.aliasOf ? record.aliasOf.path : record.path) : ''; -} -/** - * Utility class to get the active class based on defaults. - * @param propClass - * @param globalClass - * @param defaultClass - */ -const getLinkClass = (propClass, globalClass, defaultClass) => propClass != null - ? propClass - : globalClass != null - ? globalClass - : defaultClass; - -const RouterViewImpl = /*#__PURE__*/ vue.defineComponent({ - name: 'RouterView', - // #674 we manually inherit them - inheritAttrs: false, - props: { - name: { - type: String, - default: 'default', - }, - route: Object, - }, - // Better compat for @vue/compat users - // https://github.com/vuejs/router/issues/1315 - compatConfig: { MODE: 3 }, - setup(props, { attrs, slots }) { - const injectedRoute = vue.inject(routerViewLocationKey); - const routeToDisplay = vue.computed(() => props.route || injectedRoute.value); - const depth = vue.inject(viewDepthKey, 0); - const matchedRouteRef = vue.computed(() => routeToDisplay.value.matched[depth]); - vue.provide(viewDepthKey, depth + 1); - vue.provide(matchedRouteKey, matchedRouteRef); - vue.provide(routerViewLocationKey, routeToDisplay); - const viewRef = vue.ref(); - // watch at the same time the component instance, the route record we are - // rendering, and the name - vue.watch(() => [viewRef.value, matchedRouteRef.value, props.name], ([instance, to, name], [oldInstance, from, oldName]) => { - // copy reused instances - if (to) { - // this will update the instance for new instances as well as reused - // instances when navigating to a new route - to.instances[name] = instance; - // the component instance is reused for a different route or name so - // we copy any saved update or leave guards. With async setup, the - // mounting component will mount before the matchedRoute changes, - // making instance === oldInstance, so we check if guards have been - // added before. This works because we remove guards when - // unmounting/deactivating components - if (from && from !== to && instance && instance === oldInstance) { - if (!to.leaveGuards.size) { - to.leaveGuards = from.leaveGuards; - } - if (!to.updateGuards.size) { - to.updateGuards = from.updateGuards; - } - } - } - // trigger beforeRouteEnter next callbacks - if (instance && - to && - // if there is no instance but to and from are the same this might be - // the first visit - (!from || !isSameRouteRecord(to, from) || !oldInstance)) { - (to.enterCallbacks[name] || []).forEach(callback => callback(instance)); - } - }, { flush: 'post' }); - return () => { - const route = routeToDisplay.value; - const matchedRoute = matchedRouteRef.value; - const ViewComponent = matchedRoute && matchedRoute.components[props.name]; - // we need the value at the time we render because when we unmount, we - // navigated to a different location so the value is different - const currentName = props.name; - if (!ViewComponent) { - return normalizeSlot(slots.default, { Component: ViewComponent, route }); - } - // props from route configuration - const routePropsOption = matchedRoute.props[props.name]; - const routeProps = routePropsOption - ? routePropsOption === true - ? route.params - : typeof routePropsOption === 'function' - ? routePropsOption(route) - : routePropsOption - : null; - const onVnodeUnmounted = vnode => { - // remove the instance reference to prevent leak - if (vnode.component.isUnmounted) { - matchedRoute.instances[currentName] = null; - } - }; - const component = vue.h(ViewComponent, assign({}, routeProps, attrs, { - onVnodeUnmounted, - ref: viewRef, - })); - return ( - // pass the vnode to the slot as a prop. - // h and both accept vnodes - normalizeSlot(slots.default, { Component: component, route }) || - component); - }; - }, -}); -function normalizeSlot(slot, data) { - if (!slot) - return null; - const slotContent = slot(data); - return slotContent.length === 1 ? slotContent[0] : slotContent; -} -// export the public type for h/tsx inference -// also to avoid inline import() in generated d.ts files -/** - * Component to display the current route the user is at. - */ -const RouterView = RouterViewImpl; - -/** - * Creates a Router instance that can be used by a Vue app. - * - * @param options - {@link RouterOptions} - */ -function createRouter(options) { - const matcher = createRouterMatcher(options.routes, options); - const parseQuery$1 = options.parseQuery || parseQuery; - const stringifyQuery$1 = options.stringifyQuery || stringifyQuery; - const routerHistory = options.history; - const beforeGuards = useCallbacks(); - const beforeResolveGuards = useCallbacks(); - const afterGuards = useCallbacks(); - const currentRoute = vue.shallowRef(START_LOCATION_NORMALIZED); - let pendingLocation = START_LOCATION_NORMALIZED; - // leave the scrollRestoration if no scrollBehavior is provided - if (isBrowser && options.scrollBehavior && 'scrollRestoration' in history) { - history.scrollRestoration = 'manual'; - } - const normalizeParams = applyToParams.bind(null, paramValue => '' + paramValue); - const encodeParams = applyToParams.bind(null, encodeParam); - const decodeParams = - // @ts-expect-error: intentionally avoid the type check - applyToParams.bind(null, decode); - function addRoute(parentOrRoute, route) { - let parent; - let record; - if (isRouteName(parentOrRoute)) { - parent = matcher.getRecordMatcher(parentOrRoute); - record = route; - } - else { - record = parentOrRoute; - } - return matcher.addRoute(record, parent); - } - function removeRoute(name) { - const recordMatcher = matcher.getRecordMatcher(name); - if (recordMatcher) { - matcher.removeRoute(recordMatcher); - } - } - function getRoutes() { - return matcher.getRoutes().map(routeMatcher => routeMatcher.record); - } - function hasRoute(name) { - return !!matcher.getRecordMatcher(name); - } - function resolve(rawLocation, currentLocation) { - // const objectLocation = routerLocationAsObject(rawLocation) - // we create a copy to modify it later - currentLocation = assign({}, currentLocation || currentRoute.value); - if (typeof rawLocation === 'string') { - const locationNormalized = parseURL(parseQuery$1, rawLocation, currentLocation.path); - const matchedRoute = matcher.resolve({ path: locationNormalized.path }, currentLocation); - const href = routerHistory.createHref(locationNormalized.fullPath); - // locationNormalized is always a new object - return assign(locationNormalized, matchedRoute, { - params: decodeParams(matchedRoute.params), - hash: decode(locationNormalized.hash), - redirectedFrom: undefined, - href, - }); - } - let matcherLocation; - // path could be relative in object as well - if ('path' in rawLocation) { - matcherLocation = assign({}, rawLocation, { - path: parseURL(parseQuery$1, rawLocation.path, currentLocation.path).path, - }); - } - else { - // remove any nullish param - const targetParams = assign({}, rawLocation.params); - for (const key in targetParams) { - if (targetParams[key] == null) { - delete targetParams[key]; - } - } - // pass encoded values to the matcher so it can produce encoded path and fullPath - matcherLocation = assign({}, rawLocation, { - params: encodeParams(rawLocation.params), - }); - // current location params are decoded, we need to encode them in case the - // matcher merges the params - currentLocation.params = encodeParams(currentLocation.params); - } - const matchedRoute = matcher.resolve(matcherLocation, currentLocation); - const hash = rawLocation.hash || ''; - // decoding them) the matcher might have merged current location params so - // we need to run the decoding again - matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params)); - const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, { - hash: encodeHash(hash), - path: matchedRoute.path, - })); - const href = routerHistory.createHref(fullPath); - return assign({ - fullPath, - // keep the hash encoded so fullPath is effectively path + encodedQuery + - // hash - hash, - query: - // if the user is using a custom query lib like qs, we might have - // nested objects, so we keep the query as is, meaning it can contain - // numbers at `$route.query`, but at the point, the user will have to - // use their own type anyway. - // https://github.com/vuejs/router/issues/328#issuecomment-649481567 - stringifyQuery$1 === stringifyQuery - ? normalizeQuery(rawLocation.query) - : (rawLocation.query || {}), - }, matchedRoute, { - redirectedFrom: undefined, - href, - }); - } - function locationAsObject(to) { - return typeof to === 'string' - ? parseURL(parseQuery$1, to, currentRoute.value.path) - : assign({}, to); - } - function checkCanceledNavigation(to, from) { - if (pendingLocation !== to) { - return createRouterError(8 /* NAVIGATION_CANCELLED */, { - from, - to, - }); - } - } - function push(to) { - return pushWithRedirect(to); - } - function replace(to) { - return push(assign(locationAsObject(to), { replace: true })); - } - function handleRedirectRecord(to) { - const lastMatched = to.matched[to.matched.length - 1]; - if (lastMatched && lastMatched.redirect) { - const { redirect } = lastMatched; - let newTargetLocation = typeof redirect === 'function' ? redirect(to) : redirect; - if (typeof newTargetLocation === 'string') { - newTargetLocation = - newTargetLocation.includes('?') || newTargetLocation.includes('#') - ? (newTargetLocation = locationAsObject(newTargetLocation)) - : // force empty params - { path: newTargetLocation }; - // @ts-expect-error: force empty params when a string is passed to let - // the router parse them again - newTargetLocation.params = {}; - } - return assign({ - query: to.query, - hash: to.hash, - params: to.params, - }, newTargetLocation); - } - } - function pushWithRedirect(to, redirectedFrom) { - const targetLocation = (pendingLocation = resolve(to)); - const from = currentRoute.value; - const data = to.state; - const force = to.force; - // to could be a string where `replace` is a function - const replace = to.replace === true; - const shouldRedirect = handleRedirectRecord(targetLocation); - if (shouldRedirect) - return pushWithRedirect(assign(locationAsObject(shouldRedirect), { - state: data, - force, - replace, - }), - // keep original redirectedFrom if it exists - redirectedFrom || targetLocation); - // if it was a redirect we already called `pushWithRedirect` above - const toLocation = targetLocation; - toLocation.redirectedFrom = redirectedFrom; - let failure; - if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) { - failure = createRouterError(16 /* NAVIGATION_DUPLICATED */, { to: toLocation, from }); - // trigger scroll to allow scrolling to the same anchor - handleScroll(from, from, - // this is a push, the only way for it to be triggered from a - // history.listen is with a redirect, which makes it become a push - true, - // This cannot be the first navigation because the initial location - // cannot be manually navigated to - false); - } - return (failure ? Promise.resolve(failure) : navigate(toLocation, from)) - .catch((error) => isNavigationFailure(error) - ? // navigation redirects still mark the router as ready - isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */) - ? error - : markAsReady(error) // also returns the error - : // reject any unknown error - triggerError(error, toLocation, from)) - .then((failure) => { - if (failure) { - if (isNavigationFailure(failure, 2 /* NAVIGATION_GUARD_REDIRECT */)) { - return pushWithRedirect( - // keep options - assign(locationAsObject(failure.to), { - state: data, - force, - replace, - }), - // preserve the original redirectedFrom if any - redirectedFrom || toLocation); - } - } - else { - // if we fail we don't finalize the navigation - failure = finalizeNavigation(toLocation, from, true, replace, data); - } - triggerAfterEach(toLocation, from, failure); - return failure; - }); - } - /** - * Helper to reject and skip all navigation guards if a new navigation happened - * @param to - * @param from - */ - function checkCanceledNavigationAndReject(to, from) { - const error = checkCanceledNavigation(to, from); - return error ? Promise.reject(error) : Promise.resolve(); - } - // TODO: refactor the whole before guards by internally using router.beforeEach - function navigate(to, from) { - let guards; - const [leavingRecords, updatingRecords, enteringRecords] = extractChangingRecords(to, from); - // all components here have been resolved once because we are leaving - guards = extractComponentsGuards(leavingRecords.reverse(), 'beforeRouteLeave', to, from); - // leavingRecords is already reversed - for (const record of leavingRecords) { - record.leaveGuards.forEach(guard => { - guards.push(guardToPromiseFn(guard, to, from)); - }); - } - const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from); - guards.push(canceledNavigationCheck); - // run the queue of per route beforeRouteLeave guards - return (runGuardQueue(guards) - .then(() => { - // check global guards beforeEach - guards = []; - for (const guard of beforeGuards.list()) { - guards.push(guardToPromiseFn(guard, to, from)); - } - guards.push(canceledNavigationCheck); - return runGuardQueue(guards); - }) - .then(() => { - // check in components beforeRouteUpdate - guards = extractComponentsGuards(updatingRecords, 'beforeRouteUpdate', to, from); - for (const record of updatingRecords) { - record.updateGuards.forEach(guard => { - guards.push(guardToPromiseFn(guard, to, from)); - }); - } - guards.push(canceledNavigationCheck); - // run the queue of per route beforeEnter guards - return runGuardQueue(guards); - }) - .then(() => { - // check the route beforeEnter - guards = []; - for (const record of to.matched) { - // do not trigger beforeEnter on reused views - if (record.beforeEnter && !from.matched.includes(record)) { - if (Array.isArray(record.beforeEnter)) { - for (const beforeEnter of record.beforeEnter) - guards.push(guardToPromiseFn(beforeEnter, to, from)); - } - else { - guards.push(guardToPromiseFn(record.beforeEnter, to, from)); - } - } - } - guards.push(canceledNavigationCheck); - // run the queue of per route beforeEnter guards - return runGuardQueue(guards); - }) - .then(() => { - // NOTE: at this point to.matched is normalized and does not contain any () => Promise - // clear existing enterCallbacks, these are added by extractComponentsGuards - to.matched.forEach(record => (record.enterCallbacks = {})); - // check in-component beforeRouteEnter - guards = extractComponentsGuards(enteringRecords, 'beforeRouteEnter', to, from); - guards.push(canceledNavigationCheck); - // run the queue of per route beforeEnter guards - return runGuardQueue(guards); - }) - .then(() => { - // check global guards beforeResolve - guards = []; - for (const guard of beforeResolveGuards.list()) { - guards.push(guardToPromiseFn(guard, to, from)); - } - guards.push(canceledNavigationCheck); - return runGuardQueue(guards); - }) - // catch any navigation canceled - .catch(err => isNavigationFailure(err, 8 /* NAVIGATION_CANCELLED */) - ? err - : Promise.reject(err))); - } - function triggerAfterEach(to, from, failure) { - // navigation is confirmed, call afterGuards - // TODO: wrap with error handlers - for (const guard of afterGuards.list()) - guard(to, from, failure); - } - /** - * - Cleans up any navigation guards - * - Changes the url if necessary - * - Calls the scrollBehavior - */ - function finalizeNavigation(toLocation, from, isPush, replace, data) { - // a more recent navigation took place - const error = checkCanceledNavigation(toLocation, from); - if (error) - return error; - // only consider as push if it's not the first navigation - const isFirstNavigation = from === START_LOCATION_NORMALIZED; - const state = !isBrowser ? {} : history.state; - // change URL only if the user did a push/replace and if it's not the initial navigation because - // it's just reflecting the url - if (isPush) { - // on the initial navigation, we want to reuse the scroll position from - // history state if it exists - if (replace || isFirstNavigation) - routerHistory.replace(toLocation.fullPath, assign({ - scroll: isFirstNavigation && state && state.scroll, - }, data)); - else - routerHistory.push(toLocation.fullPath, data); - } - // accept current navigation - currentRoute.value = toLocation; - handleScroll(toLocation, from, isPush, isFirstNavigation); - markAsReady(); - } - let removeHistoryListener; - // attach listener to history to trigger navigations - function setupListeners() { - // avoid setting up listeners twice due to an invalid first navigation - if (removeHistoryListener) - return; - removeHistoryListener = routerHistory.listen((to, _from, info) => { - // cannot be a redirect route because it was in history - const toLocation = resolve(to); - // due to dynamic routing, and to hash history with manual navigation - // (manually changing the url or calling history.hash = '#/somewhere'), - // there could be a redirect record in history - const shouldRedirect = handleRedirectRecord(toLocation); - if (shouldRedirect) { - pushWithRedirect(assign(shouldRedirect, { replace: true }), toLocation).catch(noop); - return; - } - pendingLocation = toLocation; - const from = currentRoute.value; - // TODO: should be moved to web history? - if (isBrowser) { - saveScrollPosition(getScrollKey(from.fullPath, info.delta), computeScrollPosition()); - } - navigate(toLocation, from) - .catch((error) => { - if (isNavigationFailure(error, 4 /* NAVIGATION_ABORTED */ | 8 /* NAVIGATION_CANCELLED */)) { - return error; - } - if (isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */)) { - // Here we could call if (info.delta) routerHistory.go(-info.delta, - // false) but this is bug prone as we have no way to wait the - // navigation to be finished before calling pushWithRedirect. Using - // a setTimeout of 16ms seems to work but there is not guarantee for - // it to work on every browser. So Instead we do not restore the - // history entry and trigger a new navigation as requested by the - // navigation guard. - // the error is already handled by router.push we just want to avoid - // logging the error - pushWithRedirect(error.to, toLocation - // avoid an uncaught rejection, let push call triggerError - ) - .then(failure => { - // manual change in hash history #916 ending up in the URL not - // changing but it was changed by the manual url change, so we - // need to manually change it ourselves - if (isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ | - 16 /* NAVIGATION_DUPLICATED */) && - !info.delta && - info.type === NavigationType.pop) { - routerHistory.go(-1, false); - } - }) - .catch(noop); - // avoid the then branch - return Promise.reject(); - } - // do not restore history on unknown direction - if (info.delta) - routerHistory.go(-info.delta, false); - // unrecognized error, transfer to the global handler - return triggerError(error, toLocation, from); - }) - .then((failure) => { - failure = - failure || - finalizeNavigation( - // after navigation, all matched components are resolved - toLocation, from, false); - // revert the navigation - if (failure) { - if (info.delta) { - routerHistory.go(-info.delta, false); - } - else if (info.type === NavigationType.pop && - isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ | 16 /* NAVIGATION_DUPLICATED */)) { - // manual change in hash history #916 - // it's like a push but lacks the information of the direction - routerHistory.go(-1, false); - } - } - triggerAfterEach(toLocation, from, failure); - }) - .catch(noop); - }); - } - // Initialization and Errors - let readyHandlers = useCallbacks(); - let errorHandlers = useCallbacks(); - let ready; - /** - * Trigger errorHandlers added via onError and throws the error as well - * - * @param error - error to throw - * @param to - location we were navigating to when the error happened - * @param from - location we were navigating from when the error happened - * @returns the error as a rejected promise - */ - function triggerError(error, to, from) { - markAsReady(error); - const list = errorHandlers.list(); - if (list.length) { - list.forEach(handler => handler(error, to, from)); - } - else { - console.error(error); - } - return Promise.reject(error); - } - function isReady() { - if (ready && currentRoute.value !== START_LOCATION_NORMALIZED) - return Promise.resolve(); - return new Promise((resolve, reject) => { - readyHandlers.add([resolve, reject]); - }); - } - function markAsReady(err) { - if (!ready) { - // still not ready if an error happened - ready = !err; - setupListeners(); - readyHandlers - .list() - .forEach(([resolve, reject]) => (err ? reject(err) : resolve())); - readyHandlers.reset(); - } - return err; - } - // Scroll behavior - function handleScroll(to, from, isPush, isFirstNavigation) { - const { scrollBehavior } = options; - if (!isBrowser || !scrollBehavior) - return Promise.resolve(); - const scrollPosition = (!isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0))) || - ((isFirstNavigation || !isPush) && - history.state && - history.state.scroll) || - null; - return vue.nextTick() - .then(() => scrollBehavior(to, from, scrollPosition)) - .then(position => position && scrollToPosition(position)) - .catch(err => triggerError(err, to, from)); - } - const go = (delta) => routerHistory.go(delta); - let started; - const installedApps = new Set(); - const router = { - currentRoute, - addRoute, - removeRoute, - hasRoute, - getRoutes, - resolve, - options, - push, - replace, - go, - back: () => go(-1), - forward: () => go(1), - beforeEach: beforeGuards.add, - beforeResolve: beforeResolveGuards.add, - afterEach: afterGuards.add, - onError: errorHandlers.add, - isReady, - install(app) { - const router = this; - app.component('RouterLink', RouterLink); - app.component('RouterView', RouterView); - app.config.globalProperties.$router = router; - Object.defineProperty(app.config.globalProperties, '$route', { - enumerable: true, - get: () => vue.unref(currentRoute), - }); - // this initial navigation is only necessary on client, on server it doesn't - // make sense because it will create an extra unnecessary navigation and could - // lead to problems - if (isBrowser && - // used for the initial navigation client side to avoid pushing - // multiple times when the router is used in multiple apps - !started && - currentRoute.value === START_LOCATION_NORMALIZED) { - // see above - started = true; - push(routerHistory.location).catch(err => { - }); - } - const reactiveRoute = {}; - for (const key in START_LOCATION_NORMALIZED) { - // @ts-expect-error: the key matches - reactiveRoute[key] = vue.computed(() => currentRoute.value[key]); - } - app.provide(routerKey, router); - app.provide(routeLocationKey, vue.reactive(reactiveRoute)); - app.provide(routerViewLocationKey, currentRoute); - const unmountApp = app.unmount; - installedApps.add(app); - app.unmount = function () { - installedApps.delete(app); - // the router is not attached to an app anymore - if (installedApps.size < 1) { - // invalidate the current navigation - pendingLocation = START_LOCATION_NORMALIZED; - removeHistoryListener && removeHistoryListener(); - removeHistoryListener = null; - currentRoute.value = START_LOCATION_NORMALIZED; - started = false; - ready = false; - } - unmountApp(); - }; - }, - }; - return router; -} -function runGuardQueue(guards) { - return guards.reduce((promise, guard) => promise.then(() => guard()), Promise.resolve()); -} -function extractChangingRecords(to, from) { - const leavingRecords = []; - const updatingRecords = []; - const enteringRecords = []; - const len = Math.max(from.matched.length, to.matched.length); - for (let i = 0; i < len; i++) { - const recordFrom = from.matched[i]; - if (recordFrom) { - if (to.matched.find(record => isSameRouteRecord(record, recordFrom))) - updatingRecords.push(recordFrom); - else - leavingRecords.push(recordFrom); - } - const recordTo = to.matched[i]; - if (recordTo) { - // the type doesn't matter because we are comparing per reference - if (!from.matched.find(record => isSameRouteRecord(record, recordTo))) { - enteringRecords.push(recordTo); - } - } - } - return [leavingRecords, updatingRecords, enteringRecords]; -} - -/** - * Returns the router instance. Equivalent to using `$router` inside - * templates. - */ -function useRouter() { - return vue.inject(routerKey); -} -/** - * Returns the current route location. Equivalent to using `$route` inside - * templates. - */ -function useRoute() { - return vue.inject(routeLocationKey); -} - -exports.RouterLink = RouterLink; -exports.RouterView = RouterView; -exports.START_LOCATION = START_LOCATION_NORMALIZED; -exports.createMemoryHistory = createMemoryHistory; -exports.createRouter = createRouter; -exports.createRouterMatcher = createRouterMatcher; -exports.createWebHashHistory = createWebHashHistory; -exports.createWebHistory = createWebHistory; -exports.isNavigationFailure = isNavigationFailure; -exports.matchedRouteKey = matchedRouteKey; -exports.onBeforeRouteLeave = onBeforeRouteLeave; -exports.onBeforeRouteUpdate = onBeforeRouteUpdate; -exports.parseQuery = parseQuery; -exports.routeLocationKey = routeLocationKey; -exports.routerKey = routerKey; -exports.routerViewLocationKey = routerViewLocationKey; -exports.stringifyQuery = stringifyQuery; -exports.useLink = useLink; -exports.useRoute = useRoute; -exports.useRouter = useRouter; -exports.viewDepthKey = viewDepthKey; +module.exports = require('../dist/vue-router.prod.cjs') \ No newline at end of file diff --git a/node_modules/vue-router/dist/vue-router.d.ts b/node_modules/vue-router/dist/vue-router.d.ts index 0f184c0..74452e7 100644 --- a/node_modules/vue-router/dist/vue-router.d.ts +++ b/node_modules/vue-router/dist/vue-router.d.ts @@ -4,7 +4,8 @@ import { Component } from 'vue'; import { ComponentCustomProps } from 'vue'; import { ComponentPublicInstance } from 'vue'; import { ComputedRef } from 'vue'; -import { InjectionKey } from 'vue'; +import { DefineComponent } from 'vue'; +import type { InjectionKey } from 'vue'; import { Ref } from 'vue'; import { UnwrapRef } from 'vue'; import { VNode } from 'vue'; @@ -13,7 +14,7 @@ import { VNodeProps } from 'vue'; declare type Awaitable = T | Promise; /** - * Creates a in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere. + * Creates an in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere. * It's up to the user to replace that location with the starter location by either calling `router.push` or `router.replace`. * * @param base - Base applied to all urls, defaults to '/' @@ -35,18 +36,16 @@ export declare function createRouter(options: RouterOptions): Router; * @param routes - array of initial routes * @param globalOptions - global route options */ -export declare function createRouterMatcher(routes: RouteRecordRaw[], globalOptions: PathParserOptions): RouterMatcher; +export declare function createRouterMatcher(routes: Readonly, globalOptions: PathParserOptions): RouterMatcher; /** - * Creates a hash history. Useful for web applications with no host (e.g. - * `file://`) or when configuring a server to handle any URL is not possible. + * Creates a hash history. Useful for web applications with no host (e.g. `file://`) or when configuring a server to + * handle any URL is not possible. * - * @param base - optional base to provide. Defaults to `location.pathname + - * location.search` If there is a `` tag in the `head`, its value will be - * ignored in favor of this parameter **but note it affects all the - * history.pushState() calls**, meaning that if you use a `` tag, it's - * `href` value **has to match this parameter** (ignoring anything after the - * `#`). + * @param base - optional base to provide. Defaults to `location.pathname + location.search` If there is a `` tag + * in the `head`, its value will be ignored in favor of this parameter **but note it affects all the history.pushState() + * calls**, meaning that if you use a `` tag, it's `href` value **has to match this parameter** (ignoring anything + * after the `#`). * * @example * ```js @@ -83,9 +82,12 @@ export declare function createWebHistory(base?: string): RouterHistory; declare type _ErrorHandler = (error: any, to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded) => any; /** - * Flags so we can combine them when checking for multiple errors + * Flags so we can combine them when checking for multiple errors. This is the internal version of + * {@link NavigationFailureType}. + * + * @internal */ -declare const enum ErrorTypes { +export declare const enum ErrorTypes { MATCHER_NOT_FOUND = 1, NAVIGATION_GUARD_REDIRECT = 2, NAVIGATION_ABORTED = 4, @@ -103,11 +105,20 @@ export declare interface HistoryState { [x: string]: HistoryStateValue; } +/** + * Allowed arrays for history.state. + * + * @internal + */ declare interface HistoryStateArray extends Array { } /** - * Allowed variables in HTML5 history state + * Allowed variables in HTML5 history state. Note that pushState clones the state + * passed and does not accept everything: e.g.: it doesn't accept symbols, nor + * functions as values. It also ignores Symbols as keys. + * + * @internal */ declare type HistoryStateValue = string | number | boolean | null | undefined | HistoryState | HistoryStateArray; @@ -142,21 +153,12 @@ export declare function isNavigationFailure(error: any, type?: ErrorTypes | Navi declare type Lazy = () => Promise; -declare interface LocationAsName { - name: RouteRecordName; - params?: RouteParams; -} - /** - * @internal + * Ensures a route is loaded, so it can be passed as o prop to ``. + * + * @param route - resolved route to load */ -export declare interface LocationAsPath { - path: string; -} - -declare interface LocationAsRelative { - params?: RouteParams; -} +export declare function loadRouteLocation(route: RouteLocationNormalized): Promise; /** * @internal @@ -213,10 +215,60 @@ export declare type LocationQueryValueRaw = LocationQueryValue | number | undefi */ export declare const matchedRouteKey: InjectionKey>; -declare interface MatcherLocation extends Pick { +/** + * Normalized/resolved Route location that returned by the matcher. + */ +declare interface MatcherLocation { + /** + * Name of the matched record + */ + name: RouteRecordName | null | undefined; + /** + * Percentage encoded pathname section of the URL. + */ + path: string; + /** + * Object of decoded params extracted from the `path`. + */ + params: RouteParams; + /** + * Merged `meta` properties from all the matched route records. + */ + meta: RouteMeta; + /** + * Array of {@link RouteRecord} containing components as they were + * passed when adding records. It can also contain redirect records. This + * can't be used directly + */ + matched: RouteRecord[]; +} + +/** + * @internal + */ +declare interface MatcherLocationAsName { + name: RouteRecordName; + params?: RouteParams; } -declare type MatcherLocationRaw = LocationAsPath | LocationAsName | LocationAsRelative; +/** + * @internal + */ +export declare interface MatcherLocationAsPath { + path: string; +} + +/** + * @internal + */ +declare interface MatcherLocationAsRelative { + params?: RouteParams; +} + +/** + * Route location that can be passed to the matcher. + */ +declare type MatcherLocationRaw = MatcherLocationAsPath | MatcherLocationAsName | MatcherLocationAsRelative; declare interface NavigationCallback { (to: HistoryLocation, from: HistoryLocation, information: NavigationInformation): void; @@ -300,17 +352,22 @@ export declare interface NavigationHookAfter { } declare interface NavigationInformation { - type: NavigationType_2; + type: NavigationType; direction: NavigationDirection; delta: number; } -declare interface NavigationRedirectError extends Omit { +/** + * Internal error used to detect a redirection. + * + * @internal + */ +export declare interface NavigationRedirectError extends Omit { type: ErrorTypes.NAVIGATION_GUARD_REDIRECT; to: RouteLocationRaw; } -declare enum NavigationType_2 { +declare enum NavigationType { pop = "pop", push = "push" } @@ -360,7 +417,7 @@ declare interface PathParser { */ keys: PathParserParamKey[]; /** - * Parses a url and returns the matched params or nul if it doesn't match. An + * Parses a url and returns the matched params or null if it doesn't match. An * optional param that isn't preset will be an empty string. A repeatable * param will be an array if there is at least one value. * @@ -385,20 +442,28 @@ export declare type PathParserOptions = Pick<_PathParserOptions, 'end' | 'sensit */ export declare interface _PathParserOptions { /** - * Makes the RegExp case sensitive. Defaults to false + * Makes the RegExp case-sensitive. + * + * @defaultValue `false` */ sensitive?: boolean; /** - * Should we disallow a trailing slash. Defaults to false + * Whether to disallow a trailing slash or not. + * + * @defaultValue `false` */ strict?: boolean; /** - * Should the RegExp match from the beginning by prepending a `^` to it. Defaults to true + * Should the RegExp match from the beginning by prepending a `^` to it. * @internal + * + * @defaultValue `true` */ start?: boolean; /** - * Should the RegExp match until the end by appending a `$` to it. Defaults to true + * Should the RegExp match until the end by appending a `$` to it. + * + * @defaultValue `true` */ end?: boolean; } @@ -420,7 +485,7 @@ declare type RawRouteComponent = RouteComponent | Lazy; /** * Allowed Component in {@link RouteLocationMatched} */ -export declare type RouteComponent = Component; +export declare type RouteComponent = Component | DefineComponent; /** * {@link RouteLocationRaw} resolved using the matcher @@ -439,11 +504,7 @@ export declare interface RouteLocation extends _RouteLocationBase { * * @internal */ -export declare interface _RouteLocationBase { - /** - * Percentage encoded pathname section of the URL. - */ - path: string; +export declare interface _RouteLocationBase extends Pick { /** * The whole location including the `search` and `hash`. This string is * percentage encoded. @@ -457,23 +518,11 @@ export declare interface _RouteLocationBase { * Hash of the current location. If present, starts with a `#`. */ hash: string; - /** - * Name of the matched record - */ - name: RouteRecordName | null | undefined; - /** - * Object of decoded params extracted from the `path`. - */ - params: RouteParams; /** * Contains the location we were initially trying to access before ending up * on the current location. */ redirectedFrom: RouteLocation | undefined; - /** - * Merged `meta` properties from all of the matched route records. - */ - meta: RouteMeta; } /** @@ -485,7 +534,15 @@ export declare interface _RouteLocationBase { export declare const routeLocationKey: InjectionKey; export declare interface RouteLocationMatched extends RouteRecordNormalized { - components: Record; + components: Record | null | undefined; +} + +/** + * Route Location that can infer the necessary params based on the name. + * + * @internal + */ +export declare interface RouteLocationNamedRaw extends RouteQueryAndHash, LocationAsRelativeRaw, RouteLocationOptions { } /** @@ -505,20 +562,25 @@ export declare interface RouteLocationNormalized extends _RouteLocationBase { export declare interface RouteLocationNormalizedLoaded extends _RouteLocationBase { /** * Array of {@link RouteLocationMatched} containing only plain components (any - * lazy-loaded components have been loaded and were replaced inside of the + * lazy-loaded components have been loaded and were replaced inside the * `components` object) so it can be directly used to display routes. It * cannot contain redirect records either */ matched: RouteLocationMatched[]; } +/** + * Common options for all navigation methods. + */ export declare interface RouteLocationOptions { /** * Replace the entry in the history instead of pushing a new entry */ replace?: boolean; /** - * Triggers the navigation even if the location is the same as the current one + * Triggers the navigation even if the location is the same as the current one. + * Note this will also add a new entry to the history unless `replace: true` + * is passed. */ force?: boolean; /** @@ -529,10 +591,18 @@ export declare interface RouteLocationOptions { state?: HistoryState; } +/** + * Route Location that can infer the possible paths. + * + * @internal + */ +export declare interface RouteLocationPathRaw extends RouteQueryAndHash, MatcherLocationAsPath, RouteLocationOptions { +} + /** * User-level route location */ -export declare type RouteLocationRaw = string | (RouteQueryAndHash & LocationAsPath & RouteLocationOptions) | (RouteQueryAndHash & LocationAsRelativeRaw & RouteLocationOptions); +export declare type RouteLocationRaw = string | RouteLocationPathRaw | RouteLocationNamedRaw; /** * Interface to type `meta` fields in route records. @@ -576,7 +646,7 @@ export declare interface RouteQueryAndHash { } /** - * Router instance + * Router instance. */ export declare interface Router { /** @@ -591,14 +661,18 @@ export declare interface Router { */ readonly options: RouterOptions; /** - * Add a new {@link RouteRecordRaw route record} as the child of an existing route. + * Allows turning off the listening of history events. This is a low level api for micro-frontends. + */ + listening: boolean; + /** + * Add a new {@link RouteRecordRaw | route record} as the child of an existing route. * * @param parentName - Parent Route Record where `route` should be appended at * @param route - Route Record to add */ addRoute(parentName: RouteRecordName, route: RouteRecordRaw): () => void; /** - * Add a new {@link RouteRecordRaw route record} to the router. + * Add a new {@link RouteRecordRaw | route record} to the router. * * @param route - Route Record to add */ @@ -616,14 +690,14 @@ export declare interface Router { */ hasRoute(name: RouteRecordName): boolean; /** - * Get a full list of all the {@link RouteRecord route records}. + * Get a full list of all the {@link RouteRecord | route records}. */ getRoutes(): RouteRecord[]; /** - * Returns the {@link RouteLocation normalized version} of a - * {@link RouteLocationRaw route location}. Also includes an `href` property - * that includes any existing `base`. By default the `currentLocation` used is - * `route.currentRoute` and should only be overriden in advanced use cases. + * Returns the {@link RouteLocation | normalized version} of a + * {@link RouteLocationRaw | route location}. Also includes an `href` property + * that includes any existing `base`. By default, the `currentLocation` used is + * `route.currentRoute` and should only be overridden in advanced use cases. * * @param to - Raw route location to resolve * @param currentLocation - Optional current location to resolve against @@ -726,7 +800,7 @@ export declare interface Router { isReady(): Promise; /** * Called automatically by `app.use(router)`. Should not be called manually by - * the user. + * the user. This will trigger the initial navigation when on client side. * * @internal * @param app - Application that uses the router @@ -757,10 +831,6 @@ export declare interface _RouteRecordBase extends PathParserOptions { * target location. */ redirect?: RouteRecordRedirectOption; - /** - * Array of nested routes. - */ - children?: RouteRecordRaw[]; /** * Aliases for the record. Allows defining extra paths that will behave like a * copy of the record. Allows having paths shorthands like `/users/:id` and @@ -780,6 +850,14 @@ export declare interface _RouteRecordBase extends PathParserOptions { * Arbitrary data attached to the record. */ meta?: RouteMeta; + /** + * Array of nested routes. + */ + children?: RouteRecordRaw[]; + /** + * Allow passing down params as props to the component rendered by `router-view`. + */ + props?: _RouteRecordProps | Record; } declare interface RouteRecordMatcher extends PathParser { @@ -798,6 +876,26 @@ declare interface RouteRecordMultipleViews extends _RouteRecordBase { */ components: Record; component?: never; + children?: never; + redirect?: never; + /** + * Allow passing down params as props to the component rendered by + * `router-view`. Should be an object with the same keys as `components` or a + * boolean to be applied to every component. + */ + props?: Record | boolean; +} + +/** + * Route Record defining multiple named components with the `components` option and children. + */ +declare interface RouteRecordMultipleViewsWithChildren extends _RouteRecordBase { + /** + * Components to display when the URL matches this route. Allow using named views. + */ + components?: Record | null | undefined; + component?: never; + children: RouteRecordRaw[]; /** * Allow passing down params as props to the component rendered by * `router-view`. Should be an object with the same keys as `components` or a @@ -812,7 +910,7 @@ declare interface RouteRecordMultipleViews extends _RouteRecordBase { export declare type RouteRecordName = string | symbol; /** - * Normalized version of a {@link RouteRecord route record} + * Normalized version of a {@link RouteRecord | route record}. */ export declare interface RouteRecordNormalized { /** @@ -830,11 +928,11 @@ export declare interface RouteRecordNormalized { /** * {@inheritDoc RouteRecordMultipleViews.components} */ - components: RouteRecordMultipleViews['components']; + components: RouteRecordMultipleViews['components'] | null | undefined; /** - * {@inheritDoc _RouteRecordBase.components} + * Nested route records. */ - children: Exclude<_RouteRecordBase['children'], void>; + children: RouteRecordRaw[]; /** * {@inheritDoc _RouteRecordBase.meta} */ @@ -887,7 +985,7 @@ export declare interface RouteRecordNormalized { */ declare type _RouteRecordProps = boolean | Record | ((to: RouteLocationNormalized) => Record); -export declare type RouteRecordRaw = RouteRecordSingleView | RouteRecordMultipleViews | RouteRecordRedirect; +export declare type RouteRecordRaw = RouteRecordSingleView | RouteRecordSingleViewWithChildren | RouteRecordMultipleViews | RouteRecordMultipleViewsWithChildren | RouteRecordRedirect; /** * Route Record that defines a redirect. Cannot have `component` or `components` @@ -897,6 +995,7 @@ declare interface RouteRecordRedirect extends _RouteRecordBase { redirect: RouteRecordRedirectOption; component?: never; components?: never; + props?: never; } /** @@ -913,6 +1012,24 @@ declare interface RouteRecordSingleView extends _RouteRecordBase { */ component: RawRouteComponent; components?: never; + children?: never; + redirect?: never; + /** + * Allow passing down params as props to the component rendered by `router-view`. + */ + props?: _RouteRecordProps; +} + +/** + * Route Record defining one single component with a nested view. + */ +declare interface RouteRecordSingleViewWithChildren extends _RouteRecordBase { + /** + * Component to display when the URL matches this route. + */ + component?: RawRouteComponent | null | undefined; + components?: never; + children: RouteRecordRaw[]; /** * Allow passing down params as props to the component rendered by `router-view`. */ @@ -928,8 +1045,8 @@ declare interface RouteRecordSingleView extends _RouteRecordBase { export declare interface RouterHistory { /** * Base path that is prepended to every url. This allows hosting an SPA at a - * subfolder of a domain like `example.com/subfolder` by having a `base` of - * `/subfolder` + * sub-folder of a domain like `example.com/sub-folder` by having a `base` of + * `/sub-folder` */ readonly base: string; /** @@ -1006,7 +1123,15 @@ export declare const routerKey: InjectionKey; /** * Component to render a link that triggers a navigation on click. */ -export declare const RouterLink: { +export declare const RouterLink: _RouterLinkI; + +/** + * Typed version of the `RouterLink` component. Its generic defaults to the typed router, so it can be inferred + * automatically for JSX. + * + * @internal + */ +export declare interface _RouterLinkI { new (): { $props: AllowedComponentProps & ComponentCustomProps & VNodeProps & RouterLinkProps; $slots: { @@ -1019,7 +1144,7 @@ export declare const RouterLink: { * @internal */ useLink: typeof useLink; -}; +} declare interface RouterLinkOptions { /** @@ -1047,7 +1172,9 @@ export declare interface RouterLinkProps extends RouterLinkOptions { */ exactActiveClass?: string; /** - * Value passed to the attribute `aria-current` when the link is exact active. Defaults to "page" + * Value passed to the attribute `aria-current` when the link is exact active. + * + * @defaultValue `'page'` */ ariaCurrentValue?: 'page' | 'step' | 'location' | 'date' | 'time' | 'true' | 'false'; } @@ -1097,7 +1224,7 @@ export declare interface RouterOptions extends PathParserOptions { /** * Initial list of routes that should be added to the router. */ - routes: RouteRecordRaw[]; + routes: Readonly; /** * Function to control scrolling when navigating between pages. Can return a * Promise to delay scrolling. Check {@link ScrollBehavior}. @@ -1116,7 +1243,7 @@ export declare interface RouterOptions extends PathParserOptions { * {@link RouterOptions.stringifyQuery}. * * @example - * Let's say you want to use the package {@link https://github.com/ljharb/qs | qs} + * Let's say you want to use the [qs package](https://github.com/ljharb/qs) * to parse queries, you can provide both `parseQuery` and `stringifyQuery`: * ```js * import qs from 'qs' @@ -1253,6 +1380,14 @@ export declare const START_LOCATION: RouteLocationNormalizedLoaded; */ export declare function stringifyQuery(query: LocationQueryRaw): string; +/** + * Allows customizing existing types of the router that are used globally like `$router`, ``, and `beforeRouteLeave()`. **ONLY FOR INTERNAL USAGE**. + * + * @internal + */ +export declare interface TypesConfig { +} + export declare function useLink(props: UseLinkOptions): { route: ComputedRef; +export declare const viewDepthKey: InjectionKey>; /** * Type to transform a static object into one that allows passing Refs as @@ -1310,10 +1445,12 @@ declare module '@vue/runtime-core' { * @param next - function to validate, cancel or modify (by redirecting) the * navigation */ - beforeRouteEnter?: NavigationGuardWithThis + beforeRouteEnter?: TypesConfig extends Record<'beforeRouteEnter', infer T> + ? T + : NavigationGuardWithThis /** - * Guard called whenever the route that renders this component has changed but + * Guard called whenever the route that renders this component has changed, but * it is reused for the new route. This allows you to guard for changes in * params, the query or the hash. * @@ -1322,7 +1459,9 @@ declare module '@vue/runtime-core' { * @param next - function to validate, cancel or modify (by redirecting) the * navigation */ - beforeRouteUpdate?: NavigationGuard + beforeRouteUpdate?: TypesConfig extends Record<'beforeRouteUpdate', infer T> + ? T + : NavigationGuard /** * Guard called when the router is navigating away from the current route that @@ -1333,17 +1472,30 @@ declare module '@vue/runtime-core' { * @param next - function to validate, cancel or modify (by redirecting) the * navigation */ - beforeRouteLeave?: NavigationGuard + beforeRouteLeave?: TypesConfig extends Record<'beforeRouteLeave', infer T> + ? T + : NavigationGuard } export interface ComponentCustomProperties { /** * Normalized current location. See {@link RouteLocationNormalizedLoaded}. */ - $route: RouteLocationNormalizedLoaded + $route: TypesConfig extends Record<'$route', infer T> + ? T + : RouteLocationNormalizedLoaded /** * {@link Router} instance used by the application. */ - $router: Router + $router: TypesConfig extends Record<'$router', infer T> ? T : Router + } + + export interface GlobalComponents { + RouterView: TypesConfig extends Record<'RouterView', infer T> + ? T + : typeof RouterView + RouterLink: TypesConfig extends Record<'RouterLink', infer T> + ? T + : typeof RouterLink } } diff --git a/node_modules/vue-router/dist/vue-router.esm-browser.js b/node_modules/vue-router/dist/vue-router.esm-browser.js index 7e8d81b..d10dec6 100644 --- a/node_modules/vue-router/dist/vue-router.esm-browser.js +++ b/node_modules/vue-router/dist/vue-router.esm-browser.js @@ -1,70 +1,33 @@ /*! - * vue-router v4.0.15 + * vue-router v4.1.5 * (c) 2022 Eduardo San Martin Morote * @license MIT */ import { getCurrentInstance, inject, onUnmounted, onDeactivated, onActivated, computed, unref, watchEffect, defineComponent, reactive, h, provide, ref, watch, shallowRef, nextTick } from 'vue'; import { setupDevtoolsPlugin } from '@vue/devtools-api'; -const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -const PolySymbol = (name) => -// vr = vue router -hasSymbol - ? Symbol('[vue-router]: ' + name ) - : ('[vue-router]: ' ) + name; -// rvlm = Router View Location Matched -/** - * RouteRecord being rendered by the closest ancestor Router View. Used for - * `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View - * Location Matched - * - * @internal - */ -const matchedRouteKey = /*#__PURE__*/ PolySymbol('router view location matched' ); -/** - * Allows overriding the router view depth to control which component in - * `matched` is rendered. rvd stands for Router View Depth - * - * @internal - */ -const viewDepthKey = /*#__PURE__*/ PolySymbol('router view depth' ); -/** - * Allows overriding the router instance returned by `useRouter` in tests. r - * stands for router - * - * @internal - */ -const routerKey = /*#__PURE__*/ PolySymbol('router' ); -/** - * Allows overriding the current route returned by `useRoute` in tests. rl - * stands for route location - * - * @internal - */ -const routeLocationKey = /*#__PURE__*/ PolySymbol('route location' ); -/** - * Allows overriding the current route used by router-view. Internally this is - * used when the `route` prop is passed. - * - * @internal - */ -const routerViewLocationKey = /*#__PURE__*/ PolySymbol('router view location' ); - const isBrowser = typeof window !== 'undefined'; function isESModule(obj) { - return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module'); + return obj.__esModule || obj[Symbol.toStringTag] === 'Module'; } const assign = Object.assign; function applyToParams(fn, params) { const newParams = {}; for (const key in params) { const value = params[key]; - newParams[key] = Array.isArray(value) ? value.map(fn) : fn(value); + newParams[key] = isArray(value) + ? value.map(fn) + : fn(value); } return newParams; } const noop = () => { }; +/** + * Typesafe alternative to Array.isArray + * https://github.com/microsoft/TypeScript/pull/48228 + */ +const isArray = Array.isArray; function warn(msg) { // avoid using ...args as it breaks in older Edge builds @@ -75,7 +38,7 @@ function warn(msg) { const TRAILING_SLASH_RE = /\/$/; const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, ''); /** - * Transforms an URI into a normalized history location + * Transforms a URI into a normalized history location * * @param parseQuery * @param location - URI to normalize @@ -86,8 +49,13 @@ const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, ''); function parseURL(parseQuery, location, currentLocation = '/') { let path, query = {}, searchString = '', hash = ''; // Could use URL and URLSearchParams but IE 11 doesn't support it - const searchPos = location.indexOf('?'); - const hashPos = location.indexOf('#', searchPos > -1 ? searchPos : 0); + // TODO: move to new URL() + const hashPos = location.indexOf('#'); + let searchPos = location.indexOf('?'); + // the hash appears before the search, so it's not part of the search string + if (hashPos < searchPos && hashPos >= 0) { + searchPos = -1; + } if (searchPos > -1) { path = location.slice(0, searchPos); searchString = location.slice(searchPos + 1, hashPos > -1 ? hashPos : location.length); @@ -119,8 +87,7 @@ function stringifyURL(stringifyQuery, location) { return location.path + (query && '?') + query + (location.hash || ''); } /** - * Strips off the base from the beginning of a location.pathname in a non - * case-sensitive way. + * Strips off the base from the beginning of a location.pathname in a non-case-sensitive way. * * @param pathname - location.pathname * @param base - base to strip off @@ -172,9 +139,9 @@ function isSameRouteLocationParams(a, b) { return true; } function isSameRouteLocationParamsValue(a, b) { - return Array.isArray(a) + return isArray(a) ? isEquivalentArray(a, b) - : Array.isArray(b) + : isArray(b) ? isEquivalentArray(b, a) : a === b; } @@ -186,7 +153,7 @@ function isSameRouteLocationParamsValue(a, b) { * @param b - array of values or a single value */ function isEquivalentArray(a, b) { - return Array.isArray(b) + return isArray(b) ? a.length === b.length && a.every((value, i) => value === b[i]) : a.length === 1 && a[0] === b; } @@ -212,18 +179,24 @@ function resolveRelativePath(to, from) { let segment; for (toPosition = 0; toPosition < toSegments.length; toPosition++) { segment = toSegments[toPosition]; - // can't go below zero - if (position === 1 || segment === '.') + // we stay on the same position + if (segment === '.') continue; - if (segment === '..') - position--; - // found something that is not relative path + // go up in the from array + if (segment === '..') { + // we can't go below zero, but we still need to increment toPosition + if (position > 1) + position--; + // continue + } + // we reached a non-relative path, we stop here else break; } return (fromSegments.slice(0, position).join('/') + '/' + toSegments + // ensure we use at least the last element in the toSegments .slice(toPosition - (toPosition === toSegments.length ? 1 : 0)) .join('/')); } @@ -452,7 +425,7 @@ function useHistoryListeners(base, historyState, currentLocation, replace) { pauseState = currentLocation.value; } function listen(callback) { - // setup the listener and prepare teardown callbacks + // set up the listener and prepare teardown callbacks listeners.push(callback); const teardown = () => { const index = listeners.indexOf(callback); @@ -475,7 +448,7 @@ function useHistoryListeners(base, historyState, currentLocation, replace) { window.removeEventListener('popstate', popStateHandler); window.removeEventListener('beforeunload', beforeUnloadListener); } - // setup the listeners and prepare teardown callbacks + // set up the listeners and prepare teardown callbacks window.addEventListener('popstate', popStateHandler); window.addEventListener('beforeunload', beforeUnloadListener); return { @@ -513,14 +486,14 @@ function useHistoryStateNavigation(base) { // the length is off by one, we need to decrease it position: history.length - 1, replaced: true, - // don't add a scroll as the user may have an anchor and we want + // don't add a scroll as the user may have an anchor, and we want // scrollBehavior to be triggered without a saved position scroll: null, }, true); } function changeLocation(to, state, replace) { /** - * if a base tag is provided and we are on a normal domain, we have to + * if a base tag is provided, and we are on a normal domain, we have to * respect the provided `base` attribute because pushState() will use it and * potentially erase anything before the `#` like at * https://github.com/vuejs/router/issues/685 where a base of @@ -616,7 +589,7 @@ function createWebHistory(base) { } /** - * Creates a in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere. + * Creates an in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere. * It's up to the user to replace that location with the starter location by either calling `router.push` or `router.replace`. * * @param base - Base applied to all urls, defaults to '/' @@ -701,15 +674,13 @@ function createMemoryHistory(base = '') { } /** - * Creates a hash history. Useful for web applications with no host (e.g. - * `file://`) or when configuring a server to handle any URL is not possible. + * Creates a hash history. Useful for web applications with no host (e.g. `file://`) or when configuring a server to + * handle any URL is not possible. * - * @param base - optional base to provide. Defaults to `location.pathname + - * location.search` If there is a `` tag in the `head`, its value will be - * ignored in favor of this parameter **but note it affects all the - * history.pushState() calls**, meaning that if you use a `` tag, it's - * `href` value **has to match this parameter** (ignoring anything after the - * `#`). + * @param base - optional base to provide. Defaults to `location.pathname + location.search` If there is a `` tag + * in the `head`, its value will be ignored in favor of this parameter **but note it affects all the history.pushState() + * calls**, meaning that if you use a `` tag, it's `href` value **has to match this parameter** (ignoring anything + * after the `#`). * * @example * ```js @@ -774,7 +745,7 @@ const START_LOCATION_NORMALIZED = { redirectedFrom: undefined, }; -const NavigationFailureSymbol = /*#__PURE__*/ PolySymbol('navigation failure' ); +const NavigationFailureSymbol = Symbol('navigation failure' ); /** * Enumeration with all possible types for navigation failures. Can be passed to * {@link isNavigationFailure} to check for specific failures. @@ -799,21 +770,21 @@ var NavigationFailureType; })(NavigationFailureType || (NavigationFailureType = {})); // DEV only debug messages const ErrorTypeMessages = { - [1 /* MATCHER_NOT_FOUND */]({ location, currentLocation }) { + [1 /* ErrorTypes.MATCHER_NOT_FOUND */]({ location, currentLocation }) { return `No match for\n ${JSON.stringify(location)}${currentLocation ? '\nwhile being at\n' + JSON.stringify(currentLocation) : ''}`; }, - [2 /* NAVIGATION_GUARD_REDIRECT */]({ from, to, }) { + [2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */]({ from, to, }) { return `Redirected from "${from.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`; }, - [4 /* NAVIGATION_ABORTED */]({ from, to }) { + [4 /* ErrorTypes.NAVIGATION_ABORTED */]({ from, to }) { return `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`; }, - [8 /* NAVIGATION_CANCELLED */]({ from, to }) { + [8 /* ErrorTypes.NAVIGATION_CANCELLED */]({ from, to }) { return `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`; }, - [16 /* NAVIGATION_DUPLICATED */]({ from, to }) { + [16 /* ErrorTypes.NAVIGATION_DUPLICATED */]({ from, to }) { return `Avoided redundant navigation to current location: "${from.fullPath}".`; }, }; @@ -845,7 +816,7 @@ function stringifyRoute(to) { return JSON.stringify(location, null, 2); } -// default pattern for a param: non greedy everything but / +// default pattern for a param: non-greedy everything but / const BASE_PARAM_PATTERN = '[^/]+?'; const BASE_PATH_PARSER_OPTIONS = { sensitive: false, @@ -872,23 +843,23 @@ function tokensToParser(segments, extraOptions) { const keys = []; for (const segment of segments) { // the root segment needs special treatment - const segmentScores = segment.length ? [] : [90 /* Root */]; + const segmentScores = segment.length ? [] : [90 /* PathScore.Root */]; // allow trailing slash if (options.strict && !segment.length) pattern += '/'; for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) { const token = segment[tokenIndex]; - // resets the score if we are inside a sub segment /:a-other-:b - let subSegmentScore = 40 /* Segment */ + - (options.sensitive ? 0.25 /* BonusCaseSensitive */ : 0); - if (token.type === 0 /* Static */) { + // resets the score if we are inside a sub-segment /:a-other-:b + let subSegmentScore = 40 /* PathScore.Segment */ + + (options.sensitive ? 0.25 /* PathScore.BonusCaseSensitive */ : 0); + if (token.type === 0 /* TokenType.Static */) { // prepend the slash if we are starting a new segment if (!tokenIndex) pattern += '/'; pattern += token.value.replace(REGEX_CHARS_RE, '\\$&'); - subSegmentScore += 40 /* Static */; + subSegmentScore += 40 /* PathScore.Static */; } - else if (token.type === 1 /* Param */) { + else if (token.type === 1 /* TokenType.Param */) { const { value, repeatable, optional, regexp } = token; keys.push({ name: value, @@ -898,7 +869,7 @@ function tokensToParser(segments, extraOptions) { const re = regexp ? regexp : BASE_PARAM_PATTERN; // the user provided a custom regexp /:id(\\d+) if (re !== BASE_PARAM_PATTERN) { - subSegmentScore += 10 /* BonusCustomRegExp */; + subSegmentScore += 10 /* PathScore.BonusCustomRegExp */; // make sure the regexp is valid before using it try { new RegExp(`(${re})`); @@ -921,13 +892,13 @@ function tokensToParser(segments, extraOptions) { if (optional) subPattern += '?'; pattern += subPattern; - subSegmentScore += 20 /* Dynamic */; + subSegmentScore += 20 /* PathScore.Dynamic */; if (optional) - subSegmentScore += -8 /* BonusOptional */; + subSegmentScore += -8 /* PathScore.BonusOptional */; if (repeatable) - subSegmentScore += -20 /* BonusRepeatable */; + subSegmentScore += -20 /* PathScore.BonusRepeatable */; if (re === '.*') - subSegmentScore += -50 /* BonusWildcard */; + subSegmentScore += -50 /* PathScore.BonusWildcard */; } segmentScores.push(subSegmentScore); } @@ -938,7 +909,7 @@ function tokensToParser(segments, extraOptions) { // only apply the strict bonus to the last score if (options.strict && options.end) { const i = score.length - 1; - score[i][score[i].length - 1] += 0.7000000000000001 /* BonusStrict */; + score[i][score[i].length - 1] += 0.7000000000000001 /* PathScore.BonusStrict */; } // TODO: dev only warn double trailing slash if (!options.strict) @@ -970,20 +941,22 @@ function tokensToParser(segments, extraOptions) { path += '/'; avoidDuplicatedSlash = false; for (const token of segment) { - if (token.type === 0 /* Static */) { + if (token.type === 0 /* TokenType.Static */) { path += token.value; } - else if (token.type === 1 /* Param */) { + else if (token.type === 1 /* TokenType.Param */) { const { value, repeatable, optional } = token; const param = value in params ? params[value] : ''; - if (Array.isArray(param) && !repeatable) + if (isArray(param) && !repeatable) { throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`); - const text = Array.isArray(param) ? param.join('/') : param; + } + const text = isArray(param) + ? param.join('/') + : param; if (!text) { if (optional) { - // if we have more than one optional param like /:a?-static and there are more segments, we don't need to - // care about the optional param - if (segment.length < 2 && segments.length > 1) { + // if we have more than one optional param like /:a?-static we don't need to care about the optional param + if (segment.length < 2) { // remove the last slash as we could be at the end if (path.endsWith('/')) path = path.slice(0, -1); @@ -999,7 +972,8 @@ function tokensToParser(segments, extraOptions) { } } } - return path; + // avoid empty path when we have multiple optional params + return path || '/'; } return { re, @@ -1030,12 +1004,12 @@ function compareScoreArray(a, b) { // if the last subsegment was Static, the shorter segments should be sorted first // otherwise sort the longest segment first if (a.length < b.length) { - return a.length === 1 && a[0] === 40 /* Static */ + 40 /* Segment */ + return a.length === 1 && a[0] === 40 /* PathScore.Static */ + 40 /* PathScore.Segment */ ? -1 : 1; } else if (a.length > b.length) { - return b.length === 1 && b[0] === 40 /* Static */ + 40 /* Segment */ + return b.length === 1 && b[0] === 40 /* PathScore.Static */ + 40 /* PathScore.Segment */ ? 1 : -1; } @@ -1059,6 +1033,12 @@ function comparePathParserScore(a, b) { return comp; i++; } + if (Math.abs(bScore.length - aScore.length) === 1) { + if (isLastScoreNegative(aScore)) + return 1; + if (isLastScoreNegative(bScore)) + return -1; + } // if a and b share the same score entries but b has more, sort b first return bScore.length - aScore.length; // this is the ternary version @@ -1068,9 +1048,19 @@ function comparePathParserScore(a, b) { // ? -1 // : 0 } +/** + * This allows detecting splats at the end of a path: /home/:id(.*)* + * + * @param score - score to check + * @returns true if the last entry is negative + */ +function isLastScoreNegative(score) { + const last = score[score.length - 1]; + return score.length > 0 && last[last.length - 1] < 0; +} const ROOT_TOKEN = { - type: 0 /* Static */, + type: 0 /* TokenType.Static */, value: '', }; const VALID_PARAM_RE = /[a-zA-Z0-9_]/; @@ -1090,7 +1080,7 @@ function tokenizePath(path) { function crash(message) { throw new Error(`ERR (${state})/"${buffer}": ${message}`); } - let state = 0 /* Static */; + let state = 0 /* TokenizerState.Static */; let previousState = state; const tokens = []; // the segment will always be valid because we get into the initial state @@ -1112,19 +1102,19 @@ function tokenizePath(path) { function consumeBuffer() { if (!buffer) return; - if (state === 0 /* Static */) { + if (state === 0 /* TokenizerState.Static */) { segment.push({ - type: 0 /* Static */, + type: 0 /* TokenType.Static */, value: buffer, }); } - else if (state === 1 /* Param */ || - state === 2 /* ParamRegExp */ || - state === 3 /* ParamRegExpEnd */) { + else if (state === 1 /* TokenizerState.Param */ || + state === 2 /* TokenizerState.ParamRegExp */ || + state === 3 /* TokenizerState.ParamRegExpEnd */) { if (segment.length > 1 && (char === '*' || char === '+')) crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`); segment.push({ - type: 1 /* Param */, + type: 1 /* TokenType.Param */, value: buffer, regexp: customRe, repeatable: char === '*' || char === '+', @@ -1141,13 +1131,13 @@ function tokenizePath(path) { } while (i < path.length) { char = path[i++]; - if (char === '\\' && state !== 2 /* ParamRegExp */) { + if (char === '\\' && state !== 2 /* TokenizerState.ParamRegExp */) { previousState = state; - state = 4 /* EscapeNext */; + state = 4 /* TokenizerState.EscapeNext */; continue; } switch (state) { - case 0 /* Static */: + case 0 /* TokenizerState.Static */: if (char === '/') { if (buffer) { consumeBuffer(); @@ -1156,32 +1146,32 @@ function tokenizePath(path) { } else if (char === ':') { consumeBuffer(); - state = 1 /* Param */; + state = 1 /* TokenizerState.Param */; } else { addCharToBuffer(); } break; - case 4 /* EscapeNext */: + case 4 /* TokenizerState.EscapeNext */: addCharToBuffer(); state = previousState; break; - case 1 /* Param */: + case 1 /* TokenizerState.Param */: if (char === '(') { - state = 2 /* ParamRegExp */; + state = 2 /* TokenizerState.ParamRegExp */; } else if (VALID_PARAM_RE.test(char)) { addCharToBuffer(); } else { consumeBuffer(); - state = 0 /* Static */; + state = 0 /* TokenizerState.Static */; // go back one character if we were not modifying if (char !== '*' && char !== '?' && char !== '+') i--; } break; - case 2 /* ParamRegExp */: + case 2 /* TokenizerState.ParamRegExp */: // TODO: is it worth handling nested regexp? like :p(?:prefix_([^/]+)_suffix) // it already works by escaping the closing ) // https://paths.esm.dev/?p=AAMeJbiAwQEcDKbAoAAkP60PG2R6QAvgNaA6AFACM2ABuQBB# @@ -1192,16 +1182,16 @@ function tokenizePath(path) { if (customRe[customRe.length - 1] == '\\') customRe = customRe.slice(0, -1) + char; else - state = 3 /* ParamRegExpEnd */; + state = 3 /* TokenizerState.ParamRegExpEnd */; } else { customRe += char; } break; - case 3 /* ParamRegExpEnd */: + case 3 /* TokenizerState.ParamRegExpEnd */: // same as finalizing a param consumeBuffer(); - state = 0 /* Static */; + state = 0 /* TokenizerState.Static */; // go back one character if we were not modifying if (char !== '*' && char !== '?' && char !== '+') i--; @@ -1212,7 +1202,7 @@ function tokenizePath(path) { break; } } - if (state === 2 /* ParamRegExp */) + if (state === 2 /* TokenizerState.ParamRegExp */) crash(`Unfinished custom RegExp for param "${buffer}"`); consumeBuffer(); finalizeSegment(); @@ -1267,6 +1257,9 @@ function createRouterMatcher(routes, globalOptions) { // used later on to remove by name const isRootAdd = !originalRecord; const mainNormalizedRecord = normalizeRouteRecord(record); + { + checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent); + } // we might be the child of an alias mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record; const options = mergeOptions(globalOptions, record); @@ -1310,11 +1303,11 @@ function createRouterMatcher(routes, globalOptions) { throw new Error('Catch all routes ("*") must now be defined using a param with a custom regexp.\n' + 'See more at https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes.'); } - // create the object before hand so it can be passed to children + // create the object beforehand, so it can be passed to children matcher = createRouteRecordMatcher(normalizedRecord, parent, options); if (parent && path[0] === '/') checkMissingParamsInAbsolutePath(matcher, parent); - // if we are an alias we must tell the original record that we exist + // if we are an alias we must tell the original record that we exist, // so we can be removed if (originalRecord) { originalRecord.alias.push(matcher); @@ -1332,14 +1325,14 @@ function createRouterMatcher(routes, globalOptions) { if (isRootAdd && record.name && !isAliasRecord(matcher)) removeRoute(record.name); } - if ('children' in mainNormalizedRecord) { + if (mainNormalizedRecord.children) { const children = mainNormalizedRecord.children; for (let i = 0; i < children.length; i++) { addRoute(children[i], matcher, originalRecord && originalRecord.children[i]); } } // if there was no original record, then the first one was not an alias and all - // other alias (if any) need to reference this record when adding children + // other aliases (if any) need to reference this record when adding children originalRecord = originalRecord || matcher; // TODO: add normalized records for more flexibility // if (parent && isAliasRecord(originalRecord)) { @@ -1400,16 +1393,27 @@ function createRouterMatcher(routes, globalOptions) { if ('name' in location && location.name) { matcher = matcherMap.get(location.name); if (!matcher) - throw createRouterError(1 /* MATCHER_NOT_FOUND */, { + throw createRouterError(1 /* ErrorTypes.MATCHER_NOT_FOUND */, { location, }); + // warn if the user is passing invalid params so they can debug it better when they get removed + { + const invalidParams = Object.keys(location.params || {}).filter(paramName => !matcher.keys.find(k => k.name === paramName)); + if (invalidParams.length) { + warn(`Discarded invalid param(s) "${invalidParams.join('", "')}" when navigating. See https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22 for more details.`); + } + } name = matcher.record.name; params = assign( // paramsFromLocation is a new object paramsFromLocation(currentLocation.params, // only keep params that exist in the resolved location // TODO: only keep optional params coming from a parent record - matcher.keys.filter(k => !k.optional).map(k => k.name)), location.params); + matcher.keys.filter(k => !k.optional).map(k => k.name)), + // discard any existing params in the current location that do not exist here + // #1497 this ensures better active/exact matching + location.params && + paramsFromLocation(location.params, matcher.keys.map(k => k.name))); // throws if cannot be stringified path = matcher.stringify(params); } @@ -1423,7 +1427,6 @@ function createRouterMatcher(routes, globalOptions) { matcher = matchers.find(m => m.re.test(path)); // matcher should have a value after the loop if (matcher) { - // TODO: dev warning of unused params if provided // we know the matcher works because we tested the regexp params = matcher.parse(path); name = matcher.record.name; @@ -1436,7 +1439,7 @@ function createRouterMatcher(routes, globalOptions) { ? matcherMap.get(currentLocation.name) : matchers.find(m => m.re.test(currentLocation.path)); if (!matcher) - throw createRouterError(1 /* MATCHER_NOT_FOUND */, { + throw createRouterError(1 /* ErrorTypes.MATCHER_NOT_FOUND */, { location, currentLocation, }); @@ -1494,8 +1497,8 @@ function normalizeRouteRecord(record) { updateGuards: new Set(), enterCallbacks: {}, components: 'components' in record - ? record.components || {} - : { default: record.component }, + ? record.components || null + : record.component && { default: record.component }, }; } /** @@ -1505,7 +1508,7 @@ function normalizeRouteRecord(record) { */ function normalizeRecordProps(record) { const propsObject = {}; - // props does not exist on redirect records but we can set false directly + // props does not exist on redirect records, but we can set false directly const props = record.props || false; if ('component' in record) { propsObject.default = props; @@ -1559,17 +1562,31 @@ function isSameParam(a, b) { function checkSameParams(a, b) { for (const key of a.keys) { if (!key.optional && !b.keys.find(isSameParam.bind(null, key))) - return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`); + return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`); } for (const key of b.keys) { if (!key.optional && !a.keys.find(isSameParam.bind(null, key))) - return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`); + return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`); + } +} +/** + * A route with a name and a child with an empty path without a name should warn when adding the route + * + * @param mainNormalizedRecord - RouteRecordNormalized + * @param parent - RouteRecordMatcher + */ +function checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent) { + if (parent && + parent.record.name && + !mainNormalizedRecord.name && + !mainNormalizedRecord.path) { + warn(`The route named "${String(parent.record.name)}" has a child without a name and an empty path. Using that name won't render the empty path child so you probably want to move the name to the child instead. If this is intentional, add a name to the child route to remove the warning.`); } } function checkMissingParamsInAbsolutePath(record, parent) { for (const key of parent.keys) { if (!record.keys.find(isSameParam.bind(null, key))) - return warn(`Absolute path "${record.record.path}" should have the exact same param named "${key.name}" as its parent "${parent.record.path}".`); + return warn(`Absolute path "${record.record.path}" must have the exact same param named "${key.name}" as its parent "${parent.record.path}".`); } } function isRecordChildOf(record, parent) { @@ -1583,7 +1600,7 @@ function isRecordChildOf(record, parent) { * On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2) * defines some extra characters to be encoded. Most browsers do not encode them * in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to - * also encode `!'()*`. Leaving unencoded only ASCII alphanumeric(`a-zA-Z0-9`) + * also encode `!'()*`. Leaving un-encoded only ASCII alphanumeric(`a-zA-Z0-9`) * plus `-._~`. This extra safety should be applied to query by patching the * string returned by encodeURIComponent encodeURI also encodes `[\]^`. `\` * should be encoded to avoid ambiguity. Browsers (IE, FF, C) transform a `\` @@ -1607,7 +1624,7 @@ const PLUS_RE = /\+/g; // %2B * application/x-www-form-urlencoded * (https://url.spec.whatwg.org/#urlencoded-parsing) and most browsers seems lo * leave the plus character as is in queries. To be more flexible, we allow the - * plus character on the query but it can also be manually encoded by the user. + * plus character on the query, but it can also be manually encoded by the user. * * Resources: * - https://url.spec.whatwg.org/#urlencoded-parsing @@ -1739,7 +1756,7 @@ function parseQuery(search) { if (key in query) { // an extra variable for ts types let currentValue = query[key]; - if (!Array.isArray(currentValue)) { + if (!isArray(currentValue)) { currentValue = query[key] = [currentValue]; } currentValue.push(value); @@ -1772,7 +1789,7 @@ function stringifyQuery(query) { continue; } // keep null values - const values = Array.isArray(value) + const values = isArray(value) ? value.map(v => v && encodeQueryValue(v)) : [value && encodeQueryValue(value)]; values.forEach(value => { @@ -1801,7 +1818,7 @@ function normalizeQuery(query) { for (const key in query) { const value = query[key]; if (value !== undefined) { - normalizedQuery[key] = Array.isArray(value) + normalizedQuery[key] = isArray(value) ? value.map(v => (v == null ? null : '' + v)) : value == null ? value @@ -1811,6 +1828,43 @@ function normalizeQuery(query) { return normalizedQuery; } +/** + * RouteRecord being rendered by the closest ancestor Router View. Used for + * `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View + * Location Matched + * + * @internal + */ +const matchedRouteKey = Symbol('router view location matched' ); +/** + * Allows overriding the router view depth to control which component in + * `matched` is rendered. rvd stands for Router View Depth + * + * @internal + */ +const viewDepthKey = Symbol('router view depth' ); +/** + * Allows overriding the router instance returned by `useRouter` in tests. r + * stands for router + * + * @internal + */ +const routerKey = Symbol('router' ); +/** + * Allows overriding the current route returned by `useRoute` in tests. rl + * stands for route location + * + * @internal + */ +const routeLocationKey = Symbol('route location' ); +/** + * Allows overriding the current route used by router-view. Internally this is + * used when the `route` prop is passed. + * + * @internal + */ +const routerViewLocationKey = Symbol('router view location' ); + /** * Create a list of callbacks that can be reset. Used to create before and after navigation guards list */ @@ -1861,7 +1915,7 @@ function onBeforeRouteLeave(leaveGuard) { // to avoid warning {}).value; if (!activeRecord) { - warn('No active route record was found when calling `onBeforeRouteLeave()`. Make sure you call this function inside of a component child of . Maybe you called it inside of App.vue?'); + warn('No active route record was found when calling `onBeforeRouteLeave()`. Make sure you call this function inside a component child of . Maybe you called it inside of App.vue?'); return; } registerGuard(activeRecord, 'leaveGuards', leaveGuard); @@ -1882,7 +1936,7 @@ function onBeforeRouteUpdate(updateGuard) { // to avoid warning {}).value; if (!activeRecord) { - warn('No active route record was found when calling `onBeforeRouteUpdate()`. Make sure you call this function inside of a component child of . Maybe you called it inside of App.vue?'); + warn('No active route record was found when calling `onBeforeRouteUpdate()`. Make sure you call this function inside a component child of . Maybe you called it inside of App.vue?'); return; } registerGuard(activeRecord, 'updateGuards', updateGuard); @@ -1894,16 +1948,17 @@ function guardToPromiseFn(guard, to, from, record, name) { (record.enterCallbacks[name] = record.enterCallbacks[name] || []); return () => new Promise((resolve, reject) => { const next = (valid) => { - if (valid === false) - reject(createRouterError(4 /* NAVIGATION_ABORTED */, { + if (valid === false) { + reject(createRouterError(4 /* ErrorTypes.NAVIGATION_ABORTED */, { from, to, })); + } else if (valid instanceof Error) { reject(valid); } else if (isRouteLocation(valid)) { - reject(createRouterError(2 /* NAVIGATION_GUARD_REDIRECT */, { + reject(createRouterError(2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */, { from: to, to: valid, })); @@ -1912,8 +1967,9 @@ function guardToPromiseFn(guard, to, from, record, name) { if (enterCallbackArray && // since enterCallbackArray is truthy, both record and name also are record.enterCallbacks[name] === enterCallbackArray && - typeof valid === 'function') + typeof valid === 'function') { enterCallbackArray.push(valid); + } resolve(); } }; @@ -1933,7 +1989,6 @@ function guardToPromiseFn(guard, to, from, record, name) { } return resolvedValue; }); - // TODO: test me! } else if (guardReturn !== undefined) { // @ts-expect-error: _called is added at canOnlyBeCalledOnce @@ -1961,6 +2016,10 @@ function canOnlyBeCalledOnce(next, to, from) { function extractComponentsGuards(matched, guardType, to, from) { const guards = []; for (const record of matched) { + if (!record.components && !record.children.length) { + warn(`Record with path "${record.path}" is either missing a "component(s)"` + + ` or "children" property.`); + } for (const name in record.components) { let rawComponent = record.components[name]; { @@ -2017,6 +2076,7 @@ function extractComponentsGuards(matched, guardType, to, from) { ? resolved.default : resolved; // replace the function with the resolved component + // cannot be null or undefined because we went into the for loop record.components[name] = resolvedComponent; // __vccOpts is added by vue-class-component and contain the regular options const options = resolvedComponent.__vccOpts || resolvedComponent; @@ -2030,6 +2090,7 @@ function extractComponentsGuards(matched, guardType, to, from) { } /** * Allows differentiating lazy components from functional components and vue-class-component + * @internal * * @param component */ @@ -2039,6 +2100,34 @@ function isRouteComponent(component) { 'props' in component || '__vccOpts' in component); } +/** + * Ensures a route is loaded, so it can be passed as o prop to ``. + * + * @param route - resolved route to load + */ +function loadRouteLocation(route) { + return route.matched.every(record => record.redirect) + ? Promise.reject(new Error('Cannot load a route that redirects.')) + : Promise.all(route.matched.map(record => record.components && + Promise.all(Object.keys(record.components).reduce((promises, name) => { + const rawComponent = record.components[name]; + if (typeof rawComponent === 'function' && + !('displayName' in rawComponent)) { + promises.push(rawComponent().then(resolved => { + if (!resolved) + return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}". Ensure you passed a function that returns a promise.`)); + const resolvedComponent = isESModule(resolved) + ? resolved.default + : resolved; + // replace the function with the resolved component + // cannot be null or undefined because we went into the for loop + record.components[name] = resolvedComponent; + return; + })); + } + return promises; + }, [])))).then(() => route); +} // TODO: we could allow currentRoute as a prop to expose `isActive` and // `isExactActive` behavior should go through an RFC @@ -2113,6 +2202,7 @@ function useLink(props) { } const RouterLinkImpl = /*#__PURE__*/ defineComponent({ name: 'RouterLink', + compatConfig: { MODE: 3 }, props: { to: { type: [String, Object], @@ -2151,7 +2241,7 @@ const RouterLinkImpl = /*#__PURE__*/ defineComponent({ : null, href: link.href, // this would override user added attrs but Vue will still add - // the listener so we end up triggering both + // the listener, so we end up triggering both onClick: link.navigate, class: elClass.value, }, children); @@ -2196,7 +2286,7 @@ function includesParams(outer, inner) { return false; } else { - if (!Array.isArray(outerValue) || + if (!isArray(outerValue) || outerValue.length !== innerValue.length || innerValue.some((value, i) => value !== outerValue[i])) return false; @@ -2241,9 +2331,21 @@ const RouterViewImpl = /*#__PURE__*/ defineComponent({ warnDeprecatedUsage(); const injectedRoute = inject(routerViewLocationKey); const routeToDisplay = computed(() => props.route || injectedRoute.value); - const depth = inject(viewDepthKey, 0); - const matchedRouteRef = computed(() => routeToDisplay.value.matched[depth]); - provide(viewDepthKey, depth + 1); + const injectedDepth = inject(viewDepthKey, 0); + // The depth changes based on empty components option, which allows passthrough routes e.g. routes with children + // that are used to reuse the `path` property + const depth = computed(() => { + let initialDepth = unref(injectedDepth); + const { matched } = routeToDisplay.value; + let matchedRoute; + while ((matchedRoute = matched[initialDepth]) && + !matchedRoute.components) { + initialDepth++; + } + return initialDepth; + }); + const matchedRouteRef = computed(() => routeToDisplay.value.matched[depth.value]); + provide(viewDepthKey, computed(() => depth.value + 1)); provide(matchedRouteKey, matchedRouteRef); provide(routerViewLocationKey, routeToDisplay); const viewRef = ref(); @@ -2255,7 +2357,7 @@ const RouterViewImpl = /*#__PURE__*/ defineComponent({ // this will update the instance for new instances as well as reused // instances when navigating to a new route to.instances[name] = instance; - // the component instance is reused for a different route or name so + // the component instance is reused for a different route or name, so // we copy any saved update or leave guards. With async setup, the // mounting component will mount before the matchedRoute changes, // making instance === oldInstance, so we check if guards have been @@ -2281,16 +2383,16 @@ const RouterViewImpl = /*#__PURE__*/ defineComponent({ }, { flush: 'post' }); return () => { const route = routeToDisplay.value; - const matchedRoute = matchedRouteRef.value; - const ViewComponent = matchedRoute && matchedRoute.components[props.name]; // we need the value at the time we render because when we unmount, we // navigated to a different location so the value is different const currentName = props.name; + const matchedRoute = matchedRouteRef.value; + const ViewComponent = matchedRoute && matchedRoute.components[currentName]; if (!ViewComponent) { return normalizeSlot(slots.default, { Component: ViewComponent, route }); } // props from route configuration - const routePropsOption = matchedRoute.props[props.name]; + const routePropsOption = matchedRoute.props[currentName]; const routeProps = routePropsOption ? routePropsOption === true ? route.params @@ -2312,12 +2414,12 @@ const RouterViewImpl = /*#__PURE__*/ defineComponent({ component.ref) { // TODO: can display if it's an alias, its props const info = { - depth, + depth: depth.value, name: matchedRoute.name, path: matchedRoute.path, meta: matchedRoute.meta, }; - const internalInstances = Array.isArray(component.ref) + const internalInstances = isArray(component.ref) ? component.ref.map(r => r.i) : [component.ref.i]; internalInstances.forEach(instance => { @@ -2363,6 +2465,13 @@ function warnDeprecatedUsage() { } } +/** + * Copies a route location and removes any problematic properties that cannot be shown in devtools (e.g. Vue instances). + * + * @param routeLocation - routeLocation to format + * @param tooltip - optional tooltip + * @returns a copy of the routeLocation + */ function formatRouteLocation(routeLocation, tooltip) { const copy = assign({}, routeLocation, { // remove variables that can contain vue instances @@ -2404,6 +2513,9 @@ function addDevtools(app, router, matcher) { componentStateTypes: ['Routing'], app, }, api => { + if (typeof api.now !== 'function') { + console.warn('[Vue Router]: You seem to be using an outdated version of Vue Devtools. Are you still using the Beta release instead of the stable one? You can find the links at https://devtools.vuejs.org/guide/installation.html.'); + } // display state added by the router api.on.inspectComponent((payload, ctx) => { if (payload.instanceData) { @@ -2427,7 +2539,7 @@ function addDevtools(app, router, matcher) { }); } // if multiple useLink are used - if (Array.isArray(componentInstance.__vrl_devtools)) { + if (isArray(componentInstance.__vrl_devtools)) { componentInstance.__devtoolsApi = api; componentInstance.__vrl_devtools.forEach(devtoolsData => { let backgroundColor = ORANGE_400; @@ -2644,6 +2756,13 @@ function formatRouteRecordMatcherForStateInspector(route) { value: route.alias.map(alias => alias.record.path), }); } + if (Object.keys(route.record.meta).length) { + fields.push({ + editable: false, + key: 'meta', + value: route.record.meta, + }); + } fields.push({ key: 'score', editable: false, @@ -2709,8 +2828,9 @@ function formatRouteRecordForInspector(route) { } if (record.redirect) { tags.push({ - label: 'redirect: ' + - (typeof record.redirect === 'string' ? record.redirect : 'Object'), + label: typeof record.redirect === 'string' + ? `redirect: ${record.redirect}` + : 'redirects', textColor: 0xffffff, backgroundColor: DARK, }); @@ -2889,7 +3009,7 @@ function createRouter(options) { delete targetParams[key]; } } - // pass encoded values to the matcher so it can produce encoded path and fullPath + // pass encoded values to the matcher, so it can produce encoded path and fullPath matcherLocation = assign({}, rawLocation, { params: encodeParams(rawLocation.params), }); @@ -2902,7 +3022,7 @@ function createRouter(options) { if (hash && !hash.startsWith('#')) { warn(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`); } - // decoding them) the matcher might have merged current location params so + // the matcher might have merged current location params, so // we need to run the decoding again matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params)); const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, { @@ -2944,7 +3064,7 @@ function createRouter(options) { } function checkCanceledNavigation(to, from) { if (pendingLocation !== to) { - return createRouterError(8 /* NAVIGATION_CANCELLED */, { + return createRouterError(8 /* ErrorTypes.NAVIGATION_CANCELLED */, { from, to, }); @@ -2979,7 +3099,8 @@ function createRouter(options) { return assign({ query: to.query, hash: to.hash, - params: to.params, + // avoid transferring params if the redirect has a path + params: 'path' in newTargetLocation ? {} : to.params, }, newTargetLocation); } } @@ -2993,7 +3114,9 @@ function createRouter(options) { const shouldRedirect = handleRedirectRecord(targetLocation); if (shouldRedirect) return pushWithRedirect(assign(locationAsObject(shouldRedirect), { - state: data, + state: typeof shouldRedirect === 'object' + ? assign({}, data, shouldRedirect.state) + : data, force, replace, }), @@ -3004,7 +3127,7 @@ function createRouter(options) { toLocation.redirectedFrom = redirectedFrom; let failure; if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) { - failure = createRouterError(16 /* NAVIGATION_DUPLICATED */, { to: toLocation, from }); + failure = createRouterError(16 /* ErrorTypes.NAVIGATION_DUPLICATED */, { to: toLocation, from }); // trigger scroll to allow scrolling to the same anchor handleScroll(from, from, // this is a push, the only way for it to be triggered from a @@ -3017,14 +3140,14 @@ function createRouter(options) { return (failure ? Promise.resolve(failure) : navigate(toLocation, from)) .catch((error) => isNavigationFailure(error) ? // navigation redirects still mark the router as ready - isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */) + isNavigationFailure(error, 2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */) ? error : markAsReady(error) // also returns the error : // reject any unknown error triggerError(error, toLocation, from)) .then((failure) => { if (failure) { - if (isNavigationFailure(failure, 2 /* NAVIGATION_GUARD_REDIRECT */)) { + if (isNavigationFailure(failure, 2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */)) { if (// we are redirecting to the same location we were already at isSameRouteLocation(stringifyQuery$1, resolve(failure.to), toLocation) && // and we have done it a couple of times @@ -3039,10 +3162,14 @@ function createRouter(options) { } return pushWithRedirect( // keep options - assign(locationAsObject(failure.to), { - state: data, - force, + assign({ + // preserve an existing replacement but allow the redirect to override it replace, + }, locationAsObject(failure.to), { + state: typeof failure.to === 'object' + ? assign({}, data, failure.to.state) + : data, + force, }), // preserve the original redirectedFrom if any redirectedFrom || toLocation); @@ -3108,7 +3235,7 @@ function createRouter(options) { for (const record of to.matched) { // do not trigger beforeEnter on reused views if (record.beforeEnter && !from.matched.includes(record)) { - if (Array.isArray(record.beforeEnter)) { + if (isArray(record.beforeEnter)) { for (const beforeEnter of record.beforeEnter) guards.push(guardToPromiseFn(beforeEnter, to, from)); } @@ -3141,7 +3268,7 @@ function createRouter(options) { return runGuardQueue(guards); }) // catch any navigation canceled - .catch(err => isNavigationFailure(err, 8 /* NAVIGATION_CANCELLED */) + .catch(err => isNavigationFailure(err, 8 /* ErrorTypes.NAVIGATION_CANCELLED */) ? err : Promise.reject(err))); } @@ -3188,6 +3315,8 @@ function createRouter(options) { if (removeHistoryListener) return; removeHistoryListener = routerHistory.listen((to, _from, info) => { + if (!router.listening) + return; // cannot be a redirect route because it was in history const toLocation = resolve(to); // due to dynamic routing, and to hash history with manual navigation @@ -3206,15 +3335,15 @@ function createRouter(options) { } navigate(toLocation, from) .catch((error) => { - if (isNavigationFailure(error, 4 /* NAVIGATION_ABORTED */ | 8 /* NAVIGATION_CANCELLED */)) { + if (isNavigationFailure(error, 4 /* ErrorTypes.NAVIGATION_ABORTED */ | 8 /* ErrorTypes.NAVIGATION_CANCELLED */)) { return error; } - if (isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */)) { + if (isNavigationFailure(error, 2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */)) { // Here we could call if (info.delta) routerHistory.go(-info.delta, // false) but this is bug prone as we have no way to wait the // navigation to be finished before calling pushWithRedirect. Using - // a setTimeout of 16ms seems to work but there is not guarantee for - // it to work on every browser. So Instead we do not restore the + // a setTimeout of 16ms seems to work but there is no guarantee for + // it to work on every browser. So instead we do not restore the // history entry and trigger a new navigation as requested by the // navigation guard. // the error is already handled by router.push we just want to avoid @@ -3224,10 +3353,10 @@ function createRouter(options) { ) .then(failure => { // manual change in hash history #916 ending up in the URL not - // changing but it was changed by the manual url change, so we + // changing, but it was changed by the manual url change, so we // need to manually change it ourselves - if (isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ | - 16 /* NAVIGATION_DUPLICATED */) && + if (isNavigationFailure(failure, 4 /* ErrorTypes.NAVIGATION_ABORTED */ | + 16 /* ErrorTypes.NAVIGATION_DUPLICATED */) && !info.delta && info.type === NavigationType.pop) { routerHistory.go(-1, false); @@ -3238,8 +3367,9 @@ function createRouter(options) { return Promise.reject(); } // do not restore history on unknown direction - if (info.delta) + if (info.delta) { routerHistory.go(-info.delta, false); + } // unrecognized error, transfer to the global handler return triggerError(error, toLocation, from); }) @@ -3251,11 +3381,14 @@ function createRouter(options) { toLocation, from, false); // revert the navigation if (failure) { - if (info.delta) { + if (info.delta && + // a new navigation has been triggered, so we do not want to revert, that will change the current history + // entry while a different route is displayed + !isNavigationFailure(failure, 8 /* ErrorTypes.NAVIGATION_CANCELLED */)) { routerHistory.go(-info.delta, false); } else if (info.type === NavigationType.pop && - isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ | 16 /* NAVIGATION_DUPLICATED */)) { + isNavigationFailure(failure, 4 /* ErrorTypes.NAVIGATION_ABORTED */ | 16 /* ErrorTypes.NAVIGATION_DUPLICATED */)) { // manual change in hash history #916 // it's like a push but lacks the information of the direction routerHistory.go(-1, false); @@ -3331,6 +3464,7 @@ function createRouter(options) { const installedApps = new Set(); const router = { currentRoute, + listening: true, addRoute, removeRoute, hasRoute, @@ -3394,6 +3528,7 @@ function createRouter(options) { } unmountApp(); }; + // TODO: this probably needs to be updated so it can be used by vue-termui if (isBrowser) { addDevtools(app, router, matcher); } @@ -3443,4 +3578,4 @@ function useRoute() { return inject(routeLocationKey); } -export { NavigationFailureType, RouterLink, RouterView, START_LOCATION_NORMALIZED as START_LOCATION, createMemoryHistory, createRouter, createRouterMatcher, createWebHashHistory, createWebHistory, isNavigationFailure, matchedRouteKey, onBeforeRouteLeave, onBeforeRouteUpdate, parseQuery, routeLocationKey, routerKey, routerViewLocationKey, stringifyQuery, useLink, useRoute, useRouter, viewDepthKey }; +export { NavigationFailureType, RouterLink, RouterView, START_LOCATION_NORMALIZED as START_LOCATION, createMemoryHistory, createRouter, createRouterMatcher, createWebHashHistory, createWebHistory, isNavigationFailure, loadRouteLocation, matchedRouteKey, onBeforeRouteLeave, onBeforeRouteUpdate, parseQuery, routeLocationKey, routerKey, routerViewLocationKey, stringifyQuery, useLink, useRoute, useRouter, viewDepthKey }; diff --git a/node_modules/vue-router/dist/vue-router.esm-bundler.js b/node_modules/vue-router/dist/vue-router.esm-bundler.js index 83dc36c..78c61c2 100644 --- a/node_modules/vue-router/dist/vue-router.esm-bundler.js +++ b/node_modules/vue-router/dist/vue-router.esm-bundler.js @@ -1,3464 +1 @@ -/*! - * vue-router v4.0.15 - * (c) 2022 Eduardo San Martin Morote - * @license MIT - */ -import { getCurrentInstance, inject, onUnmounted, onDeactivated, onActivated, computed, unref, watchEffect, defineComponent, reactive, h, provide, ref, watch, shallowRef, nextTick } from 'vue'; -import { setupDevtoolsPlugin } from '@vue/devtools-api'; - -const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -const PolySymbol = (name) => -// vr = vue router -hasSymbol - ? Symbol((process.env.NODE_ENV !== 'production') ? '[vue-router]: ' + name : name) - : ((process.env.NODE_ENV !== 'production') ? '[vue-router]: ' : '_vr_') + name; -// rvlm = Router View Location Matched -/** - * RouteRecord being rendered by the closest ancestor Router View. Used for - * `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View - * Location Matched - * - * @internal - */ -const matchedRouteKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'router view location matched' : 'rvlm'); -/** - * Allows overriding the router view depth to control which component in - * `matched` is rendered. rvd stands for Router View Depth - * - * @internal - */ -const viewDepthKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'router view depth' : 'rvd'); -/** - * Allows overriding the router instance returned by `useRouter` in tests. r - * stands for router - * - * @internal - */ -const routerKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'router' : 'r'); -/** - * Allows overriding the current route returned by `useRoute` in tests. rl - * stands for route location - * - * @internal - */ -const routeLocationKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'route location' : 'rl'); -/** - * Allows overriding the current route used by router-view. Internally this is - * used when the `route` prop is passed. - * - * @internal - */ -const routerViewLocationKey = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'router view location' : 'rvl'); - -const isBrowser = typeof window !== 'undefined'; - -function isESModule(obj) { - return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module'); -} -const assign = Object.assign; -function applyToParams(fn, params) { - const newParams = {}; - for (const key in params) { - const value = params[key]; - newParams[key] = Array.isArray(value) ? value.map(fn) : fn(value); - } - return newParams; -} -const noop = () => { }; - -function warn(msg) { - // avoid using ...args as it breaks in older Edge builds - const args = Array.from(arguments).slice(1); - console.warn.apply(console, ['[Vue Router warn]: ' + msg].concat(args)); -} - -const TRAILING_SLASH_RE = /\/$/; -const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, ''); -/** - * Transforms an URI into a normalized history location - * - * @param parseQuery - * @param location - URI to normalize - * @param currentLocation - current absolute location. Allows resolving relative - * paths. Must start with `/`. Defaults to `/` - * @returns a normalized history location - */ -function parseURL(parseQuery, location, currentLocation = '/') { - let path, query = {}, searchString = '', hash = ''; - // Could use URL and URLSearchParams but IE 11 doesn't support it - const searchPos = location.indexOf('?'); - const hashPos = location.indexOf('#', searchPos > -1 ? searchPos : 0); - if (searchPos > -1) { - path = location.slice(0, searchPos); - searchString = location.slice(searchPos + 1, hashPos > -1 ? hashPos : location.length); - query = parseQuery(searchString); - } - if (hashPos > -1) { - path = path || location.slice(0, hashPos); - // keep the # character - hash = location.slice(hashPos, location.length); - } - // no search and no query - path = resolveRelativePath(path != null ? path : location, currentLocation); - // empty path means a relative query or hash `?foo=f`, `#thing` - return { - fullPath: path + (searchString && '?') + searchString + hash, - path, - query, - hash, - }; -} -/** - * Stringifies a URL object - * - * @param stringifyQuery - * @param location - */ -function stringifyURL(stringifyQuery, location) { - const query = location.query ? stringifyQuery(location.query) : ''; - return location.path + (query && '?') + query + (location.hash || ''); -} -/** - * Strips off the base from the beginning of a location.pathname in a non - * case-sensitive way. - * - * @param pathname - location.pathname - * @param base - base to strip off - */ -function stripBase(pathname, base) { - // no base or base is not found at the beginning - if (!base || !pathname.toLowerCase().startsWith(base.toLowerCase())) - return pathname; - return pathname.slice(base.length) || '/'; -} -/** - * Checks if two RouteLocation are equal. This means that both locations are - * pointing towards the same {@link RouteRecord} and that all `params`, `query` - * parameters and `hash` are the same - * - * @param a - first {@link RouteLocation} - * @param b - second {@link RouteLocation} - */ -function isSameRouteLocation(stringifyQuery, a, b) { - const aLastIndex = a.matched.length - 1; - const bLastIndex = b.matched.length - 1; - return (aLastIndex > -1 && - aLastIndex === bLastIndex && - isSameRouteRecord(a.matched[aLastIndex], b.matched[bLastIndex]) && - isSameRouteLocationParams(a.params, b.params) && - stringifyQuery(a.query) === stringifyQuery(b.query) && - a.hash === b.hash); -} -/** - * Check if two `RouteRecords` are equal. Takes into account aliases: they are - * considered equal to the `RouteRecord` they are aliasing. - * - * @param a - first {@link RouteRecord} - * @param b - second {@link RouteRecord} - */ -function isSameRouteRecord(a, b) { - // since the original record has an undefined value for aliasOf - // but all aliases point to the original record, this will always compare - // the original record - return (a.aliasOf || a) === (b.aliasOf || b); -} -function isSameRouteLocationParams(a, b) { - if (Object.keys(a).length !== Object.keys(b).length) - return false; - for (const key in a) { - if (!isSameRouteLocationParamsValue(a[key], b[key])) - return false; - } - return true; -} -function isSameRouteLocationParamsValue(a, b) { - return Array.isArray(a) - ? isEquivalentArray(a, b) - : Array.isArray(b) - ? isEquivalentArray(b, a) - : a === b; -} -/** - * Check if two arrays are the same or if an array with one single entry is the - * same as another primitive value. Used to check query and parameters - * - * @param a - array of values - * @param b - array of values or a single value - */ -function isEquivalentArray(a, b) { - return Array.isArray(b) - ? a.length === b.length && a.every((value, i) => value === b[i]) - : a.length === 1 && a[0] === b; -} -/** - * Resolves a relative path that starts with `.`. - * - * @param to - path location we are resolving - * @param from - currentLocation.path, should start with `/` - */ -function resolveRelativePath(to, from) { - if (to.startsWith('/')) - return to; - if ((process.env.NODE_ENV !== 'production') && !from.startsWith('/')) { - warn(`Cannot resolve a relative location without an absolute path. Trying to resolve "${to}" from "${from}". It should look like "/${from}".`); - return to; - } - if (!to) - return from; - const fromSegments = from.split('/'); - const toSegments = to.split('/'); - let position = fromSegments.length - 1; - let toPosition; - let segment; - for (toPosition = 0; toPosition < toSegments.length; toPosition++) { - segment = toSegments[toPosition]; - // can't go below zero - if (position === 1 || segment === '.') - continue; - if (segment === '..') - position--; - // found something that is not relative path - else - break; - } - return (fromSegments.slice(0, position).join('/') + - '/' + - toSegments - .slice(toPosition - (toPosition === toSegments.length ? 1 : 0)) - .join('/')); -} - -var NavigationType; -(function (NavigationType) { - NavigationType["pop"] = "pop"; - NavigationType["push"] = "push"; -})(NavigationType || (NavigationType = {})); -var NavigationDirection; -(function (NavigationDirection) { - NavigationDirection["back"] = "back"; - NavigationDirection["forward"] = "forward"; - NavigationDirection["unknown"] = ""; -})(NavigationDirection || (NavigationDirection = {})); -/** - * Starting location for Histories - */ -const START = ''; -// Generic utils -/** - * Normalizes a base by removing any trailing slash and reading the base tag if - * present. - * - * @param base - base to normalize - */ -function normalizeBase(base) { - if (!base) { - if (isBrowser) { - // respect tag - const baseEl = document.querySelector('base'); - base = (baseEl && baseEl.getAttribute('href')) || '/'; - // strip full URL origin - base = base.replace(/^\w+:\/\/[^\/]+/, ''); - } - else { - base = '/'; - } - } - // ensure leading slash when it was removed by the regex above avoid leading - // slash with hash because the file could be read from the disk like file:// - // and the leading slash would cause problems - if (base[0] !== '/' && base[0] !== '#') - base = '/' + base; - // remove the trailing slash so all other method can just do `base + fullPath` - // to build an href - return removeTrailingSlash(base); -} -// remove any character before the hash -const BEFORE_HASH_RE = /^[^#]+#/; -function createHref(base, location) { - return base.replace(BEFORE_HASH_RE, '#') + location; -} - -function getElementPosition(el, offset) { - const docRect = document.documentElement.getBoundingClientRect(); - const elRect = el.getBoundingClientRect(); - return { - behavior: offset.behavior, - left: elRect.left - docRect.left - (offset.left || 0), - top: elRect.top - docRect.top - (offset.top || 0), - }; -} -const computeScrollPosition = () => ({ - left: window.pageXOffset, - top: window.pageYOffset, -}); -function scrollToPosition(position) { - let scrollToOptions; - if ('el' in position) { - const positionEl = position.el; - const isIdSelector = typeof positionEl === 'string' && positionEl.startsWith('#'); - /** - * `id`s can accept pretty much any characters, including CSS combinators - * like `>` or `~`. It's still possible to retrieve elements using - * `document.getElementById('~')` but it needs to be escaped when using - * `document.querySelector('#\\~')` for it to be valid. The only - * requirements for `id`s are them to be unique on the page and to not be - * empty (`id=""`). Because of that, when passing an id selector, it should - * be properly escaped for it to work with `querySelector`. We could check - * for the id selector to be simple (no CSS combinators `+ >~`) but that - * would make things inconsistent since they are valid characters for an - * `id` but would need to be escaped when using `querySelector`, breaking - * their usage and ending up in no selector returned. Selectors need to be - * escaped: - * - * - `#1-thing` becomes `#\31 -thing` - * - `#with~symbols` becomes `#with\\~symbols` - * - * - More information about the topic can be found at - * https://mathiasbynens.be/notes/html5-id-class. - * - Practical example: https://mathiasbynens.be/demo/html5-id - */ - if ((process.env.NODE_ENV !== 'production') && typeof position.el === 'string') { - if (!isIdSelector || !document.getElementById(position.el.slice(1))) { - try { - const foundEl = document.querySelector(position.el); - if (isIdSelector && foundEl) { - warn(`The selector "${position.el}" should be passed as "el: document.querySelector('${position.el}')" because it starts with "#".`); - // return to avoid other warnings - return; - } - } - catch (err) { - warn(`The selector "${position.el}" is invalid. If you are using an id selector, make sure to escape it. You can find more information about escaping characters in selectors at https://mathiasbynens.be/notes/css-escapes or use CSS.escape (https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape).`); - // return to avoid other warnings - return; - } - } - } - const el = typeof positionEl === 'string' - ? isIdSelector - ? document.getElementById(positionEl.slice(1)) - : document.querySelector(positionEl) - : positionEl; - if (!el) { - (process.env.NODE_ENV !== 'production') && - warn(`Couldn't find element using selector "${position.el}" returned by scrollBehavior.`); - return; - } - scrollToOptions = getElementPosition(el, position); - } - else { - scrollToOptions = position; - } - if ('scrollBehavior' in document.documentElement.style) - window.scrollTo(scrollToOptions); - else { - window.scrollTo(scrollToOptions.left != null ? scrollToOptions.left : window.pageXOffset, scrollToOptions.top != null ? scrollToOptions.top : window.pageYOffset); - } -} -function getScrollKey(path, delta) { - const position = history.state ? history.state.position - delta : -1; - return position + path; -} -const scrollPositions = new Map(); -function saveScrollPosition(key, scrollPosition) { - scrollPositions.set(key, scrollPosition); -} -function getSavedScrollPosition(key) { - const scroll = scrollPositions.get(key); - // consume it so it's not used again - scrollPositions.delete(key); - return scroll; -} -// TODO: RFC about how to save scroll position -/** - * ScrollBehavior instance used by the router to compute and restore the scroll - * position when navigating. - */ -// export interface ScrollHandler { -// // returns a scroll position that can be saved in history -// compute(): ScrollPositionEntry -// // can take an extended ScrollPositionEntry -// scroll(position: ScrollPosition): void -// } -// export const scrollHandler: ScrollHandler = { -// compute: computeScroll, -// scroll: scrollToPosition, -// } - -let createBaseLocation = () => location.protocol + '//' + location.host; -/** - * Creates a normalized history location from a window.location object - * @param location - - */ -function createCurrentLocation(base, location) { - const { pathname, search, hash } = location; - // allows hash bases like #, /#, #/, #!, #!/, /#!/, or even /folder#end - const hashPos = base.indexOf('#'); - if (hashPos > -1) { - let slicePos = hash.includes(base.slice(hashPos)) - ? base.slice(hashPos).length - : 1; - let pathFromHash = hash.slice(slicePos); - // prepend the starting slash to hash so the url starts with /# - if (pathFromHash[0] !== '/') - pathFromHash = '/' + pathFromHash; - return stripBase(pathFromHash, ''); - } - const path = stripBase(pathname, base); - return path + search + hash; -} -function useHistoryListeners(base, historyState, currentLocation, replace) { - let listeners = []; - let teardowns = []; - // TODO: should it be a stack? a Dict. Check if the popstate listener - // can trigger twice - let pauseState = null; - const popStateHandler = ({ state, }) => { - const to = createCurrentLocation(base, location); - const from = currentLocation.value; - const fromState = historyState.value; - let delta = 0; - if (state) { - currentLocation.value = to; - historyState.value = state; - // ignore the popstate and reset the pauseState - if (pauseState && pauseState === from) { - pauseState = null; - return; - } - delta = fromState ? state.position - fromState.position : 0; - } - else { - replace(to); - } - // console.log({ deltaFromCurrent }) - // Here we could also revert the navigation by calling history.go(-delta) - // this listener will have to be adapted to not trigger again and to wait for the url - // to be updated before triggering the listeners. Some kind of validation function would also - // need to be passed to the listeners so the navigation can be accepted - // call all listeners - listeners.forEach(listener => { - listener(currentLocation.value, from, { - delta, - type: NavigationType.pop, - direction: delta - ? delta > 0 - ? NavigationDirection.forward - : NavigationDirection.back - : NavigationDirection.unknown, - }); - }); - }; - function pauseListeners() { - pauseState = currentLocation.value; - } - function listen(callback) { - // setup the listener and prepare teardown callbacks - listeners.push(callback); - const teardown = () => { - const index = listeners.indexOf(callback); - if (index > -1) - listeners.splice(index, 1); - }; - teardowns.push(teardown); - return teardown; - } - function beforeUnloadListener() { - const { history } = window; - if (!history.state) - return; - history.replaceState(assign({}, history.state, { scroll: computeScrollPosition() }), ''); - } - function destroy() { - for (const teardown of teardowns) - teardown(); - teardowns = []; - window.removeEventListener('popstate', popStateHandler); - window.removeEventListener('beforeunload', beforeUnloadListener); - } - // setup the listeners and prepare teardown callbacks - window.addEventListener('popstate', popStateHandler); - window.addEventListener('beforeunload', beforeUnloadListener); - return { - pauseListeners, - listen, - destroy, - }; -} -/** - * Creates a state object - */ -function buildState(back, current, forward, replaced = false, computeScroll = false) { - return { - back, - current, - forward, - replaced, - position: window.history.length, - scroll: computeScroll ? computeScrollPosition() : null, - }; -} -function useHistoryStateNavigation(base) { - const { history, location } = window; - // private variables - const currentLocation = { - value: createCurrentLocation(base, location), - }; - const historyState = { value: history.state }; - // build current history entry as this is a fresh navigation - if (!historyState.value) { - changeLocation(currentLocation.value, { - back: null, - current: currentLocation.value, - forward: null, - // the length is off by one, we need to decrease it - position: history.length - 1, - replaced: true, - // don't add a scroll as the user may have an anchor and we want - // scrollBehavior to be triggered without a saved position - scroll: null, - }, true); - } - function changeLocation(to, state, replace) { - /** - * if a base tag is provided and we are on a normal domain, we have to - * respect the provided `base` attribute because pushState() will use it and - * potentially erase anything before the `#` like at - * https://github.com/vuejs/router/issues/685 where a base of - * `/folder/#` but a base of `/` would erase the `/folder/` section. If - * there is no host, the `` tag makes no sense and if there isn't a - * base tag we can just use everything after the `#`. - */ - const hashIndex = base.indexOf('#'); - const url = hashIndex > -1 - ? (location.host && document.querySelector('base') - ? base - : base.slice(hashIndex)) + to - : createBaseLocation() + base + to; - try { - // BROWSER QUIRK - // NOTE: Safari throws a SecurityError when calling this function 100 times in 30 seconds - history[replace ? 'replaceState' : 'pushState'](state, '', url); - historyState.value = state; - } - catch (err) { - if ((process.env.NODE_ENV !== 'production')) { - warn('Error with push/replace State', err); - } - else { - console.error(err); - } - // Force the navigation, this also resets the call count - location[replace ? 'replace' : 'assign'](url); - } - } - function replace(to, data) { - const state = assign({}, history.state, buildState(historyState.value.back, - // keep back and forward entries but override current position - to, historyState.value.forward, true), data, { position: historyState.value.position }); - changeLocation(to, state, true); - currentLocation.value = to; - } - function push(to, data) { - // Add to current entry the information of where we are going - // as well as saving the current position - const currentState = assign({}, - // use current history state to gracefully handle a wrong call to - // history.replaceState - // https://github.com/vuejs/router/issues/366 - historyState.value, history.state, { - forward: to, - scroll: computeScrollPosition(), - }); - if ((process.env.NODE_ENV !== 'production') && !history.state) { - warn(`history.state seems to have been manually replaced without preserving the necessary values. Make sure to preserve existing history state if you are manually calling history.replaceState:\n\n` + - `history.replaceState(history.state, '', url)\n\n` + - `You can find more information at https://next.router.vuejs.org/guide/migration/#usage-of-history-state.`); - } - changeLocation(currentState.current, currentState, true); - const state = assign({}, buildState(currentLocation.value, to, null), { position: currentState.position + 1 }, data); - changeLocation(to, state, false); - currentLocation.value = to; - } - return { - location: currentLocation, - state: historyState, - push, - replace, - }; -} -/** - * Creates an HTML5 history. Most common history for single page applications. - * - * @param base - - */ -function createWebHistory(base) { - base = normalizeBase(base); - const historyNavigation = useHistoryStateNavigation(base); - const historyListeners = useHistoryListeners(base, historyNavigation.state, historyNavigation.location, historyNavigation.replace); - function go(delta, triggerListeners = true) { - if (!triggerListeners) - historyListeners.pauseListeners(); - history.go(delta); - } - const routerHistory = assign({ - // it's overridden right after - location: '', - base, - go, - createHref: createHref.bind(null, base), - }, historyNavigation, historyListeners); - Object.defineProperty(routerHistory, 'location', { - enumerable: true, - get: () => historyNavigation.location.value, - }); - Object.defineProperty(routerHistory, 'state', { - enumerable: true, - get: () => historyNavigation.state.value, - }); - return routerHistory; -} - -/** - * Creates a in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere. - * It's up to the user to replace that location with the starter location by either calling `router.push` or `router.replace`. - * - * @param base - Base applied to all urls, defaults to '/' - * @returns a history object that can be passed to the router constructor - */ -function createMemoryHistory(base = '') { - let listeners = []; - let queue = [START]; - let position = 0; - base = normalizeBase(base); - function setLocation(location) { - position++; - if (position === queue.length) { - // we are at the end, we can simply append a new entry - queue.push(location); - } - else { - // we are in the middle, we remove everything from here in the queue - queue.splice(position); - queue.push(location); - } - } - function triggerListeners(to, from, { direction, delta }) { - const info = { - direction, - delta, - type: NavigationType.pop, - }; - for (const callback of listeners) { - callback(to, from, info); - } - } - const routerHistory = { - // rewritten by Object.defineProperty - location: START, - // TODO: should be kept in queue - state: {}, - base, - createHref: createHref.bind(null, base), - replace(to) { - // remove current entry and decrement position - queue.splice(position--, 1); - setLocation(to); - }, - push(to, data) { - setLocation(to); - }, - listen(callback) { - listeners.push(callback); - return () => { - const index = listeners.indexOf(callback); - if (index > -1) - listeners.splice(index, 1); - }; - }, - destroy() { - listeners = []; - queue = [START]; - position = 0; - }, - go(delta, shouldTrigger = true) { - const from = this.location; - const direction = - // we are considering delta === 0 going forward, but in abstract mode - // using 0 for the delta doesn't make sense like it does in html5 where - // it reloads the page - delta < 0 ? NavigationDirection.back : NavigationDirection.forward; - position = Math.max(0, Math.min(position + delta, queue.length - 1)); - if (shouldTrigger) { - triggerListeners(this.location, from, { - direction, - delta, - }); - } - }, - }; - Object.defineProperty(routerHistory, 'location', { - enumerable: true, - get: () => queue[position], - }); - return routerHistory; -} - -/** - * Creates a hash history. Useful for web applications with no host (e.g. - * `file://`) or when configuring a server to handle any URL is not possible. - * - * @param base - optional base to provide. Defaults to `location.pathname + - * location.search` If there is a `` tag in the `head`, its value will be - * ignored in favor of this parameter **but note it affects all the - * history.pushState() calls**, meaning that if you use a `` tag, it's - * `href` value **has to match this parameter** (ignoring anything after the - * `#`). - * - * @example - * ```js - * // at https://example.com/folder - * createWebHashHistory() // gives a url of `https://example.com/folder#` - * createWebHashHistory('/folder/') // gives a url of `https://example.com/folder/#` - * // if the `#` is provided in the base, it won't be added by `createWebHashHistory` - * createWebHashHistory('/folder/#/app/') // gives a url of `https://example.com/folder/#/app/` - * // you should avoid doing this because it changes the original url and breaks copying urls - * createWebHashHistory('/other-folder/') // gives a url of `https://example.com/other-folder/#` - * - * // at file:///usr/etc/folder/index.html - * // for locations with no `host`, the base is ignored - * createWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#` - * ``` - */ -function createWebHashHistory(base) { - // Make sure this implementation is fine in terms of encoding, specially for IE11 - // for `file://`, directly use the pathname and ignore the base - // location.pathname contains an initial `/` even at the root: `https://example.com` - base = location.host ? base || location.pathname + location.search : ''; - // allow the user to provide a `#` in the middle: `/base/#/app` - if (!base.includes('#')) - base += '#'; - if ((process.env.NODE_ENV !== 'production') && !base.endsWith('#/') && !base.endsWith('#')) { - warn(`A hash base must end with a "#":\n"${base}" should be "${base.replace(/#.*$/, '#')}".`); - } - return createWebHistory(base); -} - -function isRouteLocation(route) { - return typeof route === 'string' || (route && typeof route === 'object'); -} -function isRouteName(name) { - return typeof name === 'string' || typeof name === 'symbol'; -} - -/** - * Initial route location where the router is. Can be used in navigation guards - * to differentiate the initial navigation. - * - * @example - * ```js - * import { START_LOCATION } from 'vue-router' - * - * router.beforeEach((to, from) => { - * if (from === START_LOCATION) { - * // initial navigation - * } - * }) - * ``` - */ -const START_LOCATION_NORMALIZED = { - path: '/', - name: undefined, - params: {}, - query: {}, - hash: '', - fullPath: '/', - matched: [], - meta: {}, - redirectedFrom: undefined, -}; - -const NavigationFailureSymbol = /*#__PURE__*/ PolySymbol((process.env.NODE_ENV !== 'production') ? 'navigation failure' : 'nf'); -/** - * Enumeration with all possible types for navigation failures. Can be passed to - * {@link isNavigationFailure} to check for specific failures. - */ -var NavigationFailureType; -(function (NavigationFailureType) { - /** - * An aborted navigation is a navigation that failed because a navigation - * guard returned `false` or called `next(false)` - */ - NavigationFailureType[NavigationFailureType["aborted"] = 4] = "aborted"; - /** - * A cancelled navigation is a navigation that failed because a more recent - * navigation finished started (not necessarily finished). - */ - NavigationFailureType[NavigationFailureType["cancelled"] = 8] = "cancelled"; - /** - * A duplicated navigation is a navigation that failed because it was - * initiated while already being at the exact same location. - */ - NavigationFailureType[NavigationFailureType["duplicated"] = 16] = "duplicated"; -})(NavigationFailureType || (NavigationFailureType = {})); -// DEV only debug messages -const ErrorTypeMessages = { - [1 /* MATCHER_NOT_FOUND */]({ location, currentLocation }) { - return `No match for\n ${JSON.stringify(location)}${currentLocation - ? '\nwhile being at\n' + JSON.stringify(currentLocation) - : ''}`; - }, - [2 /* NAVIGATION_GUARD_REDIRECT */]({ from, to, }) { - return `Redirected from "${from.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`; - }, - [4 /* NAVIGATION_ABORTED */]({ from, to }) { - return `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`; - }, - [8 /* NAVIGATION_CANCELLED */]({ from, to }) { - return `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`; - }, - [16 /* NAVIGATION_DUPLICATED */]({ from, to }) { - return `Avoided redundant navigation to current location: "${from.fullPath}".`; - }, -}; -function createRouterError(type, params) { - // keep full error messages in cjs versions - if ((process.env.NODE_ENV !== 'production') || !true) { - return assign(new Error(ErrorTypeMessages[type](params)), { - type, - [NavigationFailureSymbol]: true, - }, params); - } - else { - return assign(new Error(), { - type, - [NavigationFailureSymbol]: true, - }, params); - } -} -function isNavigationFailure(error, type) { - return (error instanceof Error && - NavigationFailureSymbol in error && - (type == null || !!(error.type & type))); -} -const propertiesToLog = ['params', 'query', 'hash']; -function stringifyRoute(to) { - if (typeof to === 'string') - return to; - if ('path' in to) - return to.path; - const location = {}; - for (const key of propertiesToLog) { - if (key in to) - location[key] = to[key]; - } - return JSON.stringify(location, null, 2); -} - -// default pattern for a param: non greedy everything but / -const BASE_PARAM_PATTERN = '[^/]+?'; -const BASE_PATH_PARSER_OPTIONS = { - sensitive: false, - strict: false, - start: true, - end: true, -}; -// Special Regex characters that must be escaped in static tokens -const REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g; -/** - * Creates a path parser from an array of Segments (a segment is an array of Tokens) - * - * @param segments - array of segments returned by tokenizePath - * @param extraOptions - optional options for the regexp - * @returns a PathParser - */ -function tokensToParser(segments, extraOptions) { - const options = assign({}, BASE_PATH_PARSER_OPTIONS, extraOptions); - // the amount of scores is the same as the length of segments except for the root segment "/" - const score = []; - // the regexp as a string - let pattern = options.start ? '^' : ''; - // extracted keys - const keys = []; - for (const segment of segments) { - // the root segment needs special treatment - const segmentScores = segment.length ? [] : [90 /* Root */]; - // allow trailing slash - if (options.strict && !segment.length) - pattern += '/'; - for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) { - const token = segment[tokenIndex]; - // resets the score if we are inside a sub segment /:a-other-:b - let subSegmentScore = 40 /* Segment */ + - (options.sensitive ? 0.25 /* BonusCaseSensitive */ : 0); - if (token.type === 0 /* Static */) { - // prepend the slash if we are starting a new segment - if (!tokenIndex) - pattern += '/'; - pattern += token.value.replace(REGEX_CHARS_RE, '\\$&'); - subSegmentScore += 40 /* Static */; - } - else if (token.type === 1 /* Param */) { - const { value, repeatable, optional, regexp } = token; - keys.push({ - name: value, - repeatable, - optional, - }); - const re = regexp ? regexp : BASE_PARAM_PATTERN; - // the user provided a custom regexp /:id(\\d+) - if (re !== BASE_PARAM_PATTERN) { - subSegmentScore += 10 /* BonusCustomRegExp */; - // make sure the regexp is valid before using it - try { - new RegExp(`(${re})`); - } - catch (err) { - throw new Error(`Invalid custom RegExp for param "${value}" (${re}): ` + - err.message); - } - } - // when we repeat we must take care of the repeating leading slash - let subPattern = repeatable ? `((?:${re})(?:/(?:${re}))*)` : `(${re})`; - // prepend the slash if we are starting a new segment - if (!tokenIndex) - subPattern = - // avoid an optional / if there are more segments e.g. /:p?-static - // or /:p?-:p2 - optional && segment.length < 2 - ? `(?:/${subPattern})` - : '/' + subPattern; - if (optional) - subPattern += '?'; - pattern += subPattern; - subSegmentScore += 20 /* Dynamic */; - if (optional) - subSegmentScore += -8 /* BonusOptional */; - if (repeatable) - subSegmentScore += -20 /* BonusRepeatable */; - if (re === '.*') - subSegmentScore += -50 /* BonusWildcard */; - } - segmentScores.push(subSegmentScore); - } - // an empty array like /home/ -> [[{home}], []] - // if (!segment.length) pattern += '/' - score.push(segmentScores); - } - // only apply the strict bonus to the last score - if (options.strict && options.end) { - const i = score.length - 1; - score[i][score[i].length - 1] += 0.7000000000000001 /* BonusStrict */; - } - // TODO: dev only warn double trailing slash - if (!options.strict) - pattern += '/?'; - if (options.end) - pattern += '$'; - // allow paths like /dynamic to only match dynamic or dynamic/... but not dynamic_something_else - else if (options.strict) - pattern += '(?:/|$)'; - const re = new RegExp(pattern, options.sensitive ? '' : 'i'); - function parse(path) { - const match = path.match(re); - const params = {}; - if (!match) - return null; - for (let i = 1; i < match.length; i++) { - const value = match[i] || ''; - const key = keys[i - 1]; - params[key.name] = value && key.repeatable ? value.split('/') : value; - } - return params; - } - function stringify(params) { - let path = ''; - // for optional parameters to allow to be empty - let avoidDuplicatedSlash = false; - for (const segment of segments) { - if (!avoidDuplicatedSlash || !path.endsWith('/')) - path += '/'; - avoidDuplicatedSlash = false; - for (const token of segment) { - if (token.type === 0 /* Static */) { - path += token.value; - } - else if (token.type === 1 /* Param */) { - const { value, repeatable, optional } = token; - const param = value in params ? params[value] : ''; - if (Array.isArray(param) && !repeatable) - throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`); - const text = Array.isArray(param) ? param.join('/') : param; - if (!text) { - if (optional) { - // if we have more than one optional param like /:a?-static and there are more segments, we don't need to - // care about the optional param - if (segment.length < 2 && segments.length > 1) { - // remove the last slash as we could be at the end - if (path.endsWith('/')) - path = path.slice(0, -1); - // do not append a slash on the next iteration - else - avoidDuplicatedSlash = true; - } - } - else - throw new Error(`Missing required param "${value}"`); - } - path += text; - } - } - } - return path; - } - return { - re, - score, - keys, - parse, - stringify, - }; -} -/** - * Compares an array of numbers as used in PathParser.score and returns a - * number. This function can be used to `sort` an array - * - * @param a - first array of numbers - * @param b - second array of numbers - * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b - * should be sorted first - */ -function compareScoreArray(a, b) { - let i = 0; - while (i < a.length && i < b.length) { - const diff = b[i] - a[i]; - // only keep going if diff === 0 - if (diff) - return diff; - i++; - } - // if the last subsegment was Static, the shorter segments should be sorted first - // otherwise sort the longest segment first - if (a.length < b.length) { - return a.length === 1 && a[0] === 40 /* Static */ + 40 /* Segment */ - ? -1 - : 1; - } - else if (a.length > b.length) { - return b.length === 1 && b[0] === 40 /* Static */ + 40 /* Segment */ - ? 1 - : -1; - } - return 0; -} -/** - * Compare function that can be used with `sort` to sort an array of PathParser - * - * @param a - first PathParser - * @param b - second PathParser - * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b - */ -function comparePathParserScore(a, b) { - let i = 0; - const aScore = a.score; - const bScore = b.score; - while (i < aScore.length && i < bScore.length) { - const comp = compareScoreArray(aScore[i], bScore[i]); - // do not return if both are equal - if (comp) - return comp; - i++; - } - // if a and b share the same score entries but b has more, sort b first - return bScore.length - aScore.length; - // this is the ternary version - // return aScore.length < bScore.length - // ? 1 - // : aScore.length > bScore.length - // ? -1 - // : 0 -} - -const ROOT_TOKEN = { - type: 0 /* Static */, - value: '', -}; -const VALID_PARAM_RE = /[a-zA-Z0-9_]/; -// After some profiling, the cache seems to be unnecessary because tokenizePath -// (the slowest part of adding a route) is very fast -// const tokenCache = new Map() -function tokenizePath(path) { - if (!path) - return [[]]; - if (path === '/') - return [[ROOT_TOKEN]]; - if (!path.startsWith('/')) { - throw new Error((process.env.NODE_ENV !== 'production') - ? `Route paths should start with a "/": "${path}" should be "/${path}".` - : `Invalid path "${path}"`); - } - // if (tokenCache.has(path)) return tokenCache.get(path)! - function crash(message) { - throw new Error(`ERR (${state})/"${buffer}": ${message}`); - } - let state = 0 /* Static */; - let previousState = state; - const tokens = []; - // the segment will always be valid because we get into the initial state - // with the leading / - let segment; - function finalizeSegment() { - if (segment) - tokens.push(segment); - segment = []; - } - // index on the path - let i = 0; - // char at index - let char; - // buffer of the value read - let buffer = ''; - // custom regexp for a param - let customRe = ''; - function consumeBuffer() { - if (!buffer) - return; - if (state === 0 /* Static */) { - segment.push({ - type: 0 /* Static */, - value: buffer, - }); - } - else if (state === 1 /* Param */ || - state === 2 /* ParamRegExp */ || - state === 3 /* ParamRegExpEnd */) { - if (segment.length > 1 && (char === '*' || char === '+')) - crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`); - segment.push({ - type: 1 /* Param */, - value: buffer, - regexp: customRe, - repeatable: char === '*' || char === '+', - optional: char === '*' || char === '?', - }); - } - else { - crash('Invalid state to consume buffer'); - } - buffer = ''; - } - function addCharToBuffer() { - buffer += char; - } - while (i < path.length) { - char = path[i++]; - if (char === '\\' && state !== 2 /* ParamRegExp */) { - previousState = state; - state = 4 /* EscapeNext */; - continue; - } - switch (state) { - case 0 /* Static */: - if (char === '/') { - if (buffer) { - consumeBuffer(); - } - finalizeSegment(); - } - else if (char === ':') { - consumeBuffer(); - state = 1 /* Param */; - } - else { - addCharToBuffer(); - } - break; - case 4 /* EscapeNext */: - addCharToBuffer(); - state = previousState; - break; - case 1 /* Param */: - if (char === '(') { - state = 2 /* ParamRegExp */; - } - else if (VALID_PARAM_RE.test(char)) { - addCharToBuffer(); - } - else { - consumeBuffer(); - state = 0 /* Static */; - // go back one character if we were not modifying - if (char !== '*' && char !== '?' && char !== '+') - i--; - } - break; - case 2 /* ParamRegExp */: - // TODO: is it worth handling nested regexp? like :p(?:prefix_([^/]+)_suffix) - // it already works by escaping the closing ) - // https://paths.esm.dev/?p=AAMeJbiAwQEcDKbAoAAkP60PG2R6QAvgNaA6AFACM2ABuQBB# - // is this really something people need since you can also write - // /prefix_:p()_suffix - if (char === ')') { - // handle the escaped ) - if (customRe[customRe.length - 1] == '\\') - customRe = customRe.slice(0, -1) + char; - else - state = 3 /* ParamRegExpEnd */; - } - else { - customRe += char; - } - break; - case 3 /* ParamRegExpEnd */: - // same as finalizing a param - consumeBuffer(); - state = 0 /* Static */; - // go back one character if we were not modifying - if (char !== '*' && char !== '?' && char !== '+') - i--; - customRe = ''; - break; - default: - crash('Unknown state'); - break; - } - } - if (state === 2 /* ParamRegExp */) - crash(`Unfinished custom RegExp for param "${buffer}"`); - consumeBuffer(); - finalizeSegment(); - // tokenCache.set(path, tokens) - return tokens; -} - -function createRouteRecordMatcher(record, parent, options) { - const parser = tokensToParser(tokenizePath(record.path), options); - // warn against params with the same name - if ((process.env.NODE_ENV !== 'production')) { - const existingKeys = new Set(); - for (const key of parser.keys) { - if (existingKeys.has(key.name)) - warn(`Found duplicated params with name "${key.name}" for path "${record.path}". Only the last one will be available on "$route.params".`); - existingKeys.add(key.name); - } - } - const matcher = assign(parser, { - record, - parent, - // these needs to be populated by the parent - children: [], - alias: [], - }); - if (parent) { - // both are aliases or both are not aliases - // we don't want to mix them because the order is used when - // passing originalRecord in Matcher.addRoute - if (!matcher.record.aliasOf === !parent.record.aliasOf) - parent.children.push(matcher); - } - return matcher; -} - -/** - * Creates a Router Matcher. - * - * @internal - * @param routes - array of initial routes - * @param globalOptions - global route options - */ -function createRouterMatcher(routes, globalOptions) { - // normalized ordered array of matchers - const matchers = []; - const matcherMap = new Map(); - globalOptions = mergeOptions({ strict: false, end: true, sensitive: false }, globalOptions); - function getRecordMatcher(name) { - return matcherMap.get(name); - } - function addRoute(record, parent, originalRecord) { - // used later on to remove by name - const isRootAdd = !originalRecord; - const mainNormalizedRecord = normalizeRouteRecord(record); - // we might be the child of an alias - mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record; - const options = mergeOptions(globalOptions, record); - // generate an array of records to correctly handle aliases - const normalizedRecords = [ - mainNormalizedRecord, - ]; - if ('alias' in record) { - const aliases = typeof record.alias === 'string' ? [record.alias] : record.alias; - for (const alias of aliases) { - normalizedRecords.push(assign({}, mainNormalizedRecord, { - // this allows us to hold a copy of the `components` option - // so that async components cache is hold on the original record - components: originalRecord - ? originalRecord.record.components - : mainNormalizedRecord.components, - path: alias, - // we might be the child of an alias - aliasOf: originalRecord - ? originalRecord.record - : mainNormalizedRecord, - // the aliases are always of the same kind as the original since they - // are defined on the same record - })); - } - } - let matcher; - let originalMatcher; - for (const normalizedRecord of normalizedRecords) { - const { path } = normalizedRecord; - // Build up the path for nested routes if the child isn't an absolute - // route. Only add the / delimiter if the child path isn't empty and if the - // parent path doesn't have a trailing slash - if (parent && path[0] !== '/') { - const parentPath = parent.record.path; - const connectingSlash = parentPath[parentPath.length - 1] === '/' ? '' : '/'; - normalizedRecord.path = - parent.record.path + (path && connectingSlash + path); - } - if ((process.env.NODE_ENV !== 'production') && normalizedRecord.path === '*') { - throw new Error('Catch all routes ("*") must now be defined using a param with a custom regexp.\n' + - 'See more at https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes.'); - } - // create the object before hand so it can be passed to children - matcher = createRouteRecordMatcher(normalizedRecord, parent, options); - if ((process.env.NODE_ENV !== 'production') && parent && path[0] === '/') - checkMissingParamsInAbsolutePath(matcher, parent); - // if we are an alias we must tell the original record that we exist - // so we can be removed - if (originalRecord) { - originalRecord.alias.push(matcher); - if ((process.env.NODE_ENV !== 'production')) { - checkSameParams(originalRecord, matcher); - } - } - else { - // otherwise, the first record is the original and others are aliases - originalMatcher = originalMatcher || matcher; - if (originalMatcher !== matcher) - originalMatcher.alias.push(matcher); - // remove the route if named and only for the top record (avoid in nested calls) - // this works because the original record is the first one - if (isRootAdd && record.name && !isAliasRecord(matcher)) - removeRoute(record.name); - } - if ('children' in mainNormalizedRecord) { - const children = mainNormalizedRecord.children; - for (let i = 0; i < children.length; i++) { - addRoute(children[i], matcher, originalRecord && originalRecord.children[i]); - } - } - // if there was no original record, then the first one was not an alias and all - // other alias (if any) need to reference this record when adding children - originalRecord = originalRecord || matcher; - // TODO: add normalized records for more flexibility - // if (parent && isAliasRecord(originalRecord)) { - // parent.children.push(originalRecord) - // } - insertMatcher(matcher); - } - return originalMatcher - ? () => { - // since other matchers are aliases, they should be removed by the original matcher - removeRoute(originalMatcher); - } - : noop; - } - function removeRoute(matcherRef) { - if (isRouteName(matcherRef)) { - const matcher = matcherMap.get(matcherRef); - if (matcher) { - matcherMap.delete(matcherRef); - matchers.splice(matchers.indexOf(matcher), 1); - matcher.children.forEach(removeRoute); - matcher.alias.forEach(removeRoute); - } - } - else { - const index = matchers.indexOf(matcherRef); - if (index > -1) { - matchers.splice(index, 1); - if (matcherRef.record.name) - matcherMap.delete(matcherRef.record.name); - matcherRef.children.forEach(removeRoute); - matcherRef.alias.forEach(removeRoute); - } - } - } - function getRoutes() { - return matchers; - } - function insertMatcher(matcher) { - let i = 0; - while (i < matchers.length && - comparePathParserScore(matcher, matchers[i]) >= 0 && - // Adding children with empty path should still appear before the parent - // https://github.com/vuejs/router/issues/1124 - (matcher.record.path !== matchers[i].record.path || - !isRecordChildOf(matcher, matchers[i]))) - i++; - matchers.splice(i, 0, matcher); - // only add the original record to the name map - if (matcher.record.name && !isAliasRecord(matcher)) - matcherMap.set(matcher.record.name, matcher); - } - function resolve(location, currentLocation) { - let matcher; - let params = {}; - let path; - let name; - if ('name' in location && location.name) { - matcher = matcherMap.get(location.name); - if (!matcher) - throw createRouterError(1 /* MATCHER_NOT_FOUND */, { - location, - }); - name = matcher.record.name; - params = assign( - // paramsFromLocation is a new object - paramsFromLocation(currentLocation.params, - // only keep params that exist in the resolved location - // TODO: only keep optional params coming from a parent record - matcher.keys.filter(k => !k.optional).map(k => k.name)), location.params); - // throws if cannot be stringified - path = matcher.stringify(params); - } - else if ('path' in location) { - // no need to resolve the path with the matcher as it was provided - // this also allows the user to control the encoding - path = location.path; - if ((process.env.NODE_ENV !== 'production') && !path.startsWith('/')) { - warn(`The Matcher cannot resolve relative paths but received "${path}". Unless you directly called \`matcher.resolve("${path}")\`, this is probably a bug in vue-router. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/router.`); - } - matcher = matchers.find(m => m.re.test(path)); - // matcher should have a value after the loop - if (matcher) { - // TODO: dev warning of unused params if provided - // we know the matcher works because we tested the regexp - params = matcher.parse(path); - name = matcher.record.name; - } - // location is a relative path - } - else { - // match by name or path of current route - matcher = currentLocation.name - ? matcherMap.get(currentLocation.name) - : matchers.find(m => m.re.test(currentLocation.path)); - if (!matcher) - throw createRouterError(1 /* MATCHER_NOT_FOUND */, { - location, - currentLocation, - }); - name = matcher.record.name; - // since we are navigating to the same location, we don't need to pick the - // params like when `name` is provided - params = assign({}, currentLocation.params, location.params); - path = matcher.stringify(params); - } - const matched = []; - let parentMatcher = matcher; - while (parentMatcher) { - // reversed order so parents are at the beginning - matched.unshift(parentMatcher.record); - parentMatcher = parentMatcher.parent; - } - return { - name, - path, - params, - matched, - meta: mergeMetaFields(matched), - }; - } - // add initial routes - routes.forEach(route => addRoute(route)); - return { addRoute, resolve, removeRoute, getRoutes, getRecordMatcher }; -} -function paramsFromLocation(params, keys) { - const newParams = {}; - for (const key of keys) { - if (key in params) - newParams[key] = params[key]; - } - return newParams; -} -/** - * Normalizes a RouteRecordRaw. Creates a copy - * - * @param record - * @returns the normalized version - */ -function normalizeRouteRecord(record) { - return { - path: record.path, - redirect: record.redirect, - name: record.name, - meta: record.meta || {}, - aliasOf: undefined, - beforeEnter: record.beforeEnter, - props: normalizeRecordProps(record), - children: record.children || [], - instances: {}, - leaveGuards: new Set(), - updateGuards: new Set(), - enterCallbacks: {}, - components: 'components' in record - ? record.components || {} - : { default: record.component }, - }; -} -/** - * Normalize the optional `props` in a record to always be an object similar to - * components. Also accept a boolean for components. - * @param record - */ -function normalizeRecordProps(record) { - const propsObject = {}; - // props does not exist on redirect records but we can set false directly - const props = record.props || false; - if ('component' in record) { - propsObject.default = props; - } - else { - // NOTE: we could also allow a function to be applied to every component. - // Would need user feedback for use cases - for (const name in record.components) - propsObject[name] = typeof props === 'boolean' ? props : props[name]; - } - return propsObject; -} -/** - * Checks if a record or any of its parent is an alias - * @param record - */ -function isAliasRecord(record) { - while (record) { - if (record.record.aliasOf) - return true; - record = record.parent; - } - return false; -} -/** - * Merge meta fields of an array of records - * - * @param matched - array of matched records - */ -function mergeMetaFields(matched) { - return matched.reduce((meta, record) => assign(meta, record.meta), {}); -} -function mergeOptions(defaults, partialOptions) { - const options = {}; - for (const key in defaults) { - options[key] = key in partialOptions ? partialOptions[key] : defaults[key]; - } - return options; -} -function isSameParam(a, b) { - return (a.name === b.name && - a.optional === b.optional && - a.repeatable === b.repeatable); -} -/** - * Check if a path and its alias have the same required params - * - * @param a - original record - * @param b - alias record - */ -function checkSameParams(a, b) { - for (const key of a.keys) { - if (!key.optional && !b.keys.find(isSameParam.bind(null, key))) - return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`); - } - for (const key of b.keys) { - if (!key.optional && !a.keys.find(isSameParam.bind(null, key))) - return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`); - } -} -function checkMissingParamsInAbsolutePath(record, parent) { - for (const key of parent.keys) { - if (!record.keys.find(isSameParam.bind(null, key))) - return warn(`Absolute path "${record.record.path}" should have the exact same param named "${key.name}" as its parent "${parent.record.path}".`); - } -} -function isRecordChildOf(record, parent) { - return parent.children.some(child => child === record || isRecordChildOf(record, child)); -} - -/** - * Encoding Rules ␣ = Space Path: ␣ " < > # ? { } Query: ␣ " < > # & = Hash: ␣ " - * < > ` - * - * On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2) - * defines some extra characters to be encoded. Most browsers do not encode them - * in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to - * also encode `!'()*`. Leaving unencoded only ASCII alphanumeric(`a-zA-Z0-9`) - * plus `-._~`. This extra safety should be applied to query by patching the - * string returned by encodeURIComponent encodeURI also encodes `[\]^`. `\` - * should be encoded to avoid ambiguity. Browsers (IE, FF, C) transform a `\` - * into a `/` if directly typed in. The _backtick_ (`````) should also be - * encoded everywhere because some browsers like FF encode it when directly - * written while others don't. Safari and IE don't encode ``"<>{}``` in hash. - */ -// const EXTRA_RESERVED_RE = /[!'()*]/g -// const encodeReservedReplacer = (c: string) => '%' + c.charCodeAt(0).toString(16) -const HASH_RE = /#/g; // %23 -const AMPERSAND_RE = /&/g; // %26 -const SLASH_RE = /\//g; // %2F -const EQUAL_RE = /=/g; // %3D -const IM_RE = /\?/g; // %3F -const PLUS_RE = /\+/g; // %2B -/** - * NOTE: It's not clear to me if we should encode the + symbol in queries, it - * seems to be less flexible than not doing so and I can't find out the legacy - * systems requiring this for regular requests like text/html. In the standard, - * the encoding of the plus character is only mentioned for - * application/x-www-form-urlencoded - * (https://url.spec.whatwg.org/#urlencoded-parsing) and most browsers seems lo - * leave the plus character as is in queries. To be more flexible, we allow the - * plus character on the query but it can also be manually encoded by the user. - * - * Resources: - * - https://url.spec.whatwg.org/#urlencoded-parsing - * - https://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20 - */ -const ENC_BRACKET_OPEN_RE = /%5B/g; // [ -const ENC_BRACKET_CLOSE_RE = /%5D/g; // ] -const ENC_CARET_RE = /%5E/g; // ^ -const ENC_BACKTICK_RE = /%60/g; // ` -const ENC_CURLY_OPEN_RE = /%7B/g; // { -const ENC_PIPE_RE = /%7C/g; // | -const ENC_CURLY_CLOSE_RE = /%7D/g; // } -const ENC_SPACE_RE = /%20/g; // } -/** - * Encode characters that need to be encoded on the path, search and hash - * sections of the URL. - * - * @internal - * @param text - string to encode - * @returns encoded string - */ -function commonEncode(text) { - return encodeURI('' + text) - .replace(ENC_PIPE_RE, '|') - .replace(ENC_BRACKET_OPEN_RE, '[') - .replace(ENC_BRACKET_CLOSE_RE, ']'); -} -/** - * Encode characters that need to be encoded on the hash section of the URL. - * - * @param text - string to encode - * @returns encoded string - */ -function encodeHash(text) { - return commonEncode(text) - .replace(ENC_CURLY_OPEN_RE, '{') - .replace(ENC_CURLY_CLOSE_RE, '}') - .replace(ENC_CARET_RE, '^'); -} -/** - * Encode characters that need to be encoded query values on the query - * section of the URL. - * - * @param text - string to encode - * @returns encoded string - */ -function encodeQueryValue(text) { - return (commonEncode(text) - // Encode the space as +, encode the + to differentiate it from the space - .replace(PLUS_RE, '%2B') - .replace(ENC_SPACE_RE, '+') - .replace(HASH_RE, '%23') - .replace(AMPERSAND_RE, '%26') - .replace(ENC_BACKTICK_RE, '`') - .replace(ENC_CURLY_OPEN_RE, '{') - .replace(ENC_CURLY_CLOSE_RE, '}') - .replace(ENC_CARET_RE, '^')); -} -/** - * Like `encodeQueryValue` but also encodes the `=` character. - * - * @param text - string to encode - */ -function encodeQueryKey(text) { - return encodeQueryValue(text).replace(EQUAL_RE, '%3D'); -} -/** - * Encode characters that need to be encoded on the path section of the URL. - * - * @param text - string to encode - * @returns encoded string - */ -function encodePath(text) { - return commonEncode(text).replace(HASH_RE, '%23').replace(IM_RE, '%3F'); -} -/** - * Encode characters that need to be encoded on the path section of the URL as a - * param. This function encodes everything {@link encodePath} does plus the - * slash (`/`) character. If `text` is `null` or `undefined`, returns an empty - * string instead. - * - * @param text - string to encode - * @returns encoded string - */ -function encodeParam(text) { - return text == null ? '' : encodePath(text).replace(SLASH_RE, '%2F'); -} -/** - * Decode text using `decodeURIComponent`. Returns the original text if it - * fails. - * - * @param text - string to decode - * @returns decoded string - */ -function decode(text) { - try { - return decodeURIComponent('' + text); - } - catch (err) { - (process.env.NODE_ENV !== 'production') && warn(`Error decoding "${text}". Using original value`); - } - return '' + text; -} - -/** - * Transforms a queryString into a {@link LocationQuery} object. Accept both, a - * version with the leading `?` and without Should work as URLSearchParams - - * @internal - * - * @param search - search string to parse - * @returns a query object - */ -function parseQuery(search) { - const query = {}; - // avoid creating an object with an empty key and empty value - // because of split('&') - if (search === '' || search === '?') - return query; - const hasLeadingIM = search[0] === '?'; - const searchParams = (hasLeadingIM ? search.slice(1) : search).split('&'); - for (let i = 0; i < searchParams.length; ++i) { - // pre decode the + into space - const searchParam = searchParams[i].replace(PLUS_RE, ' '); - // allow the = character - const eqPos = searchParam.indexOf('='); - const key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos)); - const value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1)); - if (key in query) { - // an extra variable for ts types - let currentValue = query[key]; - if (!Array.isArray(currentValue)) { - currentValue = query[key] = [currentValue]; - } - currentValue.push(value); - } - else { - query[key] = value; - } - } - return query; -} -/** - * Stringifies a {@link LocationQueryRaw} object. Like `URLSearchParams`, it - * doesn't prepend a `?` - * - * @internal - * - * @param query - query object to stringify - * @returns string version of the query without the leading `?` - */ -function stringifyQuery(query) { - let search = ''; - for (let key in query) { - const value = query[key]; - key = encodeQueryKey(key); - if (value == null) { - // only null adds the value - if (value !== undefined) { - search += (search.length ? '&' : '') + key; - } - continue; - } - // keep null values - const values = Array.isArray(value) - ? value.map(v => v && encodeQueryValue(v)) - : [value && encodeQueryValue(value)]; - values.forEach(value => { - // skip undefined values in arrays as if they were not present - // smaller code than using filter - if (value !== undefined) { - // only append & with non-empty search - search += (search.length ? '&' : '') + key; - if (value != null) - search += '=' + value; - } - }); - } - return search; -} -/** - * Transforms a {@link LocationQueryRaw} into a {@link LocationQuery} by casting - * numbers into strings, removing keys with an undefined value and replacing - * undefined with null in arrays - * - * @param query - query object to normalize - * @returns a normalized query object - */ -function normalizeQuery(query) { - const normalizedQuery = {}; - for (const key in query) { - const value = query[key]; - if (value !== undefined) { - normalizedQuery[key] = Array.isArray(value) - ? value.map(v => (v == null ? null : '' + v)) - : value == null - ? value - : '' + value; - } - } - return normalizedQuery; -} - -/** - * Create a list of callbacks that can be reset. Used to create before and after navigation guards list - */ -function useCallbacks() { - let handlers = []; - function add(handler) { - handlers.push(handler); - return () => { - const i = handlers.indexOf(handler); - if (i > -1) - handlers.splice(i, 1); - }; - } - function reset() { - handlers = []; - } - return { - add, - list: () => handlers, - reset, - }; -} - -function registerGuard(record, name, guard) { - const removeFromList = () => { - record[name].delete(guard); - }; - onUnmounted(removeFromList); - onDeactivated(removeFromList); - onActivated(() => { - record[name].add(guard); - }); - record[name].add(guard); -} -/** - * Add a navigation guard that triggers whenever the component for the current - * location is about to be left. Similar to {@link beforeRouteLeave} but can be - * used in any component. The guard is removed when the component is unmounted. - * - * @param leaveGuard - {@link NavigationGuard} - */ -function onBeforeRouteLeave(leaveGuard) { - if ((process.env.NODE_ENV !== 'production') && !getCurrentInstance()) { - warn('getCurrentInstance() returned null. onBeforeRouteLeave() must be called at the top of a setup function'); - return; - } - const activeRecord = inject(matchedRouteKey, - // to avoid warning - {}).value; - if (!activeRecord) { - (process.env.NODE_ENV !== 'production') && - warn('No active route record was found when calling `onBeforeRouteLeave()`. Make sure you call this function inside of a component child of . Maybe you called it inside of App.vue?'); - return; - } - registerGuard(activeRecord, 'leaveGuards', leaveGuard); -} -/** - * Add a navigation guard that triggers whenever the current location is about - * to be updated. Similar to {@link beforeRouteUpdate} but can be used in any - * component. The guard is removed when the component is unmounted. - * - * @param updateGuard - {@link NavigationGuard} - */ -function onBeforeRouteUpdate(updateGuard) { - if ((process.env.NODE_ENV !== 'production') && !getCurrentInstance()) { - warn('getCurrentInstance() returned null. onBeforeRouteUpdate() must be called at the top of a setup function'); - return; - } - const activeRecord = inject(matchedRouteKey, - // to avoid warning - {}).value; - if (!activeRecord) { - (process.env.NODE_ENV !== 'production') && - warn('No active route record was found when calling `onBeforeRouteUpdate()`. Make sure you call this function inside of a component child of . Maybe you called it inside of App.vue?'); - return; - } - registerGuard(activeRecord, 'updateGuards', updateGuard); -} -function guardToPromiseFn(guard, to, from, record, name) { - // keep a reference to the enterCallbackArray to prevent pushing callbacks if a new navigation took place - const enterCallbackArray = record && - // name is defined if record is because of the function overload - (record.enterCallbacks[name] = record.enterCallbacks[name] || []); - return () => new Promise((resolve, reject) => { - const next = (valid) => { - if (valid === false) - reject(createRouterError(4 /* NAVIGATION_ABORTED */, { - from, - to, - })); - else if (valid instanceof Error) { - reject(valid); - } - else if (isRouteLocation(valid)) { - reject(createRouterError(2 /* NAVIGATION_GUARD_REDIRECT */, { - from: to, - to: valid, - })); - } - else { - if (enterCallbackArray && - // since enterCallbackArray is truthy, both record and name also are - record.enterCallbacks[name] === enterCallbackArray && - typeof valid === 'function') - enterCallbackArray.push(valid); - resolve(); - } - }; - // wrapping with Promise.resolve allows it to work with both async and sync guards - const guardReturn = guard.call(record && record.instances[name], to, from, (process.env.NODE_ENV !== 'production') ? canOnlyBeCalledOnce(next, to, from) : next); - let guardCall = Promise.resolve(guardReturn); - if (guard.length < 3) - guardCall = guardCall.then(next); - if ((process.env.NODE_ENV !== 'production') && guard.length > 2) { - const message = `The "next" callback was never called inside of ${guard.name ? '"' + guard.name + '"' : ''}:\n${guard.toString()}\n. If you are returning a value instead of calling "next", make sure to remove the "next" parameter from your function.`; - if (typeof guardReturn === 'object' && 'then' in guardReturn) { - guardCall = guardCall.then(resolvedValue => { - // @ts-expect-error: _called is added at canOnlyBeCalledOnce - if (!next._called) { - warn(message); - return Promise.reject(new Error('Invalid navigation guard')); - } - return resolvedValue; - }); - // TODO: test me! - } - else if (guardReturn !== undefined) { - // @ts-expect-error: _called is added at canOnlyBeCalledOnce - if (!next._called) { - warn(message); - reject(new Error('Invalid navigation guard')); - return; - } - } - } - guardCall.catch(err => reject(err)); - }); -} -function canOnlyBeCalledOnce(next, to, from) { - let called = 0; - return function () { - if (called++ === 1) - warn(`The "next" callback was called more than once in one navigation guard when going from "${from.fullPath}" to "${to.fullPath}". It should be called exactly one time in each navigation guard. This will fail in production.`); - // @ts-expect-error: we put it in the original one because it's easier to check - next._called = true; - if (called === 1) - next.apply(null, arguments); - }; -} -function extractComponentsGuards(matched, guardType, to, from) { - const guards = []; - for (const record of matched) { - for (const name in record.components) { - let rawComponent = record.components[name]; - if ((process.env.NODE_ENV !== 'production')) { - if (!rawComponent || - (typeof rawComponent !== 'object' && - typeof rawComponent !== 'function')) { - warn(`Component "${name}" in record with path "${record.path}" is not` + - ` a valid component. Received "${String(rawComponent)}".`); - // throw to ensure we stop here but warn to ensure the message isn't - // missed by the user - throw new Error('Invalid route component'); - } - else if ('then' in rawComponent) { - // warn if user wrote import('/component.vue') instead of () => - // import('./component.vue') - warn(`Component "${name}" in record with path "${record.path}" is a ` + - `Promise instead of a function that returns a Promise. Did you ` + - `write "import('./MyPage.vue')" instead of ` + - `"() => import('./MyPage.vue')" ? This will break in ` + - `production if not fixed.`); - const promise = rawComponent; - rawComponent = () => promise; - } - else if (rawComponent.__asyncLoader && - // warn only once per component - !rawComponent.__warnedDefineAsync) { - rawComponent.__warnedDefineAsync = true; - warn(`Component "${name}" in record with path "${record.path}" is defined ` + - `using "defineAsyncComponent()". ` + - `Write "() => import('./MyPage.vue')" instead of ` + - `"defineAsyncComponent(() => import('./MyPage.vue'))".`); - } - } - // skip update and leave guards if the route component is not mounted - if (guardType !== 'beforeRouteEnter' && !record.instances[name]) - continue; - if (isRouteComponent(rawComponent)) { - // __vccOpts is added by vue-class-component and contain the regular options - const options = rawComponent.__vccOpts || rawComponent; - const guard = options[guardType]; - guard && guards.push(guardToPromiseFn(guard, to, from, record, name)); - } - else { - // start requesting the chunk already - let componentPromise = rawComponent(); - if ((process.env.NODE_ENV !== 'production') && !('catch' in componentPromise)) { - warn(`Component "${name}" in record with path "${record.path}" is a function that does not return a Promise. If you were passing a functional component, make sure to add a "displayName" to the component. This will break in production if not fixed.`); - componentPromise = Promise.resolve(componentPromise); - } - guards.push(() => componentPromise.then(resolved => { - if (!resolved) - return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}"`)); - const resolvedComponent = isESModule(resolved) - ? resolved.default - : resolved; - // replace the function with the resolved component - record.components[name] = resolvedComponent; - // __vccOpts is added by vue-class-component and contain the regular options - const options = resolvedComponent.__vccOpts || resolvedComponent; - const guard = options[guardType]; - return guard && guardToPromiseFn(guard, to, from, record, name)(); - })); - } - } - } - return guards; -} -/** - * Allows differentiating lazy components from functional components and vue-class-component - * - * @param component - */ -function isRouteComponent(component) { - return (typeof component === 'object' || - 'displayName' in component || - 'props' in component || - '__vccOpts' in component); -} - -// TODO: we could allow currentRoute as a prop to expose `isActive` and -// `isExactActive` behavior should go through an RFC -function useLink(props) { - const router = inject(routerKey); - const currentRoute = inject(routeLocationKey); - const route = computed(() => router.resolve(unref(props.to))); - const activeRecordIndex = computed(() => { - const { matched } = route.value; - const { length } = matched; - const routeMatched = matched[length - 1]; - const currentMatched = currentRoute.matched; - if (!routeMatched || !currentMatched.length) - return -1; - const index = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched)); - if (index > -1) - return index; - // possible parent record - const parentRecordPath = getOriginalPath(matched[length - 2]); - return ( - // we are dealing with nested routes - length > 1 && - // if the parent and matched route have the same path, this link is - // referring to the empty child. Or we currently are on a different - // child of the same parent - getOriginalPath(routeMatched) === parentRecordPath && - // avoid comparing the child with its parent - currentMatched[currentMatched.length - 1].path !== parentRecordPath - ? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2])) - : index); - }); - const isActive = computed(() => activeRecordIndex.value > -1 && - includesParams(currentRoute.params, route.value.params)); - const isExactActive = computed(() => activeRecordIndex.value > -1 && - activeRecordIndex.value === currentRoute.matched.length - 1 && - isSameRouteLocationParams(currentRoute.params, route.value.params)); - function navigate(e = {}) { - if (guardEvent(e)) { - return router[unref(props.replace) ? 'replace' : 'push'](unref(props.to) - // avoid uncaught errors are they are logged anyway - ).catch(noop); - } - return Promise.resolve(); - } - // devtools only - if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) && isBrowser) { - const instance = getCurrentInstance(); - if (instance) { - const linkContextDevtools = { - route: route.value, - isActive: isActive.value, - isExactActive: isExactActive.value, - }; - // @ts-expect-error: this is internal - instance.__vrl_devtools = instance.__vrl_devtools || []; - // @ts-expect-error: this is internal - instance.__vrl_devtools.push(linkContextDevtools); - watchEffect(() => { - linkContextDevtools.route = route.value; - linkContextDevtools.isActive = isActive.value; - linkContextDevtools.isExactActive = isExactActive.value; - }, { flush: 'post' }); - } - } - return { - route, - href: computed(() => route.value.href), - isActive, - isExactActive, - navigate, - }; -} -const RouterLinkImpl = /*#__PURE__*/ defineComponent({ - name: 'RouterLink', - props: { - to: { - type: [String, Object], - required: true, - }, - replace: Boolean, - activeClass: String, - // inactiveClass: String, - exactActiveClass: String, - custom: Boolean, - ariaCurrentValue: { - type: String, - default: 'page', - }, - }, - useLink, - setup(props, { slots }) { - const link = reactive(useLink(props)); - const { options } = inject(routerKey); - const elClass = computed(() => ({ - [getLinkClass(props.activeClass, options.linkActiveClass, 'router-link-active')]: link.isActive, - // [getLinkClass( - // props.inactiveClass, - // options.linkInactiveClass, - // 'router-link-inactive' - // )]: !link.isExactActive, - [getLinkClass(props.exactActiveClass, options.linkExactActiveClass, 'router-link-exact-active')]: link.isExactActive, - })); - return () => { - const children = slots.default && slots.default(link); - return props.custom - ? children - : h('a', { - 'aria-current': link.isExactActive - ? props.ariaCurrentValue - : null, - href: link.href, - // this would override user added attrs but Vue will still add - // the listener so we end up triggering both - onClick: link.navigate, - class: elClass.value, - }, children); - }; - }, -}); -// export the public type for h/tsx inference -// also to avoid inline import() in generated d.ts files -/** - * Component to render a link that triggers a navigation on click. - */ -const RouterLink = RouterLinkImpl; -function guardEvent(e) { - // don't redirect with control keys - if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) - return; - // don't redirect when preventDefault called - if (e.defaultPrevented) - return; - // don't redirect on right click - if (e.button !== undefined && e.button !== 0) - return; - // don't redirect if `target="_blank"` - // @ts-expect-error getAttribute does exist - if (e.currentTarget && e.currentTarget.getAttribute) { - // @ts-expect-error getAttribute exists - const target = e.currentTarget.getAttribute('target'); - if (/\b_blank\b/i.test(target)) - return; - } - // this may be a Weex event which doesn't have this method - if (e.preventDefault) - e.preventDefault(); - return true; -} -function includesParams(outer, inner) { - for (const key in inner) { - const innerValue = inner[key]; - const outerValue = outer[key]; - if (typeof innerValue === 'string') { - if (innerValue !== outerValue) - return false; - } - else { - if (!Array.isArray(outerValue) || - outerValue.length !== innerValue.length || - innerValue.some((value, i) => value !== outerValue[i])) - return false; - } - } - return true; -} -/** - * Get the original path value of a record by following its aliasOf - * @param record - */ -function getOriginalPath(record) { - return record ? (record.aliasOf ? record.aliasOf.path : record.path) : ''; -} -/** - * Utility class to get the active class based on defaults. - * @param propClass - * @param globalClass - * @param defaultClass - */ -const getLinkClass = (propClass, globalClass, defaultClass) => propClass != null - ? propClass - : globalClass != null - ? globalClass - : defaultClass; - -const RouterViewImpl = /*#__PURE__*/ defineComponent({ - name: 'RouterView', - // #674 we manually inherit them - inheritAttrs: false, - props: { - name: { - type: String, - default: 'default', - }, - route: Object, - }, - // Better compat for @vue/compat users - // https://github.com/vuejs/router/issues/1315 - compatConfig: { MODE: 3 }, - setup(props, { attrs, slots }) { - (process.env.NODE_ENV !== 'production') && warnDeprecatedUsage(); - const injectedRoute = inject(routerViewLocationKey); - const routeToDisplay = computed(() => props.route || injectedRoute.value); - const depth = inject(viewDepthKey, 0); - const matchedRouteRef = computed(() => routeToDisplay.value.matched[depth]); - provide(viewDepthKey, depth + 1); - provide(matchedRouteKey, matchedRouteRef); - provide(routerViewLocationKey, routeToDisplay); - const viewRef = ref(); - // watch at the same time the component instance, the route record we are - // rendering, and the name - watch(() => [viewRef.value, matchedRouteRef.value, props.name], ([instance, to, name], [oldInstance, from, oldName]) => { - // copy reused instances - if (to) { - // this will update the instance for new instances as well as reused - // instances when navigating to a new route - to.instances[name] = instance; - // the component instance is reused for a different route or name so - // we copy any saved update or leave guards. With async setup, the - // mounting component will mount before the matchedRoute changes, - // making instance === oldInstance, so we check if guards have been - // added before. This works because we remove guards when - // unmounting/deactivating components - if (from && from !== to && instance && instance === oldInstance) { - if (!to.leaveGuards.size) { - to.leaveGuards = from.leaveGuards; - } - if (!to.updateGuards.size) { - to.updateGuards = from.updateGuards; - } - } - } - // trigger beforeRouteEnter next callbacks - if (instance && - to && - // if there is no instance but to and from are the same this might be - // the first visit - (!from || !isSameRouteRecord(to, from) || !oldInstance)) { - (to.enterCallbacks[name] || []).forEach(callback => callback(instance)); - } - }, { flush: 'post' }); - return () => { - const route = routeToDisplay.value; - const matchedRoute = matchedRouteRef.value; - const ViewComponent = matchedRoute && matchedRoute.components[props.name]; - // we need the value at the time we render because when we unmount, we - // navigated to a different location so the value is different - const currentName = props.name; - if (!ViewComponent) { - return normalizeSlot(slots.default, { Component: ViewComponent, route }); - } - // props from route configuration - const routePropsOption = matchedRoute.props[props.name]; - const routeProps = routePropsOption - ? routePropsOption === true - ? route.params - : typeof routePropsOption === 'function' - ? routePropsOption(route) - : routePropsOption - : null; - const onVnodeUnmounted = vnode => { - // remove the instance reference to prevent leak - if (vnode.component.isUnmounted) { - matchedRoute.instances[currentName] = null; - } - }; - const component = h(ViewComponent, assign({}, routeProps, attrs, { - onVnodeUnmounted, - ref: viewRef, - })); - if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) && - isBrowser && - component.ref) { - // TODO: can display if it's an alias, its props - const info = { - depth, - name: matchedRoute.name, - path: matchedRoute.path, - meta: matchedRoute.meta, - }; - const internalInstances = Array.isArray(component.ref) - ? component.ref.map(r => r.i) - : [component.ref.i]; - internalInstances.forEach(instance => { - // @ts-expect-error - instance.__vrv_devtools = info; - }); - } - return ( - // pass the vnode to the slot as a prop. - // h and both accept vnodes - normalizeSlot(slots.default, { Component: component, route }) || - component); - }; - }, -}); -function normalizeSlot(slot, data) { - if (!slot) - return null; - const slotContent = slot(data); - return slotContent.length === 1 ? slotContent[0] : slotContent; -} -// export the public type for h/tsx inference -// also to avoid inline import() in generated d.ts files -/** - * Component to display the current route the user is at. - */ -const RouterView = RouterViewImpl; -// warn against deprecated usage with & -// due to functional component being no longer eager in Vue 3 -function warnDeprecatedUsage() { - const instance = getCurrentInstance(); - const parentName = instance.parent && instance.parent.type.name; - if (parentName && - (parentName === 'KeepAlive' || parentName.includes('Transition'))) { - const comp = parentName === 'KeepAlive' ? 'keep-alive' : 'transition'; - warn(` can no longer be used directly inside or .\n` + - `Use slot props instead:\n\n` + - `\n` + - ` <${comp}>\n` + - ` \n` + - ` \n` + - ``); - } -} - -function formatRouteLocation(routeLocation, tooltip) { - const copy = assign({}, routeLocation, { - // remove variables that can contain vue instances - matched: routeLocation.matched.map(matched => omit(matched, ['instances', 'children', 'aliasOf'])), - }); - return { - _custom: { - type: null, - readOnly: true, - display: routeLocation.fullPath, - tooltip, - value: copy, - }, - }; -} -function formatDisplay(display) { - return { - _custom: { - display, - }, - }; -} -// to support multiple router instances -let routerId = 0; -function addDevtools(app, router, matcher) { - // Take over router.beforeEach and afterEach - // make sure we are not registering the devtool twice - if (router.__hasDevtools) - return; - router.__hasDevtools = true; - // increment to support multiple router instances - const id = routerId++; - setupDevtoolsPlugin({ - id: 'org.vuejs.router' + (id ? '.' + id : ''), - label: 'Vue Router', - packageName: 'vue-router', - homepage: 'https://router.vuejs.org', - logo: 'https://router.vuejs.org/logo.png', - componentStateTypes: ['Routing'], - app, - }, api => { - // display state added by the router - api.on.inspectComponent((payload, ctx) => { - if (payload.instanceData) { - payload.instanceData.state.push({ - type: 'Routing', - key: '$route', - editable: false, - value: formatRouteLocation(router.currentRoute.value, 'Current Route'), - }); - } - }); - // mark router-link as active and display tags on router views - api.on.visitComponentTree(({ treeNode: node, componentInstance }) => { - if (componentInstance.__vrv_devtools) { - const info = componentInstance.__vrv_devtools; - node.tags.push({ - label: (info.name ? `${info.name.toString()}: ` : '') + info.path, - textColor: 0, - tooltip: 'This component is rendered by <router-view>', - backgroundColor: PINK_500, - }); - } - // if multiple useLink are used - if (Array.isArray(componentInstance.__vrl_devtools)) { - componentInstance.__devtoolsApi = api; - componentInstance.__vrl_devtools.forEach(devtoolsData => { - let backgroundColor = ORANGE_400; - let tooltip = ''; - if (devtoolsData.isExactActive) { - backgroundColor = LIME_500; - tooltip = 'This is exactly active'; - } - else if (devtoolsData.isActive) { - backgroundColor = BLUE_600; - tooltip = 'This link is active'; - } - node.tags.push({ - label: devtoolsData.route.path, - textColor: 0, - tooltip, - backgroundColor, - }); - }); - } - }); - watch(router.currentRoute, () => { - // refresh active state - refreshRoutesView(); - api.notifyComponentUpdate(); - api.sendInspectorTree(routerInspectorId); - api.sendInspectorState(routerInspectorId); - }); - const navigationsLayerId = 'router:navigations:' + id; - api.addTimelineLayer({ - id: navigationsLayerId, - label: `Router${id ? ' ' + id : ''} Navigations`, - color: 0x40a8c4, - }); - // const errorsLayerId = 'router:errors' - // api.addTimelineLayer({ - // id: errorsLayerId, - // label: 'Router Errors', - // color: 0xea5455, - // }) - router.onError((error, to) => { - api.addTimelineEvent({ - layerId: navigationsLayerId, - event: { - title: 'Error during Navigation', - subtitle: to.fullPath, - logType: 'error', - time: api.now(), - data: { error }, - groupId: to.meta.__navigationId, - }, - }); - }); - // attached to `meta` and used to group events - let navigationId = 0; - router.beforeEach((to, from) => { - const data = { - guard: formatDisplay('beforeEach'), - from: formatRouteLocation(from, 'Current Location during this navigation'), - to: formatRouteLocation(to, 'Target location'), - }; - // Used to group navigations together, hide from devtools - Object.defineProperty(to.meta, '__navigationId', { - value: navigationId++, - }); - api.addTimelineEvent({ - layerId: navigationsLayerId, - event: { - time: api.now(), - title: 'Start of navigation', - subtitle: to.fullPath, - data, - groupId: to.meta.__navigationId, - }, - }); - }); - router.afterEach((to, from, failure) => { - const data = { - guard: formatDisplay('afterEach'), - }; - if (failure) { - data.failure = { - _custom: { - type: Error, - readOnly: true, - display: failure ? failure.message : '', - tooltip: 'Navigation Failure', - value: failure, - }, - }; - data.status = formatDisplay('❌'); - } - else { - data.status = formatDisplay('✅'); - } - // we set here to have the right order - data.from = formatRouteLocation(from, 'Current Location during this navigation'); - data.to = formatRouteLocation(to, 'Target location'); - api.addTimelineEvent({ - layerId: navigationsLayerId, - event: { - title: 'End of navigation', - subtitle: to.fullPath, - time: api.now(), - data, - logType: failure ? 'warning' : 'default', - groupId: to.meta.__navigationId, - }, - }); - }); - /** - * Inspector of Existing routes - */ - const routerInspectorId = 'router-inspector:' + id; - api.addInspector({ - id: routerInspectorId, - label: 'Routes' + (id ? ' ' + id : ''), - icon: 'book', - treeFilterPlaceholder: 'Search routes', - }); - function refreshRoutesView() { - // the routes view isn't active - if (!activeRoutesPayload) - return; - const payload = activeRoutesPayload; - // children routes will appear as nested - let routes = matcher.getRoutes().filter(route => !route.parent); - // reset match state to false - routes.forEach(resetMatchStateOnRouteRecord); - // apply a match state if there is a payload - if (payload.filter) { - routes = routes.filter(route => - // save matches state based on the payload - isRouteMatching(route, payload.filter.toLowerCase())); - } - // mark active routes - routes.forEach(route => markRouteRecordActive(route, router.currentRoute.value)); - payload.rootNodes = routes.map(formatRouteRecordForInspector); - } - let activeRoutesPayload; - api.on.getInspectorTree(payload => { - activeRoutesPayload = payload; - if (payload.app === app && payload.inspectorId === routerInspectorId) { - refreshRoutesView(); - } - }); - /** - * Display information about the currently selected route record - */ - api.on.getInspectorState(payload => { - if (payload.app === app && payload.inspectorId === routerInspectorId) { - const routes = matcher.getRoutes(); - const route = routes.find(route => route.record.__vd_id === payload.nodeId); - if (route) { - payload.state = { - options: formatRouteRecordMatcherForStateInspector(route), - }; - } - } - }); - api.sendInspectorTree(routerInspectorId); - api.sendInspectorState(routerInspectorId); - }); -} -function modifierForKey(key) { - if (key.optional) { - return key.repeatable ? '*' : '?'; - } - else { - return key.repeatable ? '+' : ''; - } -} -function formatRouteRecordMatcherForStateInspector(route) { - const { record } = route; - const fields = [ - { editable: false, key: 'path', value: record.path }, - ]; - if (record.name != null) { - fields.push({ - editable: false, - key: 'name', - value: record.name, - }); - } - fields.push({ editable: false, key: 'regexp', value: route.re }); - if (route.keys.length) { - fields.push({ - editable: false, - key: 'keys', - value: { - _custom: { - type: null, - readOnly: true, - display: route.keys - .map(key => `${key.name}${modifierForKey(key)}`) - .join(' '), - tooltip: 'Param keys', - value: route.keys, - }, - }, - }); - } - if (record.redirect != null) { - fields.push({ - editable: false, - key: 'redirect', - value: record.redirect, - }); - } - if (route.alias.length) { - fields.push({ - editable: false, - key: 'aliases', - value: route.alias.map(alias => alias.record.path), - }); - } - fields.push({ - key: 'score', - editable: false, - value: { - _custom: { - type: null, - readOnly: true, - display: route.score.map(score => score.join(', ')).join(' | '), - tooltip: 'Score used to sort routes', - value: route.score, - }, - }, - }); - return fields; -} -/** - * Extracted from tailwind palette - */ -const PINK_500 = 0xec4899; -const BLUE_600 = 0x2563eb; -const LIME_500 = 0x84cc16; -const CYAN_400 = 0x22d3ee; -const ORANGE_400 = 0xfb923c; -// const GRAY_100 = 0xf4f4f5 -const DARK = 0x666666; -function formatRouteRecordForInspector(route) { - const tags = []; - const { record } = route; - if (record.name != null) { - tags.push({ - label: String(record.name), - textColor: 0, - backgroundColor: CYAN_400, - }); - } - if (record.aliasOf) { - tags.push({ - label: 'alias', - textColor: 0, - backgroundColor: ORANGE_400, - }); - } - if (route.__vd_match) { - tags.push({ - label: 'matches', - textColor: 0, - backgroundColor: PINK_500, - }); - } - if (route.__vd_exactActive) { - tags.push({ - label: 'exact', - textColor: 0, - backgroundColor: LIME_500, - }); - } - if (route.__vd_active) { - tags.push({ - label: 'active', - textColor: 0, - backgroundColor: BLUE_600, - }); - } - if (record.redirect) { - tags.push({ - label: 'redirect: ' + - (typeof record.redirect === 'string' ? record.redirect : 'Object'), - textColor: 0xffffff, - backgroundColor: DARK, - }); - } - // add an id to be able to select it. Using the `path` is not possible because - // empty path children would collide with their parents - let id = record.__vd_id; - if (id == null) { - id = String(routeRecordId++); - record.__vd_id = id; - } - return { - id, - label: record.path, - tags, - children: route.children.map(formatRouteRecordForInspector), - }; -} -// incremental id for route records and inspector state -let routeRecordId = 0; -const EXTRACT_REGEXP_RE = /^\/(.*)\/([a-z]*)$/; -function markRouteRecordActive(route, currentRoute) { - // no route will be active if matched is empty - // reset the matching state - const isExactActive = currentRoute.matched.length && - isSameRouteRecord(currentRoute.matched[currentRoute.matched.length - 1], route.record); - route.__vd_exactActive = route.__vd_active = isExactActive; - if (!isExactActive) { - route.__vd_active = currentRoute.matched.some(match => isSameRouteRecord(match, route.record)); - } - route.children.forEach(childRoute => markRouteRecordActive(childRoute, currentRoute)); -} -function resetMatchStateOnRouteRecord(route) { - route.__vd_match = false; - route.children.forEach(resetMatchStateOnRouteRecord); -} -function isRouteMatching(route, filter) { - const found = String(route.re).match(EXTRACT_REGEXP_RE); - route.__vd_match = false; - if (!found || found.length < 3) { - return false; - } - // use a regexp without $ at the end to match nested routes better - const nonEndingRE = new RegExp(found[1].replace(/\$$/, ''), found[2]); - if (nonEndingRE.test(filter)) { - // mark children as matches - route.children.forEach(child => isRouteMatching(child, filter)); - // exception case: `/` - if (route.record.path !== '/' || filter === '/') { - route.__vd_match = route.re.test(filter); - return true; - } - // hide the / route - return false; - } - const path = route.record.path.toLowerCase(); - const decodedPath = decode(path); - // also allow partial matching on the path - if (!filter.startsWith('/') && - (decodedPath.includes(filter) || path.includes(filter))) - return true; - if (decodedPath.startsWith(filter) || path.startsWith(filter)) - return true; - if (route.record.name && String(route.record.name).includes(filter)) - return true; - return route.children.some(child => isRouteMatching(child, filter)); -} -function omit(obj, keys) { - const ret = {}; - for (const key in obj) { - if (!keys.includes(key)) { - // @ts-expect-error - ret[key] = obj[key]; - } - } - return ret; -} - -/** - * Creates a Router instance that can be used by a Vue app. - * - * @param options - {@link RouterOptions} - */ -function createRouter(options) { - const matcher = createRouterMatcher(options.routes, options); - const parseQuery$1 = options.parseQuery || parseQuery; - const stringifyQuery$1 = options.stringifyQuery || stringifyQuery; - const routerHistory = options.history; - if ((process.env.NODE_ENV !== 'production') && !routerHistory) - throw new Error('Provide the "history" option when calling "createRouter()":' + - ' https://next.router.vuejs.org/api/#history.'); - const beforeGuards = useCallbacks(); - const beforeResolveGuards = useCallbacks(); - const afterGuards = useCallbacks(); - const currentRoute = shallowRef(START_LOCATION_NORMALIZED); - let pendingLocation = START_LOCATION_NORMALIZED; - // leave the scrollRestoration if no scrollBehavior is provided - if (isBrowser && options.scrollBehavior && 'scrollRestoration' in history) { - history.scrollRestoration = 'manual'; - } - const normalizeParams = applyToParams.bind(null, paramValue => '' + paramValue); - const encodeParams = applyToParams.bind(null, encodeParam); - const decodeParams = - // @ts-expect-error: intentionally avoid the type check - applyToParams.bind(null, decode); - function addRoute(parentOrRoute, route) { - let parent; - let record; - if (isRouteName(parentOrRoute)) { - parent = matcher.getRecordMatcher(parentOrRoute); - record = route; - } - else { - record = parentOrRoute; - } - return matcher.addRoute(record, parent); - } - function removeRoute(name) { - const recordMatcher = matcher.getRecordMatcher(name); - if (recordMatcher) { - matcher.removeRoute(recordMatcher); - } - else if ((process.env.NODE_ENV !== 'production')) { - warn(`Cannot remove non-existent route "${String(name)}"`); - } - } - function getRoutes() { - return matcher.getRoutes().map(routeMatcher => routeMatcher.record); - } - function hasRoute(name) { - return !!matcher.getRecordMatcher(name); - } - function resolve(rawLocation, currentLocation) { - // const objectLocation = routerLocationAsObject(rawLocation) - // we create a copy to modify it later - currentLocation = assign({}, currentLocation || currentRoute.value); - if (typeof rawLocation === 'string') { - const locationNormalized = parseURL(parseQuery$1, rawLocation, currentLocation.path); - const matchedRoute = matcher.resolve({ path: locationNormalized.path }, currentLocation); - const href = routerHistory.createHref(locationNormalized.fullPath); - if ((process.env.NODE_ENV !== 'production')) { - if (href.startsWith('//')) - warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`); - else if (!matchedRoute.matched.length) { - warn(`No match found for location with path "${rawLocation}"`); - } - } - // locationNormalized is always a new object - return assign(locationNormalized, matchedRoute, { - params: decodeParams(matchedRoute.params), - hash: decode(locationNormalized.hash), - redirectedFrom: undefined, - href, - }); - } - let matcherLocation; - // path could be relative in object as well - if ('path' in rawLocation) { - if ((process.env.NODE_ENV !== 'production') && - 'params' in rawLocation && - !('name' in rawLocation) && - // @ts-expect-error: the type is never - Object.keys(rawLocation.params).length) { - warn(`Path "${ - // @ts-expect-error: the type is never - rawLocation.path}" was passed with params but they will be ignored. Use a named route alongside params instead.`); - } - matcherLocation = assign({}, rawLocation, { - path: parseURL(parseQuery$1, rawLocation.path, currentLocation.path).path, - }); - } - else { - // remove any nullish param - const targetParams = assign({}, rawLocation.params); - for (const key in targetParams) { - if (targetParams[key] == null) { - delete targetParams[key]; - } - } - // pass encoded values to the matcher so it can produce encoded path and fullPath - matcherLocation = assign({}, rawLocation, { - params: encodeParams(rawLocation.params), - }); - // current location params are decoded, we need to encode them in case the - // matcher merges the params - currentLocation.params = encodeParams(currentLocation.params); - } - const matchedRoute = matcher.resolve(matcherLocation, currentLocation); - const hash = rawLocation.hash || ''; - if ((process.env.NODE_ENV !== 'production') && hash && !hash.startsWith('#')) { - warn(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`); - } - // decoding them) the matcher might have merged current location params so - // we need to run the decoding again - matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params)); - const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, { - hash: encodeHash(hash), - path: matchedRoute.path, - })); - const href = routerHistory.createHref(fullPath); - if ((process.env.NODE_ENV !== 'production')) { - if (href.startsWith('//')) { - warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`); - } - else if (!matchedRoute.matched.length) { - warn(`No match found for location with path "${'path' in rawLocation ? rawLocation.path : rawLocation}"`); - } - } - return assign({ - fullPath, - // keep the hash encoded so fullPath is effectively path + encodedQuery + - // hash - hash, - query: - // if the user is using a custom query lib like qs, we might have - // nested objects, so we keep the query as is, meaning it can contain - // numbers at `$route.query`, but at the point, the user will have to - // use their own type anyway. - // https://github.com/vuejs/router/issues/328#issuecomment-649481567 - stringifyQuery$1 === stringifyQuery - ? normalizeQuery(rawLocation.query) - : (rawLocation.query || {}), - }, matchedRoute, { - redirectedFrom: undefined, - href, - }); - } - function locationAsObject(to) { - return typeof to === 'string' - ? parseURL(parseQuery$1, to, currentRoute.value.path) - : assign({}, to); - } - function checkCanceledNavigation(to, from) { - if (pendingLocation !== to) { - return createRouterError(8 /* NAVIGATION_CANCELLED */, { - from, - to, - }); - } - } - function push(to) { - return pushWithRedirect(to); - } - function replace(to) { - return push(assign(locationAsObject(to), { replace: true })); - } - function handleRedirectRecord(to) { - const lastMatched = to.matched[to.matched.length - 1]; - if (lastMatched && lastMatched.redirect) { - const { redirect } = lastMatched; - let newTargetLocation = typeof redirect === 'function' ? redirect(to) : redirect; - if (typeof newTargetLocation === 'string') { - newTargetLocation = - newTargetLocation.includes('?') || newTargetLocation.includes('#') - ? (newTargetLocation = locationAsObject(newTargetLocation)) - : // force empty params - { path: newTargetLocation }; - // @ts-expect-error: force empty params when a string is passed to let - // the router parse them again - newTargetLocation.params = {}; - } - if ((process.env.NODE_ENV !== 'production') && - !('path' in newTargetLocation) && - !('name' in newTargetLocation)) { - warn(`Invalid redirect found:\n${JSON.stringify(newTargetLocation, null, 2)}\n when navigating to "${to.fullPath}". A redirect must contain a name or path. This will break in production.`); - throw new Error('Invalid redirect'); - } - return assign({ - query: to.query, - hash: to.hash, - params: to.params, - }, newTargetLocation); - } - } - function pushWithRedirect(to, redirectedFrom) { - const targetLocation = (pendingLocation = resolve(to)); - const from = currentRoute.value; - const data = to.state; - const force = to.force; - // to could be a string where `replace` is a function - const replace = to.replace === true; - const shouldRedirect = handleRedirectRecord(targetLocation); - if (shouldRedirect) - return pushWithRedirect(assign(locationAsObject(shouldRedirect), { - state: data, - force, - replace, - }), - // keep original redirectedFrom if it exists - redirectedFrom || targetLocation); - // if it was a redirect we already called `pushWithRedirect` above - const toLocation = targetLocation; - toLocation.redirectedFrom = redirectedFrom; - let failure; - if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) { - failure = createRouterError(16 /* NAVIGATION_DUPLICATED */, { to: toLocation, from }); - // trigger scroll to allow scrolling to the same anchor - handleScroll(from, from, - // this is a push, the only way for it to be triggered from a - // history.listen is with a redirect, which makes it become a push - true, - // This cannot be the first navigation because the initial location - // cannot be manually navigated to - false); - } - return (failure ? Promise.resolve(failure) : navigate(toLocation, from)) - .catch((error) => isNavigationFailure(error) - ? // navigation redirects still mark the router as ready - isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */) - ? error - : markAsReady(error) // also returns the error - : // reject any unknown error - triggerError(error, toLocation, from)) - .then((failure) => { - if (failure) { - if (isNavigationFailure(failure, 2 /* NAVIGATION_GUARD_REDIRECT */)) { - if ((process.env.NODE_ENV !== 'production') && - // we are redirecting to the same location we were already at - isSameRouteLocation(stringifyQuery$1, resolve(failure.to), toLocation) && - // and we have done it a couple of times - redirectedFrom && - // @ts-expect-error: added only in dev - (redirectedFrom._count = redirectedFrom._count - ? // @ts-expect-error - redirectedFrom._count + 1 - : 1) > 10) { - warn(`Detected an infinite redirection in a navigation guard when going from "${from.fullPath}" to "${toLocation.fullPath}". Aborting to avoid a Stack Overflow. This will break in production if not fixed.`); - return Promise.reject(new Error('Infinite redirect in navigation guard')); - } - return pushWithRedirect( - // keep options - assign(locationAsObject(failure.to), { - state: data, - force, - replace, - }), - // preserve the original redirectedFrom if any - redirectedFrom || toLocation); - } - } - else { - // if we fail we don't finalize the navigation - failure = finalizeNavigation(toLocation, from, true, replace, data); - } - triggerAfterEach(toLocation, from, failure); - return failure; - }); - } - /** - * Helper to reject and skip all navigation guards if a new navigation happened - * @param to - * @param from - */ - function checkCanceledNavigationAndReject(to, from) { - const error = checkCanceledNavigation(to, from); - return error ? Promise.reject(error) : Promise.resolve(); - } - // TODO: refactor the whole before guards by internally using router.beforeEach - function navigate(to, from) { - let guards; - const [leavingRecords, updatingRecords, enteringRecords] = extractChangingRecords(to, from); - // all components here have been resolved once because we are leaving - guards = extractComponentsGuards(leavingRecords.reverse(), 'beforeRouteLeave', to, from); - // leavingRecords is already reversed - for (const record of leavingRecords) { - record.leaveGuards.forEach(guard => { - guards.push(guardToPromiseFn(guard, to, from)); - }); - } - const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from); - guards.push(canceledNavigationCheck); - // run the queue of per route beforeRouteLeave guards - return (runGuardQueue(guards) - .then(() => { - // check global guards beforeEach - guards = []; - for (const guard of beforeGuards.list()) { - guards.push(guardToPromiseFn(guard, to, from)); - } - guards.push(canceledNavigationCheck); - return runGuardQueue(guards); - }) - .then(() => { - // check in components beforeRouteUpdate - guards = extractComponentsGuards(updatingRecords, 'beforeRouteUpdate', to, from); - for (const record of updatingRecords) { - record.updateGuards.forEach(guard => { - guards.push(guardToPromiseFn(guard, to, from)); - }); - } - guards.push(canceledNavigationCheck); - // run the queue of per route beforeEnter guards - return runGuardQueue(guards); - }) - .then(() => { - // check the route beforeEnter - guards = []; - for (const record of to.matched) { - // do not trigger beforeEnter on reused views - if (record.beforeEnter && !from.matched.includes(record)) { - if (Array.isArray(record.beforeEnter)) { - for (const beforeEnter of record.beforeEnter) - guards.push(guardToPromiseFn(beforeEnter, to, from)); - } - else { - guards.push(guardToPromiseFn(record.beforeEnter, to, from)); - } - } - } - guards.push(canceledNavigationCheck); - // run the queue of per route beforeEnter guards - return runGuardQueue(guards); - }) - .then(() => { - // NOTE: at this point to.matched is normalized and does not contain any () => Promise - // clear existing enterCallbacks, these are added by extractComponentsGuards - to.matched.forEach(record => (record.enterCallbacks = {})); - // check in-component beforeRouteEnter - guards = extractComponentsGuards(enteringRecords, 'beforeRouteEnter', to, from); - guards.push(canceledNavigationCheck); - // run the queue of per route beforeEnter guards - return runGuardQueue(guards); - }) - .then(() => { - // check global guards beforeResolve - guards = []; - for (const guard of beforeResolveGuards.list()) { - guards.push(guardToPromiseFn(guard, to, from)); - } - guards.push(canceledNavigationCheck); - return runGuardQueue(guards); - }) - // catch any navigation canceled - .catch(err => isNavigationFailure(err, 8 /* NAVIGATION_CANCELLED */) - ? err - : Promise.reject(err))); - } - function triggerAfterEach(to, from, failure) { - // navigation is confirmed, call afterGuards - // TODO: wrap with error handlers - for (const guard of afterGuards.list()) - guard(to, from, failure); - } - /** - * - Cleans up any navigation guards - * - Changes the url if necessary - * - Calls the scrollBehavior - */ - function finalizeNavigation(toLocation, from, isPush, replace, data) { - // a more recent navigation took place - const error = checkCanceledNavigation(toLocation, from); - if (error) - return error; - // only consider as push if it's not the first navigation - const isFirstNavigation = from === START_LOCATION_NORMALIZED; - const state = !isBrowser ? {} : history.state; - // change URL only if the user did a push/replace and if it's not the initial navigation because - // it's just reflecting the url - if (isPush) { - // on the initial navigation, we want to reuse the scroll position from - // history state if it exists - if (replace || isFirstNavigation) - routerHistory.replace(toLocation.fullPath, assign({ - scroll: isFirstNavigation && state && state.scroll, - }, data)); - else - routerHistory.push(toLocation.fullPath, data); - } - // accept current navigation - currentRoute.value = toLocation; - handleScroll(toLocation, from, isPush, isFirstNavigation); - markAsReady(); - } - let removeHistoryListener; - // attach listener to history to trigger navigations - function setupListeners() { - // avoid setting up listeners twice due to an invalid first navigation - if (removeHistoryListener) - return; - removeHistoryListener = routerHistory.listen((to, _from, info) => { - // cannot be a redirect route because it was in history - const toLocation = resolve(to); - // due to dynamic routing, and to hash history with manual navigation - // (manually changing the url or calling history.hash = '#/somewhere'), - // there could be a redirect record in history - const shouldRedirect = handleRedirectRecord(toLocation); - if (shouldRedirect) { - pushWithRedirect(assign(shouldRedirect, { replace: true }), toLocation).catch(noop); - return; - } - pendingLocation = toLocation; - const from = currentRoute.value; - // TODO: should be moved to web history? - if (isBrowser) { - saveScrollPosition(getScrollKey(from.fullPath, info.delta), computeScrollPosition()); - } - navigate(toLocation, from) - .catch((error) => { - if (isNavigationFailure(error, 4 /* NAVIGATION_ABORTED */ | 8 /* NAVIGATION_CANCELLED */)) { - return error; - } - if (isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */)) { - // Here we could call if (info.delta) routerHistory.go(-info.delta, - // false) but this is bug prone as we have no way to wait the - // navigation to be finished before calling pushWithRedirect. Using - // a setTimeout of 16ms seems to work but there is not guarantee for - // it to work on every browser. So Instead we do not restore the - // history entry and trigger a new navigation as requested by the - // navigation guard. - // the error is already handled by router.push we just want to avoid - // logging the error - pushWithRedirect(error.to, toLocation - // avoid an uncaught rejection, let push call triggerError - ) - .then(failure => { - // manual change in hash history #916 ending up in the URL not - // changing but it was changed by the manual url change, so we - // need to manually change it ourselves - if (isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ | - 16 /* NAVIGATION_DUPLICATED */) && - !info.delta && - info.type === NavigationType.pop) { - routerHistory.go(-1, false); - } - }) - .catch(noop); - // avoid the then branch - return Promise.reject(); - } - // do not restore history on unknown direction - if (info.delta) - routerHistory.go(-info.delta, false); - // unrecognized error, transfer to the global handler - return triggerError(error, toLocation, from); - }) - .then((failure) => { - failure = - failure || - finalizeNavigation( - // after navigation, all matched components are resolved - toLocation, from, false); - // revert the navigation - if (failure) { - if (info.delta) { - routerHistory.go(-info.delta, false); - } - else if (info.type === NavigationType.pop && - isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ | 16 /* NAVIGATION_DUPLICATED */)) { - // manual change in hash history #916 - // it's like a push but lacks the information of the direction - routerHistory.go(-1, false); - } - } - triggerAfterEach(toLocation, from, failure); - }) - .catch(noop); - }); - } - // Initialization and Errors - let readyHandlers = useCallbacks(); - let errorHandlers = useCallbacks(); - let ready; - /** - * Trigger errorHandlers added via onError and throws the error as well - * - * @param error - error to throw - * @param to - location we were navigating to when the error happened - * @param from - location we were navigating from when the error happened - * @returns the error as a rejected promise - */ - function triggerError(error, to, from) { - markAsReady(error); - const list = errorHandlers.list(); - if (list.length) { - list.forEach(handler => handler(error, to, from)); - } - else { - if ((process.env.NODE_ENV !== 'production')) { - warn('uncaught error during route navigation:'); - } - console.error(error); - } - return Promise.reject(error); - } - function isReady() { - if (ready && currentRoute.value !== START_LOCATION_NORMALIZED) - return Promise.resolve(); - return new Promise((resolve, reject) => { - readyHandlers.add([resolve, reject]); - }); - } - function markAsReady(err) { - if (!ready) { - // still not ready if an error happened - ready = !err; - setupListeners(); - readyHandlers - .list() - .forEach(([resolve, reject]) => (err ? reject(err) : resolve())); - readyHandlers.reset(); - } - return err; - } - // Scroll behavior - function handleScroll(to, from, isPush, isFirstNavigation) { - const { scrollBehavior } = options; - if (!isBrowser || !scrollBehavior) - return Promise.resolve(); - const scrollPosition = (!isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0))) || - ((isFirstNavigation || !isPush) && - history.state && - history.state.scroll) || - null; - return nextTick() - .then(() => scrollBehavior(to, from, scrollPosition)) - .then(position => position && scrollToPosition(position)) - .catch(err => triggerError(err, to, from)); - } - const go = (delta) => routerHistory.go(delta); - let started; - const installedApps = new Set(); - const router = { - currentRoute, - addRoute, - removeRoute, - hasRoute, - getRoutes, - resolve, - options, - push, - replace, - go, - back: () => go(-1), - forward: () => go(1), - beforeEach: beforeGuards.add, - beforeResolve: beforeResolveGuards.add, - afterEach: afterGuards.add, - onError: errorHandlers.add, - isReady, - install(app) { - const router = this; - app.component('RouterLink', RouterLink); - app.component('RouterView', RouterView); - app.config.globalProperties.$router = router; - Object.defineProperty(app.config.globalProperties, '$route', { - enumerable: true, - get: () => unref(currentRoute), - }); - // this initial navigation is only necessary on client, on server it doesn't - // make sense because it will create an extra unnecessary navigation and could - // lead to problems - if (isBrowser && - // used for the initial navigation client side to avoid pushing - // multiple times when the router is used in multiple apps - !started && - currentRoute.value === START_LOCATION_NORMALIZED) { - // see above - started = true; - push(routerHistory.location).catch(err => { - if ((process.env.NODE_ENV !== 'production')) - warn('Unexpected error when starting the router:', err); - }); - } - const reactiveRoute = {}; - for (const key in START_LOCATION_NORMALIZED) { - // @ts-expect-error: the key matches - reactiveRoute[key] = computed(() => currentRoute.value[key]); - } - app.provide(routerKey, router); - app.provide(routeLocationKey, reactive(reactiveRoute)); - app.provide(routerViewLocationKey, currentRoute); - const unmountApp = app.unmount; - installedApps.add(app); - app.unmount = function () { - installedApps.delete(app); - // the router is not attached to an app anymore - if (installedApps.size < 1) { - // invalidate the current navigation - pendingLocation = START_LOCATION_NORMALIZED; - removeHistoryListener && removeHistoryListener(); - removeHistoryListener = null; - currentRoute.value = START_LOCATION_NORMALIZED; - started = false; - ready = false; - } - unmountApp(); - }; - if (((process.env.NODE_ENV !== 'production') || __VUE_PROD_DEVTOOLS__) && isBrowser) { - addDevtools(app, router, matcher); - } - }, - }; - return router; -} -function runGuardQueue(guards) { - return guards.reduce((promise, guard) => promise.then(() => guard()), Promise.resolve()); -} -function extractChangingRecords(to, from) { - const leavingRecords = []; - const updatingRecords = []; - const enteringRecords = []; - const len = Math.max(from.matched.length, to.matched.length); - for (let i = 0; i < len; i++) { - const recordFrom = from.matched[i]; - if (recordFrom) { - if (to.matched.find(record => isSameRouteRecord(record, recordFrom))) - updatingRecords.push(recordFrom); - else - leavingRecords.push(recordFrom); - } - const recordTo = to.matched[i]; - if (recordTo) { - // the type doesn't matter because we are comparing per reference - if (!from.matched.find(record => isSameRouteRecord(record, recordTo))) { - enteringRecords.push(recordTo); - } - } - } - return [leavingRecords, updatingRecords, enteringRecords]; -} - -/** - * Returns the router instance. Equivalent to using `$router` inside - * templates. - */ -function useRouter() { - return inject(routerKey); -} -/** - * Returns the current route location. Equivalent to using `$route` inside - * templates. - */ -function useRoute() { - return inject(routeLocationKey); -} - -export { NavigationFailureType, RouterLink, RouterView, START_LOCATION_NORMALIZED as START_LOCATION, createMemoryHistory, createRouter, createRouterMatcher, createWebHashHistory, createWebHistory, isNavigationFailure, matchedRouteKey, onBeforeRouteLeave, onBeforeRouteUpdate, parseQuery, routeLocationKey, routerKey, routerViewLocationKey, stringifyQuery, useLink, useRoute, useRouter, viewDepthKey }; +export * from '../dist/vue-router.mjs' \ No newline at end of file diff --git a/node_modules/vue-router/dist/vue-router.global.js b/node_modules/vue-router/dist/vue-router.global.js index e1c5cd2..6e56ecc 100644 --- a/node_modules/vue-router/dist/vue-router.global.js +++ b/node_modules/vue-router/dist/vue-router.global.js @@ -1,70 +1,33 @@ /*! - * vue-router v4.0.15 + * vue-router v4.1.5 * (c) 2022 Eduardo San Martin Morote * @license MIT */ var VueRouter = (function (exports, vue) { 'use strict'; - const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - const PolySymbol = (name) => - // vr = vue router - hasSymbol - ? Symbol('[vue-router]: ' + name ) - : ('[vue-router]: ' ) + name; - // rvlm = Router View Location Matched - /** - * RouteRecord being rendered by the closest ancestor Router View. Used for - * `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View - * Location Matched - * - * @internal - */ - const matchedRouteKey = /*#__PURE__*/ PolySymbol('router view location matched' ); - /** - * Allows overriding the router view depth to control which component in - * `matched` is rendered. rvd stands for Router View Depth - * - * @internal - */ - const viewDepthKey = /*#__PURE__*/ PolySymbol('router view depth' ); - /** - * Allows overriding the router instance returned by `useRouter` in tests. r - * stands for router - * - * @internal - */ - const routerKey = /*#__PURE__*/ PolySymbol('router' ); - /** - * Allows overriding the current route returned by `useRoute` in tests. rl - * stands for route location - * - * @internal - */ - const routeLocationKey = /*#__PURE__*/ PolySymbol('route location' ); - /** - * Allows overriding the current route used by router-view. Internally this is - * used when the `route` prop is passed. - * - * @internal - */ - const routerViewLocationKey = /*#__PURE__*/ PolySymbol('router view location' ); - const isBrowser = typeof window !== 'undefined'; function isESModule(obj) { - return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module'); + return obj.__esModule || obj[Symbol.toStringTag] === 'Module'; } const assign = Object.assign; function applyToParams(fn, params) { const newParams = {}; for (const key in params) { const value = params[key]; - newParams[key] = Array.isArray(value) ? value.map(fn) : fn(value); + newParams[key] = isArray(value) + ? value.map(fn) + : fn(value); } return newParams; } const noop = () => { }; + /** + * Typesafe alternative to Array.isArray + * https://github.com/microsoft/TypeScript/pull/48228 + */ + const isArray = Array.isArray; function warn(msg) { // avoid using ...args as it breaks in older Edge builds @@ -75,7 +38,7 @@ var VueRouter = (function (exports, vue) { const TRAILING_SLASH_RE = /\/$/; const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, ''); /** - * Transforms an URI into a normalized history location + * Transforms a URI into a normalized history location * * @param parseQuery * @param location - URI to normalize @@ -86,8 +49,13 @@ var VueRouter = (function (exports, vue) { function parseURL(parseQuery, location, currentLocation = '/') { let path, query = {}, searchString = '', hash = ''; // Could use URL and URLSearchParams but IE 11 doesn't support it - const searchPos = location.indexOf('?'); - const hashPos = location.indexOf('#', searchPos > -1 ? searchPos : 0); + // TODO: move to new URL() + const hashPos = location.indexOf('#'); + let searchPos = location.indexOf('?'); + // the hash appears before the search, so it's not part of the search string + if (hashPos < searchPos && hashPos >= 0) { + searchPos = -1; + } if (searchPos > -1) { path = location.slice(0, searchPos); searchString = location.slice(searchPos + 1, hashPos > -1 ? hashPos : location.length); @@ -119,8 +87,7 @@ var VueRouter = (function (exports, vue) { return location.path + (query && '?') + query + (location.hash || ''); } /** - * Strips off the base from the beginning of a location.pathname in a non - * case-sensitive way. + * Strips off the base from the beginning of a location.pathname in a non-case-sensitive way. * * @param pathname - location.pathname * @param base - base to strip off @@ -172,9 +139,9 @@ var VueRouter = (function (exports, vue) { return true; } function isSameRouteLocationParamsValue(a, b) { - return Array.isArray(a) + return isArray(a) ? isEquivalentArray(a, b) - : Array.isArray(b) + : isArray(b) ? isEquivalentArray(b, a) : a === b; } @@ -186,7 +153,7 @@ var VueRouter = (function (exports, vue) { * @param b - array of values or a single value */ function isEquivalentArray(a, b) { - return Array.isArray(b) + return isArray(b) ? a.length === b.length && a.every((value, i) => value === b[i]) : a.length === 1 && a[0] === b; } @@ -212,18 +179,24 @@ var VueRouter = (function (exports, vue) { let segment; for (toPosition = 0; toPosition < toSegments.length; toPosition++) { segment = toSegments[toPosition]; - // can't go below zero - if (position === 1 || segment === '.') + // we stay on the same position + if (segment === '.') continue; - if (segment === '..') - position--; - // found something that is not relative path + // go up in the from array + if (segment === '..') { + // we can't go below zero, but we still need to increment toPosition + if (position > 1) + position--; + // continue + } + // we reached a non-relative path, we stop here else break; } return (fromSegments.slice(0, position).join('/') + '/' + toSegments + // ensure we use at least the last element in the toSegments .slice(toPosition - (toPosition === toSegments.length ? 1 : 0)) .join('/')); } @@ -452,7 +425,7 @@ var VueRouter = (function (exports, vue) { pauseState = currentLocation.value; } function listen(callback) { - // setup the listener and prepare teardown callbacks + // set up the listener and prepare teardown callbacks listeners.push(callback); const teardown = () => { const index = listeners.indexOf(callback); @@ -475,7 +448,7 @@ var VueRouter = (function (exports, vue) { window.removeEventListener('popstate', popStateHandler); window.removeEventListener('beforeunload', beforeUnloadListener); } - // setup the listeners and prepare teardown callbacks + // set up the listeners and prepare teardown callbacks window.addEventListener('popstate', popStateHandler); window.addEventListener('beforeunload', beforeUnloadListener); return { @@ -513,14 +486,14 @@ var VueRouter = (function (exports, vue) { // the length is off by one, we need to decrease it position: history.length - 1, replaced: true, - // don't add a scroll as the user may have an anchor and we want + // don't add a scroll as the user may have an anchor, and we want // scrollBehavior to be triggered without a saved position scroll: null, }, true); } function changeLocation(to, state, replace) { /** - * if a base tag is provided and we are on a normal domain, we have to + * if a base tag is provided, and we are on a normal domain, we have to * respect the provided `base` attribute because pushState() will use it and * potentially erase anything before the `#` like at * https://github.com/vuejs/router/issues/685 where a base of @@ -616,7 +589,7 @@ var VueRouter = (function (exports, vue) { } /** - * Creates a in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere. + * Creates an in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere. * It's up to the user to replace that location with the starter location by either calling `router.push` or `router.replace`. * * @param base - Base applied to all urls, defaults to '/' @@ -701,15 +674,13 @@ var VueRouter = (function (exports, vue) { } /** - * Creates a hash history. Useful for web applications with no host (e.g. - * `file://`) or when configuring a server to handle any URL is not possible. + * Creates a hash history. Useful for web applications with no host (e.g. `file://`) or when configuring a server to + * handle any URL is not possible. * - * @param base - optional base to provide. Defaults to `location.pathname + - * location.search` If there is a `` tag in the `head`, its value will be - * ignored in favor of this parameter **but note it affects all the - * history.pushState() calls**, meaning that if you use a `` tag, it's - * `href` value **has to match this parameter** (ignoring anything after the - * `#`). + * @param base - optional base to provide. Defaults to `location.pathname + location.search` If there is a `` tag + * in the `head`, its value will be ignored in favor of this parameter **but note it affects all the history.pushState() + * calls**, meaning that if you use a `` tag, it's `href` value **has to match this parameter** (ignoring anything + * after the `#`). * * @example * ```js @@ -774,7 +745,7 @@ var VueRouter = (function (exports, vue) { redirectedFrom: undefined, }; - const NavigationFailureSymbol = /*#__PURE__*/ PolySymbol('navigation failure' ); + const NavigationFailureSymbol = Symbol('navigation failure' ); /** * Enumeration with all possible types for navigation failures. Can be passed to * {@link isNavigationFailure} to check for specific failures. @@ -799,21 +770,21 @@ var VueRouter = (function (exports, vue) { })(exports.NavigationFailureType || (exports.NavigationFailureType = {})); // DEV only debug messages const ErrorTypeMessages = { - [1 /* MATCHER_NOT_FOUND */]({ location, currentLocation }) { + [1 /* ErrorTypes.MATCHER_NOT_FOUND */]({ location, currentLocation }) { return `No match for\n ${JSON.stringify(location)}${currentLocation ? '\nwhile being at\n' + JSON.stringify(currentLocation) : ''}`; }, - [2 /* NAVIGATION_GUARD_REDIRECT */]({ from, to, }) { + [2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */]({ from, to, }) { return `Redirected from "${from.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`; }, - [4 /* NAVIGATION_ABORTED */]({ from, to }) { + [4 /* ErrorTypes.NAVIGATION_ABORTED */]({ from, to }) { return `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`; }, - [8 /* NAVIGATION_CANCELLED */]({ from, to }) { + [8 /* ErrorTypes.NAVIGATION_CANCELLED */]({ from, to }) { return `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`; }, - [16 /* NAVIGATION_DUPLICATED */]({ from, to }) { + [16 /* ErrorTypes.NAVIGATION_DUPLICATED */]({ from, to }) { return `Avoided redundant navigation to current location: "${from.fullPath}".`; }, }; @@ -845,7 +816,7 @@ var VueRouter = (function (exports, vue) { return JSON.stringify(location, null, 2); } - // default pattern for a param: non greedy everything but / + // default pattern for a param: non-greedy everything but / const BASE_PARAM_PATTERN = '[^/]+?'; const BASE_PATH_PARSER_OPTIONS = { sensitive: false, @@ -872,23 +843,23 @@ var VueRouter = (function (exports, vue) { const keys = []; for (const segment of segments) { // the root segment needs special treatment - const segmentScores = segment.length ? [] : [90 /* Root */]; + const segmentScores = segment.length ? [] : [90 /* PathScore.Root */]; // allow trailing slash if (options.strict && !segment.length) pattern += '/'; for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) { const token = segment[tokenIndex]; - // resets the score if we are inside a sub segment /:a-other-:b - let subSegmentScore = 40 /* Segment */ + - (options.sensitive ? 0.25 /* BonusCaseSensitive */ : 0); - if (token.type === 0 /* Static */) { + // resets the score if we are inside a sub-segment /:a-other-:b + let subSegmentScore = 40 /* PathScore.Segment */ + + (options.sensitive ? 0.25 /* PathScore.BonusCaseSensitive */ : 0); + if (token.type === 0 /* TokenType.Static */) { // prepend the slash if we are starting a new segment if (!tokenIndex) pattern += '/'; pattern += token.value.replace(REGEX_CHARS_RE, '\\$&'); - subSegmentScore += 40 /* Static */; + subSegmentScore += 40 /* PathScore.Static */; } - else if (token.type === 1 /* Param */) { + else if (token.type === 1 /* TokenType.Param */) { const { value, repeatable, optional, regexp } = token; keys.push({ name: value, @@ -898,7 +869,7 @@ var VueRouter = (function (exports, vue) { const re = regexp ? regexp : BASE_PARAM_PATTERN; // the user provided a custom regexp /:id(\\d+) if (re !== BASE_PARAM_PATTERN) { - subSegmentScore += 10 /* BonusCustomRegExp */; + subSegmentScore += 10 /* PathScore.BonusCustomRegExp */; // make sure the regexp is valid before using it try { new RegExp(`(${re})`); @@ -921,13 +892,13 @@ var VueRouter = (function (exports, vue) { if (optional) subPattern += '?'; pattern += subPattern; - subSegmentScore += 20 /* Dynamic */; + subSegmentScore += 20 /* PathScore.Dynamic */; if (optional) - subSegmentScore += -8 /* BonusOptional */; + subSegmentScore += -8 /* PathScore.BonusOptional */; if (repeatable) - subSegmentScore += -20 /* BonusRepeatable */; + subSegmentScore += -20 /* PathScore.BonusRepeatable */; if (re === '.*') - subSegmentScore += -50 /* BonusWildcard */; + subSegmentScore += -50 /* PathScore.BonusWildcard */; } segmentScores.push(subSegmentScore); } @@ -938,7 +909,7 @@ var VueRouter = (function (exports, vue) { // only apply the strict bonus to the last score if (options.strict && options.end) { const i = score.length - 1; - score[i][score[i].length - 1] += 0.7000000000000001 /* BonusStrict */; + score[i][score[i].length - 1] += 0.7000000000000001 /* PathScore.BonusStrict */; } // TODO: dev only warn double trailing slash if (!options.strict) @@ -970,20 +941,22 @@ var VueRouter = (function (exports, vue) { path += '/'; avoidDuplicatedSlash = false; for (const token of segment) { - if (token.type === 0 /* Static */) { + if (token.type === 0 /* TokenType.Static */) { path += token.value; } - else if (token.type === 1 /* Param */) { + else if (token.type === 1 /* TokenType.Param */) { const { value, repeatable, optional } = token; const param = value in params ? params[value] : ''; - if (Array.isArray(param) && !repeatable) + if (isArray(param) && !repeatable) { throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`); - const text = Array.isArray(param) ? param.join('/') : param; + } + const text = isArray(param) + ? param.join('/') + : param; if (!text) { if (optional) { - // if we have more than one optional param like /:a?-static and there are more segments, we don't need to - // care about the optional param - if (segment.length < 2 && segments.length > 1) { + // if we have more than one optional param like /:a?-static we don't need to care about the optional param + if (segment.length < 2) { // remove the last slash as we could be at the end if (path.endsWith('/')) path = path.slice(0, -1); @@ -999,7 +972,8 @@ var VueRouter = (function (exports, vue) { } } } - return path; + // avoid empty path when we have multiple optional params + return path || '/'; } return { re, @@ -1030,12 +1004,12 @@ var VueRouter = (function (exports, vue) { // if the last subsegment was Static, the shorter segments should be sorted first // otherwise sort the longest segment first if (a.length < b.length) { - return a.length === 1 && a[0] === 40 /* Static */ + 40 /* Segment */ + return a.length === 1 && a[0] === 40 /* PathScore.Static */ + 40 /* PathScore.Segment */ ? -1 : 1; } else if (a.length > b.length) { - return b.length === 1 && b[0] === 40 /* Static */ + 40 /* Segment */ + return b.length === 1 && b[0] === 40 /* PathScore.Static */ + 40 /* PathScore.Segment */ ? 1 : -1; } @@ -1059,6 +1033,12 @@ var VueRouter = (function (exports, vue) { return comp; i++; } + if (Math.abs(bScore.length - aScore.length) === 1) { + if (isLastScoreNegative(aScore)) + return 1; + if (isLastScoreNegative(bScore)) + return -1; + } // if a and b share the same score entries but b has more, sort b first return bScore.length - aScore.length; // this is the ternary version @@ -1068,9 +1048,19 @@ var VueRouter = (function (exports, vue) { // ? -1 // : 0 } + /** + * This allows detecting splats at the end of a path: /home/:id(.*)* + * + * @param score - score to check + * @returns true if the last entry is negative + */ + function isLastScoreNegative(score) { + const last = score[score.length - 1]; + return score.length > 0 && last[last.length - 1] < 0; + } const ROOT_TOKEN = { - type: 0 /* Static */, + type: 0 /* TokenType.Static */, value: '', }; const VALID_PARAM_RE = /[a-zA-Z0-9_]/; @@ -1090,7 +1080,7 @@ var VueRouter = (function (exports, vue) { function crash(message) { throw new Error(`ERR (${state})/"${buffer}": ${message}`); } - let state = 0 /* Static */; + let state = 0 /* TokenizerState.Static */; let previousState = state; const tokens = []; // the segment will always be valid because we get into the initial state @@ -1112,19 +1102,19 @@ var VueRouter = (function (exports, vue) { function consumeBuffer() { if (!buffer) return; - if (state === 0 /* Static */) { + if (state === 0 /* TokenizerState.Static */) { segment.push({ - type: 0 /* Static */, + type: 0 /* TokenType.Static */, value: buffer, }); } - else if (state === 1 /* Param */ || - state === 2 /* ParamRegExp */ || - state === 3 /* ParamRegExpEnd */) { + else if (state === 1 /* TokenizerState.Param */ || + state === 2 /* TokenizerState.ParamRegExp */ || + state === 3 /* TokenizerState.ParamRegExpEnd */) { if (segment.length > 1 && (char === '*' || char === '+')) crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`); segment.push({ - type: 1 /* Param */, + type: 1 /* TokenType.Param */, value: buffer, regexp: customRe, repeatable: char === '*' || char === '+', @@ -1141,13 +1131,13 @@ var VueRouter = (function (exports, vue) { } while (i < path.length) { char = path[i++]; - if (char === '\\' && state !== 2 /* ParamRegExp */) { + if (char === '\\' && state !== 2 /* TokenizerState.ParamRegExp */) { previousState = state; - state = 4 /* EscapeNext */; + state = 4 /* TokenizerState.EscapeNext */; continue; } switch (state) { - case 0 /* Static */: + case 0 /* TokenizerState.Static */: if (char === '/') { if (buffer) { consumeBuffer(); @@ -1156,32 +1146,32 @@ var VueRouter = (function (exports, vue) { } else if (char === ':') { consumeBuffer(); - state = 1 /* Param */; + state = 1 /* TokenizerState.Param */; } else { addCharToBuffer(); } break; - case 4 /* EscapeNext */: + case 4 /* TokenizerState.EscapeNext */: addCharToBuffer(); state = previousState; break; - case 1 /* Param */: + case 1 /* TokenizerState.Param */: if (char === '(') { - state = 2 /* ParamRegExp */; + state = 2 /* TokenizerState.ParamRegExp */; } else if (VALID_PARAM_RE.test(char)) { addCharToBuffer(); } else { consumeBuffer(); - state = 0 /* Static */; + state = 0 /* TokenizerState.Static */; // go back one character if we were not modifying if (char !== '*' && char !== '?' && char !== '+') i--; } break; - case 2 /* ParamRegExp */: + case 2 /* TokenizerState.ParamRegExp */: // TODO: is it worth handling nested regexp? like :p(?:prefix_([^/]+)_suffix) // it already works by escaping the closing ) // https://paths.esm.dev/?p=AAMeJbiAwQEcDKbAoAAkP60PG2R6QAvgNaA6AFACM2ABuQBB# @@ -1192,16 +1182,16 @@ var VueRouter = (function (exports, vue) { if (customRe[customRe.length - 1] == '\\') customRe = customRe.slice(0, -1) + char; else - state = 3 /* ParamRegExpEnd */; + state = 3 /* TokenizerState.ParamRegExpEnd */; } else { customRe += char; } break; - case 3 /* ParamRegExpEnd */: + case 3 /* TokenizerState.ParamRegExpEnd */: // same as finalizing a param consumeBuffer(); - state = 0 /* Static */; + state = 0 /* TokenizerState.Static */; // go back one character if we were not modifying if (char !== '*' && char !== '?' && char !== '+') i--; @@ -1212,7 +1202,7 @@ var VueRouter = (function (exports, vue) { break; } } - if (state === 2 /* ParamRegExp */) + if (state === 2 /* TokenizerState.ParamRegExp */) crash(`Unfinished custom RegExp for param "${buffer}"`); consumeBuffer(); finalizeSegment(); @@ -1267,6 +1257,9 @@ var VueRouter = (function (exports, vue) { // used later on to remove by name const isRootAdd = !originalRecord; const mainNormalizedRecord = normalizeRouteRecord(record); + { + checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent); + } // we might be the child of an alias mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record; const options = mergeOptions(globalOptions, record); @@ -1310,11 +1303,11 @@ var VueRouter = (function (exports, vue) { throw new Error('Catch all routes ("*") must now be defined using a param with a custom regexp.\n' + 'See more at https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes.'); } - // create the object before hand so it can be passed to children + // create the object beforehand, so it can be passed to children matcher = createRouteRecordMatcher(normalizedRecord, parent, options); if (parent && path[0] === '/') checkMissingParamsInAbsolutePath(matcher, parent); - // if we are an alias we must tell the original record that we exist + // if we are an alias we must tell the original record that we exist, // so we can be removed if (originalRecord) { originalRecord.alias.push(matcher); @@ -1332,14 +1325,14 @@ var VueRouter = (function (exports, vue) { if (isRootAdd && record.name && !isAliasRecord(matcher)) removeRoute(record.name); } - if ('children' in mainNormalizedRecord) { + if (mainNormalizedRecord.children) { const children = mainNormalizedRecord.children; for (let i = 0; i < children.length; i++) { addRoute(children[i], matcher, originalRecord && originalRecord.children[i]); } } // if there was no original record, then the first one was not an alias and all - // other alias (if any) need to reference this record when adding children + // other aliases (if any) need to reference this record when adding children originalRecord = originalRecord || matcher; // TODO: add normalized records for more flexibility // if (parent && isAliasRecord(originalRecord)) { @@ -1400,16 +1393,27 @@ var VueRouter = (function (exports, vue) { if ('name' in location && location.name) { matcher = matcherMap.get(location.name); if (!matcher) - throw createRouterError(1 /* MATCHER_NOT_FOUND */, { + throw createRouterError(1 /* ErrorTypes.MATCHER_NOT_FOUND */, { location, }); + // warn if the user is passing invalid params so they can debug it better when they get removed + { + const invalidParams = Object.keys(location.params || {}).filter(paramName => !matcher.keys.find(k => k.name === paramName)); + if (invalidParams.length) { + warn(`Discarded invalid param(s) "${invalidParams.join('", "')}" when navigating. See https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22 for more details.`); + } + } name = matcher.record.name; params = assign( // paramsFromLocation is a new object paramsFromLocation(currentLocation.params, // only keep params that exist in the resolved location // TODO: only keep optional params coming from a parent record - matcher.keys.filter(k => !k.optional).map(k => k.name)), location.params); + matcher.keys.filter(k => !k.optional).map(k => k.name)), + // discard any existing params in the current location that do not exist here + // #1497 this ensures better active/exact matching + location.params && + paramsFromLocation(location.params, matcher.keys.map(k => k.name))); // throws if cannot be stringified path = matcher.stringify(params); } @@ -1423,7 +1427,6 @@ var VueRouter = (function (exports, vue) { matcher = matchers.find(m => m.re.test(path)); // matcher should have a value after the loop if (matcher) { - // TODO: dev warning of unused params if provided // we know the matcher works because we tested the regexp params = matcher.parse(path); name = matcher.record.name; @@ -1436,7 +1439,7 @@ var VueRouter = (function (exports, vue) { ? matcherMap.get(currentLocation.name) : matchers.find(m => m.re.test(currentLocation.path)); if (!matcher) - throw createRouterError(1 /* MATCHER_NOT_FOUND */, { + throw createRouterError(1 /* ErrorTypes.MATCHER_NOT_FOUND */, { location, currentLocation, }); @@ -1494,8 +1497,8 @@ var VueRouter = (function (exports, vue) { updateGuards: new Set(), enterCallbacks: {}, components: 'components' in record - ? record.components || {} - : { default: record.component }, + ? record.components || null + : record.component && { default: record.component }, }; } /** @@ -1505,7 +1508,7 @@ var VueRouter = (function (exports, vue) { */ function normalizeRecordProps(record) { const propsObject = {}; - // props does not exist on redirect records but we can set false directly + // props does not exist on redirect records, but we can set false directly const props = record.props || false; if ('component' in record) { propsObject.default = props; @@ -1559,17 +1562,31 @@ var VueRouter = (function (exports, vue) { function checkSameParams(a, b) { for (const key of a.keys) { if (!key.optional && !b.keys.find(isSameParam.bind(null, key))) - return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`); + return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`); } for (const key of b.keys) { if (!key.optional && !a.keys.find(isSameParam.bind(null, key))) - return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" should have the exact same param named "${key.name}"`); + return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`); + } + } + /** + * A route with a name and a child with an empty path without a name should warn when adding the route + * + * @param mainNormalizedRecord - RouteRecordNormalized + * @param parent - RouteRecordMatcher + */ + function checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent) { + if (parent && + parent.record.name && + !mainNormalizedRecord.name && + !mainNormalizedRecord.path) { + warn(`The route named "${String(parent.record.name)}" has a child without a name and an empty path. Using that name won't render the empty path child so you probably want to move the name to the child instead. If this is intentional, add a name to the child route to remove the warning.`); } } function checkMissingParamsInAbsolutePath(record, parent) { for (const key of parent.keys) { if (!record.keys.find(isSameParam.bind(null, key))) - return warn(`Absolute path "${record.record.path}" should have the exact same param named "${key.name}" as its parent "${parent.record.path}".`); + return warn(`Absolute path "${record.record.path}" must have the exact same param named "${key.name}" as its parent "${parent.record.path}".`); } } function isRecordChildOf(record, parent) { @@ -1583,7 +1600,7 @@ var VueRouter = (function (exports, vue) { * On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2) * defines some extra characters to be encoded. Most browsers do not encode them * in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to - * also encode `!'()*`. Leaving unencoded only ASCII alphanumeric(`a-zA-Z0-9`) + * also encode `!'()*`. Leaving un-encoded only ASCII alphanumeric(`a-zA-Z0-9`) * plus `-._~`. This extra safety should be applied to query by patching the * string returned by encodeURIComponent encodeURI also encodes `[\]^`. `\` * should be encoded to avoid ambiguity. Browsers (IE, FF, C) transform a `\` @@ -1607,7 +1624,7 @@ var VueRouter = (function (exports, vue) { * application/x-www-form-urlencoded * (https://url.spec.whatwg.org/#urlencoded-parsing) and most browsers seems lo * leave the plus character as is in queries. To be more flexible, we allow the - * plus character on the query but it can also be manually encoded by the user. + * plus character on the query, but it can also be manually encoded by the user. * * Resources: * - https://url.spec.whatwg.org/#urlencoded-parsing @@ -1739,7 +1756,7 @@ var VueRouter = (function (exports, vue) { if (key in query) { // an extra variable for ts types let currentValue = query[key]; - if (!Array.isArray(currentValue)) { + if (!isArray(currentValue)) { currentValue = query[key] = [currentValue]; } currentValue.push(value); @@ -1772,7 +1789,7 @@ var VueRouter = (function (exports, vue) { continue; } // keep null values - const values = Array.isArray(value) + const values = isArray(value) ? value.map(v => v && encodeQueryValue(v)) : [value && encodeQueryValue(value)]; values.forEach(value => { @@ -1801,7 +1818,7 @@ var VueRouter = (function (exports, vue) { for (const key in query) { const value = query[key]; if (value !== undefined) { - normalizedQuery[key] = Array.isArray(value) + normalizedQuery[key] = isArray(value) ? value.map(v => (v == null ? null : '' + v)) : value == null ? value @@ -1811,6 +1828,43 @@ var VueRouter = (function (exports, vue) { return normalizedQuery; } + /** + * RouteRecord being rendered by the closest ancestor Router View. Used for + * `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View + * Location Matched + * + * @internal + */ + const matchedRouteKey = Symbol('router view location matched' ); + /** + * Allows overriding the router view depth to control which component in + * `matched` is rendered. rvd stands for Router View Depth + * + * @internal + */ + const viewDepthKey = Symbol('router view depth' ); + /** + * Allows overriding the router instance returned by `useRouter` in tests. r + * stands for router + * + * @internal + */ + const routerKey = Symbol('router' ); + /** + * Allows overriding the current route returned by `useRoute` in tests. rl + * stands for route location + * + * @internal + */ + const routeLocationKey = Symbol('route location' ); + /** + * Allows overriding the current route used by router-view. Internally this is + * used when the `route` prop is passed. + * + * @internal + */ + const routerViewLocationKey = Symbol('router view location' ); + /** * Create a list of callbacks that can be reset. Used to create before and after navigation guards list */ @@ -1861,7 +1915,7 @@ var VueRouter = (function (exports, vue) { // to avoid warning {}).value; if (!activeRecord) { - warn('No active route record was found when calling `onBeforeRouteLeave()`. Make sure you call this function inside of a component child of . Maybe you called it inside of App.vue?'); + warn('No active route record was found when calling `onBeforeRouteLeave()`. Make sure you call this function inside a component child of . Maybe you called it inside of App.vue?'); return; } registerGuard(activeRecord, 'leaveGuards', leaveGuard); @@ -1882,7 +1936,7 @@ var VueRouter = (function (exports, vue) { // to avoid warning {}).value; if (!activeRecord) { - warn('No active route record was found when calling `onBeforeRouteUpdate()`. Make sure you call this function inside of a component child of . Maybe you called it inside of App.vue?'); + warn('No active route record was found when calling `onBeforeRouteUpdate()`. Make sure you call this function inside a component child of . Maybe you called it inside of App.vue?'); return; } registerGuard(activeRecord, 'updateGuards', updateGuard); @@ -1894,16 +1948,17 @@ var VueRouter = (function (exports, vue) { (record.enterCallbacks[name] = record.enterCallbacks[name] || []); return () => new Promise((resolve, reject) => { const next = (valid) => { - if (valid === false) - reject(createRouterError(4 /* NAVIGATION_ABORTED */, { + if (valid === false) { + reject(createRouterError(4 /* ErrorTypes.NAVIGATION_ABORTED */, { from, to, })); + } else if (valid instanceof Error) { reject(valid); } else if (isRouteLocation(valid)) { - reject(createRouterError(2 /* NAVIGATION_GUARD_REDIRECT */, { + reject(createRouterError(2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */, { from: to, to: valid, })); @@ -1912,8 +1967,9 @@ var VueRouter = (function (exports, vue) { if (enterCallbackArray && // since enterCallbackArray is truthy, both record and name also are record.enterCallbacks[name] === enterCallbackArray && - typeof valid === 'function') + typeof valid === 'function') { enterCallbackArray.push(valid); + } resolve(); } }; @@ -1933,7 +1989,6 @@ var VueRouter = (function (exports, vue) { } return resolvedValue; }); - // TODO: test me! } else if (guardReturn !== undefined) { // @ts-expect-error: _called is added at canOnlyBeCalledOnce @@ -1961,6 +2016,10 @@ var VueRouter = (function (exports, vue) { function extractComponentsGuards(matched, guardType, to, from) { const guards = []; for (const record of matched) { + if (!record.components && !record.children.length) { + warn(`Record with path "${record.path}" is either missing a "component(s)"` + + ` or "children" property.`); + } for (const name in record.components) { let rawComponent = record.components[name]; { @@ -2017,6 +2076,7 @@ var VueRouter = (function (exports, vue) { ? resolved.default : resolved; // replace the function with the resolved component + // cannot be null or undefined because we went into the for loop record.components[name] = resolvedComponent; // __vccOpts is added by vue-class-component and contain the regular options const options = resolvedComponent.__vccOpts || resolvedComponent; @@ -2030,6 +2090,7 @@ var VueRouter = (function (exports, vue) { } /** * Allows differentiating lazy components from functional components and vue-class-component + * @internal * * @param component */ @@ -2039,6 +2100,34 @@ var VueRouter = (function (exports, vue) { 'props' in component || '__vccOpts' in component); } + /** + * Ensures a route is loaded, so it can be passed as o prop to ``. + * + * @param route - resolved route to load + */ + function loadRouteLocation(route) { + return route.matched.every(record => record.redirect) + ? Promise.reject(new Error('Cannot load a route that redirects.')) + : Promise.all(route.matched.map(record => record.components && + Promise.all(Object.keys(record.components).reduce((promises, name) => { + const rawComponent = record.components[name]; + if (typeof rawComponent === 'function' && + !('displayName' in rawComponent)) { + promises.push(rawComponent().then(resolved => { + if (!resolved) + return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}". Ensure you passed a function that returns a promise.`)); + const resolvedComponent = isESModule(resolved) + ? resolved.default + : resolved; + // replace the function with the resolved component + // cannot be null or undefined because we went into the for loop + record.components[name] = resolvedComponent; + return; + })); + } + return promises; + }, [])))).then(() => route); + } // TODO: we could allow currentRoute as a prop to expose `isActive` and // `isExactActive` behavior should go through an RFC @@ -2113,6 +2202,7 @@ var VueRouter = (function (exports, vue) { } const RouterLinkImpl = /*#__PURE__*/ vue.defineComponent({ name: 'RouterLink', + compatConfig: { MODE: 3 }, props: { to: { type: [String, Object], @@ -2151,7 +2241,7 @@ var VueRouter = (function (exports, vue) { : null, href: link.href, // this would override user added attrs but Vue will still add - // the listener so we end up triggering both + // the listener, so we end up triggering both onClick: link.navigate, class: elClass.value, }, children); @@ -2196,7 +2286,7 @@ var VueRouter = (function (exports, vue) { return false; } else { - if (!Array.isArray(outerValue) || + if (!isArray(outerValue) || outerValue.length !== innerValue.length || innerValue.some((value, i) => value !== outerValue[i])) return false; @@ -2241,9 +2331,21 @@ var VueRouter = (function (exports, vue) { warnDeprecatedUsage(); const injectedRoute = vue.inject(routerViewLocationKey); const routeToDisplay = vue.computed(() => props.route || injectedRoute.value); - const depth = vue.inject(viewDepthKey, 0); - const matchedRouteRef = vue.computed(() => routeToDisplay.value.matched[depth]); - vue.provide(viewDepthKey, depth + 1); + const injectedDepth = vue.inject(viewDepthKey, 0); + // The depth changes based on empty components option, which allows passthrough routes e.g. routes with children + // that are used to reuse the `path` property + const depth = vue.computed(() => { + let initialDepth = vue.unref(injectedDepth); + const { matched } = routeToDisplay.value; + let matchedRoute; + while ((matchedRoute = matched[initialDepth]) && + !matchedRoute.components) { + initialDepth++; + } + return initialDepth; + }); + const matchedRouteRef = vue.computed(() => routeToDisplay.value.matched[depth.value]); + vue.provide(viewDepthKey, vue.computed(() => depth.value + 1)); vue.provide(matchedRouteKey, matchedRouteRef); vue.provide(routerViewLocationKey, routeToDisplay); const viewRef = vue.ref(); @@ -2255,7 +2357,7 @@ var VueRouter = (function (exports, vue) { // this will update the instance for new instances as well as reused // instances when navigating to a new route to.instances[name] = instance; - // the component instance is reused for a different route or name so + // the component instance is reused for a different route or name, so // we copy any saved update or leave guards. With async setup, the // mounting component will mount before the matchedRoute changes, // making instance === oldInstance, so we check if guards have been @@ -2281,16 +2383,16 @@ var VueRouter = (function (exports, vue) { }, { flush: 'post' }); return () => { const route = routeToDisplay.value; - const matchedRoute = matchedRouteRef.value; - const ViewComponent = matchedRoute && matchedRoute.components[props.name]; // we need the value at the time we render because when we unmount, we // navigated to a different location so the value is different const currentName = props.name; + const matchedRoute = matchedRouteRef.value; + const ViewComponent = matchedRoute && matchedRoute.components[currentName]; if (!ViewComponent) { return normalizeSlot(slots.default, { Component: ViewComponent, route }); } // props from route configuration - const routePropsOption = matchedRoute.props[props.name]; + const routePropsOption = matchedRoute.props[currentName]; const routeProps = routePropsOption ? routePropsOption === true ? route.params @@ -2312,12 +2414,12 @@ var VueRouter = (function (exports, vue) { component.ref) { // TODO: can display if it's an alias, its props const info = { - depth, + depth: depth.value, name: matchedRoute.name, path: matchedRoute.path, meta: matchedRoute.meta, }; - const internalInstances = Array.isArray(component.ref) + const internalInstances = isArray(component.ref) ? component.ref.map(r => r.i) : [component.ref.i]; internalInstances.forEach(instance => { @@ -2379,6 +2481,30 @@ var VueRouter = (function (exports, vue) { const HOOK_SETUP = 'devtools-plugin:setup'; const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set'; + let supported; + let perf; + function isPerformanceSupported() { + var _a; + if (supported !== undefined) { + return supported; + } + if (typeof window !== 'undefined' && window.performance) { + supported = true; + perf = window.performance; + } + else if (typeof global !== 'undefined' && ((_a = global.perf_hooks) === null || _a === void 0 ? void 0 : _a.performance)) { + supported = true; + perf = global.perf_hooks.performance; + } + else { + supported = false; + } + return supported; + } + function now() { + return isPerformanceSupported() ? perf.now() : Date.now(); + } + class ApiProxy { constructor(plugin, hook) { this.target = null; @@ -2416,6 +2542,9 @@ var VueRouter = (function (exports, vue) { } currentSettings = value; }, + now() { + return now(); + }, }; if (hook) { hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => { @@ -2503,6 +2632,13 @@ var VueRouter = (function (exports, vue) { } } + /** + * Copies a route location and removes any problematic properties that cannot be shown in devtools (e.g. Vue instances). + * + * @param routeLocation - routeLocation to format + * @param tooltip - optional tooltip + * @returns a copy of the routeLocation + */ function formatRouteLocation(routeLocation, tooltip) { const copy = assign({}, routeLocation, { // remove variables that can contain vue instances @@ -2544,6 +2680,9 @@ var VueRouter = (function (exports, vue) { componentStateTypes: ['Routing'], app, }, api => { + if (typeof api.now !== 'function') { + console.warn('[Vue Router]: You seem to be using an outdated version of Vue Devtools. Are you still using the Beta release instead of the stable one? You can find the links at https://devtools.vuejs.org/guide/installation.html.'); + } // display state added by the router api.on.inspectComponent((payload, ctx) => { if (payload.instanceData) { @@ -2567,7 +2706,7 @@ var VueRouter = (function (exports, vue) { }); } // if multiple useLink are used - if (Array.isArray(componentInstance.__vrl_devtools)) { + if (isArray(componentInstance.__vrl_devtools)) { componentInstance.__devtoolsApi = api; componentInstance.__vrl_devtools.forEach(devtoolsData => { let backgroundColor = ORANGE_400; @@ -2784,6 +2923,13 @@ var VueRouter = (function (exports, vue) { value: route.alias.map(alias => alias.record.path), }); } + if (Object.keys(route.record.meta).length) { + fields.push({ + editable: false, + key: 'meta', + value: route.record.meta, + }); + } fields.push({ key: 'score', editable: false, @@ -2849,8 +2995,9 @@ var VueRouter = (function (exports, vue) { } if (record.redirect) { tags.push({ - label: 'redirect: ' + - (typeof record.redirect === 'string' ? record.redirect : 'Object'), + label: typeof record.redirect === 'string' + ? `redirect: ${record.redirect}` + : 'redirects', textColor: 0xffffff, backgroundColor: DARK, }); @@ -3029,7 +3176,7 @@ var VueRouter = (function (exports, vue) { delete targetParams[key]; } } - // pass encoded values to the matcher so it can produce encoded path and fullPath + // pass encoded values to the matcher, so it can produce encoded path and fullPath matcherLocation = assign({}, rawLocation, { params: encodeParams(rawLocation.params), }); @@ -3042,7 +3189,7 @@ var VueRouter = (function (exports, vue) { if (hash && !hash.startsWith('#')) { warn(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`); } - // decoding them) the matcher might have merged current location params so + // the matcher might have merged current location params, so // we need to run the decoding again matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params)); const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, { @@ -3084,7 +3231,7 @@ var VueRouter = (function (exports, vue) { } function checkCanceledNavigation(to, from) { if (pendingLocation !== to) { - return createRouterError(8 /* NAVIGATION_CANCELLED */, { + return createRouterError(8 /* ErrorTypes.NAVIGATION_CANCELLED */, { from, to, }); @@ -3119,7 +3266,8 @@ var VueRouter = (function (exports, vue) { return assign({ query: to.query, hash: to.hash, - params: to.params, + // avoid transferring params if the redirect has a path + params: 'path' in newTargetLocation ? {} : to.params, }, newTargetLocation); } } @@ -3133,7 +3281,9 @@ var VueRouter = (function (exports, vue) { const shouldRedirect = handleRedirectRecord(targetLocation); if (shouldRedirect) return pushWithRedirect(assign(locationAsObject(shouldRedirect), { - state: data, + state: typeof shouldRedirect === 'object' + ? assign({}, data, shouldRedirect.state) + : data, force, replace, }), @@ -3144,7 +3294,7 @@ var VueRouter = (function (exports, vue) { toLocation.redirectedFrom = redirectedFrom; let failure; if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) { - failure = createRouterError(16 /* NAVIGATION_DUPLICATED */, { to: toLocation, from }); + failure = createRouterError(16 /* ErrorTypes.NAVIGATION_DUPLICATED */, { to: toLocation, from }); // trigger scroll to allow scrolling to the same anchor handleScroll(from, from, // this is a push, the only way for it to be triggered from a @@ -3157,14 +3307,14 @@ var VueRouter = (function (exports, vue) { return (failure ? Promise.resolve(failure) : navigate(toLocation, from)) .catch((error) => isNavigationFailure(error) ? // navigation redirects still mark the router as ready - isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */) + isNavigationFailure(error, 2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */) ? error : markAsReady(error) // also returns the error : // reject any unknown error triggerError(error, toLocation, from)) .then((failure) => { if (failure) { - if (isNavigationFailure(failure, 2 /* NAVIGATION_GUARD_REDIRECT */)) { + if (isNavigationFailure(failure, 2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */)) { if (// we are redirecting to the same location we were already at isSameRouteLocation(stringifyQuery$1, resolve(failure.to), toLocation) && // and we have done it a couple of times @@ -3179,10 +3329,14 @@ var VueRouter = (function (exports, vue) { } return pushWithRedirect( // keep options - assign(locationAsObject(failure.to), { - state: data, - force, + assign({ + // preserve an existing replacement but allow the redirect to override it replace, + }, locationAsObject(failure.to), { + state: typeof failure.to === 'object' + ? assign({}, data, failure.to.state) + : data, + force, }), // preserve the original redirectedFrom if any redirectedFrom || toLocation); @@ -3248,7 +3402,7 @@ var VueRouter = (function (exports, vue) { for (const record of to.matched) { // do not trigger beforeEnter on reused views if (record.beforeEnter && !from.matched.includes(record)) { - if (Array.isArray(record.beforeEnter)) { + if (isArray(record.beforeEnter)) { for (const beforeEnter of record.beforeEnter) guards.push(guardToPromiseFn(beforeEnter, to, from)); } @@ -3281,7 +3435,7 @@ var VueRouter = (function (exports, vue) { return runGuardQueue(guards); }) // catch any navigation canceled - .catch(err => isNavigationFailure(err, 8 /* NAVIGATION_CANCELLED */) + .catch(err => isNavigationFailure(err, 8 /* ErrorTypes.NAVIGATION_CANCELLED */) ? err : Promise.reject(err))); } @@ -3328,6 +3482,8 @@ var VueRouter = (function (exports, vue) { if (removeHistoryListener) return; removeHistoryListener = routerHistory.listen((to, _from, info) => { + if (!router.listening) + return; // cannot be a redirect route because it was in history const toLocation = resolve(to); // due to dynamic routing, and to hash history with manual navigation @@ -3346,15 +3502,15 @@ var VueRouter = (function (exports, vue) { } navigate(toLocation, from) .catch((error) => { - if (isNavigationFailure(error, 4 /* NAVIGATION_ABORTED */ | 8 /* NAVIGATION_CANCELLED */)) { + if (isNavigationFailure(error, 4 /* ErrorTypes.NAVIGATION_ABORTED */ | 8 /* ErrorTypes.NAVIGATION_CANCELLED */)) { return error; } - if (isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */)) { + if (isNavigationFailure(error, 2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */)) { // Here we could call if (info.delta) routerHistory.go(-info.delta, // false) but this is bug prone as we have no way to wait the // navigation to be finished before calling pushWithRedirect. Using - // a setTimeout of 16ms seems to work but there is not guarantee for - // it to work on every browser. So Instead we do not restore the + // a setTimeout of 16ms seems to work but there is no guarantee for + // it to work on every browser. So instead we do not restore the // history entry and trigger a new navigation as requested by the // navigation guard. // the error is already handled by router.push we just want to avoid @@ -3364,10 +3520,10 @@ var VueRouter = (function (exports, vue) { ) .then(failure => { // manual change in hash history #916 ending up in the URL not - // changing but it was changed by the manual url change, so we + // changing, but it was changed by the manual url change, so we // need to manually change it ourselves - if (isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ | - 16 /* NAVIGATION_DUPLICATED */) && + if (isNavigationFailure(failure, 4 /* ErrorTypes.NAVIGATION_ABORTED */ | + 16 /* ErrorTypes.NAVIGATION_DUPLICATED */) && !info.delta && info.type === NavigationType.pop) { routerHistory.go(-1, false); @@ -3378,8 +3534,9 @@ var VueRouter = (function (exports, vue) { return Promise.reject(); } // do not restore history on unknown direction - if (info.delta) + if (info.delta) { routerHistory.go(-info.delta, false); + } // unrecognized error, transfer to the global handler return triggerError(error, toLocation, from); }) @@ -3391,11 +3548,14 @@ var VueRouter = (function (exports, vue) { toLocation, from, false); // revert the navigation if (failure) { - if (info.delta) { + if (info.delta && + // a new navigation has been triggered, so we do not want to revert, that will change the current history + // entry while a different route is displayed + !isNavigationFailure(failure, 8 /* ErrorTypes.NAVIGATION_CANCELLED */)) { routerHistory.go(-info.delta, false); } else if (info.type === NavigationType.pop && - isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ | 16 /* NAVIGATION_DUPLICATED */)) { + isNavigationFailure(failure, 4 /* ErrorTypes.NAVIGATION_ABORTED */ | 16 /* ErrorTypes.NAVIGATION_DUPLICATED */)) { // manual change in hash history #916 // it's like a push but lacks the information of the direction routerHistory.go(-1, false); @@ -3471,6 +3631,7 @@ var VueRouter = (function (exports, vue) { const installedApps = new Set(); const router = { currentRoute, + listening: true, addRoute, removeRoute, hasRoute, @@ -3534,6 +3695,7 @@ var VueRouter = (function (exports, vue) { } unmountApp(); }; + // TODO: this probably needs to be updated so it can be used by vue-termui if (isBrowser) { addDevtools(app, router, matcher); } @@ -3592,6 +3754,7 @@ var VueRouter = (function (exports, vue) { exports.createWebHashHistory = createWebHashHistory; exports.createWebHistory = createWebHistory; exports.isNavigationFailure = isNavigationFailure; + exports.loadRouteLocation = loadRouteLocation; exports.matchedRouteKey = matchedRouteKey; exports.onBeforeRouteLeave = onBeforeRouteLeave; exports.onBeforeRouteUpdate = onBeforeRouteUpdate; diff --git a/node_modules/vue-router/dist/vue-router.global.prod.js b/node_modules/vue-router/dist/vue-router.global.prod.js index 6fd0f9d..5a98c28 100644 --- a/node_modules/vue-router/dist/vue-router.global.prod.js +++ b/node_modules/vue-router/dist/vue-router.global.prod.js @@ -1,6 +1,6 @@ /*! - * vue-router v4.0.15 + * vue-router v4.1.5 * (c) 2022 Eduardo San Martin Morote * @license MIT */ -var VueRouter=function(e,t){"use strict";const n="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag,r=e=>n?Symbol(e):"_vr_"+e,o=r("rvlm"),a=r("rvd"),c=r("r"),s=r("rl"),i=r("rvl"),l="undefined"!=typeof window;const u=Object.assign;function f(e,t){const n={};for(const r in t){const o=t[r];n[r]=Array.isArray(o)?o.map(e):e(o)}return n}const p=()=>{},h=/\/$/;function d(e,t,n="/"){let r,o={},a="",c="";const s=t.indexOf("?"),i=t.indexOf("#",s>-1?s:0);return s>-1&&(r=t.slice(0,s),a=t.slice(s+1,i>-1?i:t.length),o=e(a)),i>-1&&(r=r||t.slice(0,i),c=t.slice(i,t.length)),r=function(e,t){if(e.startsWith("/"))return e;if(!e)return t;const n=t.split("/"),r=e.split("/");let o,a,c=n.length-1;for(o=0;oe===t[n])):1===e.length&&e[0]===t}var w,E;!function(e){e.pop="pop",e.push="push"}(w||(w={})),function(e){e.back="back",e.forward="forward",e.unknown=""}(E||(E={}));function R(e){if(!e)if(l){const t=document.querySelector("base");e=(e=t&&t.getAttribute("href")||"/").replace(/^\w+:\/\/[^\/]+/,"")}else e="/";return"/"!==e[0]&&"#"!==e[0]&&(e="/"+e),e.replace(h,"")}const A=/^[^#]+#/;function O(e,t){return e.replace(A,"#")+t}const k=()=>({left:window.pageXOffset,top:window.pageYOffset});function P(e){let t;if("el"in e){const n=e.el,r="string"==typeof n&&n.startsWith("#"),o="string"==typeof n?r?document.getElementById(n.slice(1)):document.querySelector(n):n;if(!o)return;t=function(e,t){const n=document.documentElement.getBoundingClientRect(),r=e.getBoundingClientRect();return{behavior:t.behavior,left:r.left-n.left-(t.left||0),top:r.top-n.top-(t.top||0)}}(o,e)}else t=e;"scrollBehavior"in document.documentElement.style?window.scrollTo(t):window.scrollTo(null!=t.left?t.left:window.pageXOffset,null!=t.top?t.top:window.pageYOffset)}function j(e,t){return(history.state?history.state.position-t:-1)+e}const x=new Map;let C=()=>location.protocol+"//"+location.host;function $(e,t){const{pathname:n,search:r,hash:o}=t,a=e.indexOf("#");if(a>-1){let t=o.includes(e.slice(a))?e.slice(a).length:1,n=o.slice(t);return"/"!==n[0]&&(n="/"+n),m(n,"")}return m(n,e)+r+o}function S(e,t,n,r=!1,o=!1){return{back:e,current:t,forward:n,replaced:r,position:window.history.length,scroll:o?k():null}}function L(e){const t=function(e){const{history:t,location:n}=window,r={value:$(e,n)},o={value:t.state};function a(r,a,c){const s=e.indexOf("#"),i=s>-1?(n.host&&document.querySelector("base")?e:e.slice(s))+r:C()+e+r;try{t[c?"replaceState":"pushState"](a,"",i),o.value=a}catch(e){console.error(e),n[c?"replace":"assign"](i)}}return o.value||a(r.value,{back:null,current:r.value,forward:null,position:t.length-1,replaced:!0,scroll:null},!0),{location:r,state:o,push:function(e,n){const c=u({},o.value,t.state,{forward:e,scroll:k()});a(c.current,c,!0),a(e,u({},S(r.value,e,null),{position:c.position+1},n),!1),r.value=e},replace:function(e,n){a(e,u({},t.state,S(o.value.back,e,o.value.forward,!0),n,{position:o.value.position}),!0),r.value=e}}}(e=R(e)),n=function(e,t,n,r){let o=[],a=[],c=null;const s=({state:a})=>{const s=$(e,location),i=n.value,l=t.value;let u=0;if(a){if(n.value=s,t.value=a,c&&c===i)return void(c=null);u=l?a.position-l.position:0}else r(s);o.forEach((e=>{e(n.value,i,{delta:u,type:w.pop,direction:u?u>0?E.forward:E.back:E.unknown})}))};function i(){const{history:e}=window;e.state&&e.replaceState(u({},e.state,{scroll:k()}),"")}return window.addEventListener("popstate",s),window.addEventListener("beforeunload",i),{pauseListeners:function(){c=n.value},listen:function(e){o.push(e);const t=()=>{const t=o.indexOf(e);t>-1&&o.splice(t,1)};return a.push(t),t},destroy:function(){for(const e of a)e();a=[],window.removeEventListener("popstate",s),window.removeEventListener("beforeunload",i)}}}(e,t.state,t.location,t.replace);const r=u({location:"",base:e,go:function(e,t=!0){t||n.pauseListeners(),history.go(e)},createHref:O.bind(null,e)},t,n);return Object.defineProperty(r,"location",{enumerable:!0,get:()=>t.location.value}),Object.defineProperty(r,"state",{enumerable:!0,get:()=>t.state.value}),r}function q(e){return"string"==typeof e||"symbol"==typeof e}const M={path:"/",name:void 0,params:{},query:{},hash:"",fullPath:"/",matched:[],meta:{},redirectedFrom:void 0},_=r("nf");var T;function B(e,t){return u(new Error,{type:e,[_]:!0},t)}function G(e,t){return e instanceof Error&&_ in e&&(null==t||!!(e.type&t))}e.NavigationFailureType=void 0,(T=e.NavigationFailureType||(e.NavigationFailureType={}))[T.aborted=4]="aborted",T[T.cancelled=8]="cancelled",T[T.duplicated=16]="duplicated";const F="[^/]+?",I={sensitive:!1,strict:!1,start:!0,end:!0},K=/[.+*?^${}()[\]/\\]/g;function U(e,t){let n=0;for(;nt.length?1===t.length&&80===t[0]?1:-1:0}function V(e,t){let n=0;const r=e.score,o=t.score;for(;n1&&(n.endsWith("/")?n=n.slice(0,-1):r=!0)}n+=u}}return n}}}(function(e){if(!e)return[[]];if("/"===e)return[[D]];if(!e.startsWith("/"))throw new Error(`Invalid path "${e}"`);function t(e){throw new Error(`ERR (${n})/"${l}": ${e}`)}let n=0,r=n;const o=[];let a;function c(){a&&o.push(a),a=[]}let s,i=0,l="",u="";function f(){l&&(0===n?a.push({type:0,value:l}):1===n||2===n||3===n?(a.length>1&&("*"===s||"+"===s)&&t(`A repeatable param (${l}) must be alone in its segment. eg: '/:ids+.`),a.push({type:1,value:l,regexp:u,repeatable:"*"===s||"+"===s,optional:"*"===s||"?"===s})):t("Invalid state to consume buffer"),l="")}function p(){l+=s}for(;i{a(d)}:p}function a(e){if(q(e)){const t=r.get(e);t&&(r.delete(e),n.splice(n.indexOf(t),1),t.children.forEach(a),t.alias.forEach(a))}else{const t=n.indexOf(e);t>-1&&(n.splice(t,1),e.record.name&&r.delete(e.record.name),e.children.forEach(a),e.alias.forEach(a))}}function c(e){let t=0;for(;t=0&&(e.record.path!==n[t].record.path||!Z(e,n[t]));)t++;n.splice(t,0,e),e.record.name&&!Q(e)&&r.set(e.record.name,e)}return t=Y({strict:!1,end:!0,sensitive:!1},t),e.forEach((e=>o(e))),{addRoute:o,resolve:function(e,t){let o,a,c,s={};if("name"in e&&e.name){if(o=r.get(e.name),!o)throw B(1,{location:e});c=o.record.name,s=u(function(e,t){const n={};for(const r of t)r in e&&(n[r]=e[r]);return n}(t.params,o.keys.filter((e=>!e.optional)).map((e=>e.name))),e.params),a=o.stringify(s)}else if("path"in e)a=e.path,o=n.find((e=>e.re.test(a))),o&&(s=o.parse(a),c=o.record.name);else{if(o=t.name?r.get(t.name):n.find((e=>e.re.test(t.path))),!o)throw B(1,{location:e,currentLocation:t});c=o.record.name,s=u({},t.params,e.params),a=o.stringify(s)}const i=[];let l=o;for(;l;)i.unshift(l.record),l=l.parent;return{name:c,path:a,params:s,matched:i,meta:X(i)}},removeRoute:a,getRoutes:function(){return n},getRecordMatcher:function(e){return r.get(e)}}}function z(e){const t={},n=e.props||!1;if("component"in e)t.default=n;else for(const r in e.components)t[r]="boolean"==typeof n?n:n[r];return t}function Q(e){for(;e;){if(e.record.aliasOf)return!0;e=e.parent}return!1}function X(e){return e.reduce(((e,t)=>u(e,t.meta)),{})}function Y(e,t){const n={};for(const r in e)n[r]=r in t?t[r]:e[r];return n}function Z(e,t){return t.children.some((t=>t===e||Z(e,t)))}const J=/#/g,ee=/&/g,te=/\//g,ne=/=/g,re=/\?/g,oe=/\+/g,ae=/%5B/g,ce=/%5D/g,se=/%5E/g,ie=/%60/g,le=/%7B/g,ue=/%7C/g,fe=/%7D/g,pe=/%20/g;function he(e){return encodeURI(""+e).replace(ue,"|").replace(ae,"[").replace(ce,"]")}function de(e){return he(e).replace(oe,"%2B").replace(pe,"+").replace(J,"%23").replace(ee,"%26").replace(ie,"`").replace(le,"{").replace(fe,"}").replace(se,"^")}function me(e){return null==e?"":function(e){return he(e).replace(J,"%23").replace(re,"%3F")}(e).replace(te,"%2F")}function ge(e){try{return decodeURIComponent(""+e)}catch(e){}return""+e}function ve(e){const t={};if(""===e||"?"===e)return t;const n=("?"===e[0]?e.slice(1):e).split("&");for(let e=0;ee&&de(e))):[r&&de(r)]).forEach((e=>{void 0!==e&&(t+=(t.length?"&":"")+n,null!=e&&(t+="="+e))}))}return t}function be(e){const t={};for(const n in e){const r=e[n];void 0!==r&&(t[n]=Array.isArray(r)?r.map((e=>null==e?null:""+e)):null==r?r:""+r)}return t}function we(){let e=[];return{add:function(t){return e.push(t),()=>{const n=e.indexOf(t);n>-1&&e.splice(n,1)}},list:()=>e,reset:function(){e=[]}}}function Ee(e,n,r){const o=()=>{e[n].delete(r)};t.onUnmounted(o),t.onDeactivated(o),t.onActivated((()=>{e[n].add(r)})),e[n].add(r)}function Re(e,t,n,r,o){const a=r&&(r.enterCallbacks[o]=r.enterCallbacks[o]||[]);return()=>new Promise(((c,s)=>{const i=e=>{var i;!1===e?s(B(4,{from:n,to:t})):e instanceof Error?s(e):"string"==typeof(i=e)||i&&"object"==typeof i?s(B(2,{from:t,to:e})):(a&&r.enterCallbacks[o]===a&&"function"==typeof e&&a.push(e),c())},l=e.call(r&&r.instances[o],t,n,i);let u=Promise.resolve(l);e.length<3&&(u=u.then(i)),u.catch((e=>s(e)))}))}function Ae(e,t,r,o){const a=[];for(const s of e)for(const e in s.components){let i=s.components[e];if("beforeRouteEnter"===t||s.instances[e])if("object"==typeof(c=i)||"displayName"in c||"props"in c||"__vccOpts"in c){const n=(i.__vccOpts||i)[t];n&&a.push(Re(n,r,o,s,e))}else{let c=i();a.push((()=>c.then((a=>{if(!a)return Promise.reject(new Error(`Couldn't resolve component "${e}" at "${s.path}"`));const c=(i=a).__esModule||n&&"Module"===i[Symbol.toStringTag]?a.default:a;var i;s.components[e]=c;const l=(c.__vccOpts||c)[t];return l&&Re(l,r,o,s,e)()}))))}}var c;return a}function Oe(e){const n=t.inject(c),r=t.inject(s),o=t.computed((()=>n.resolve(t.unref(e.to)))),a=t.computed((()=>{const{matched:e}=o.value,{length:t}=e,n=e[t-1],a=r.matched;if(!n||!a.length)return-1;const c=a.findIndex(g.bind(null,n));if(c>-1)return c;const s=Pe(e[t-2]);return t>1&&Pe(n)===s&&a[a.length-1].path!==s?a.findIndex(g.bind(null,e[t-2])):c})),i=t.computed((()=>a.value>-1&&function(e,t){for(const n in t){const r=t[n],o=e[n];if("string"==typeof r){if(r!==o)return!1}else if(!Array.isArray(o)||o.length!==r.length||r.some(((e,t)=>e!==o[t])))return!1}return!0}(r.params,o.value.params))),l=t.computed((()=>a.value>-1&&a.value===r.matched.length-1&&v(r.params,o.value.params)));return{route:o,href:t.computed((()=>o.value.href)),isActive:i,isExactActive:l,navigate:function(r={}){return function(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return;if(e.defaultPrevented)return;if(void 0!==e.button&&0!==e.button)return;if(e.currentTarget&&e.currentTarget.getAttribute){const t=e.currentTarget.getAttribute("target");if(/\b_blank\b/i.test(t))return}e.preventDefault&&e.preventDefault();return!0}(r)?n[t.unref(e.replace)?"replace":"push"](t.unref(e.to)).catch(p):Promise.resolve()}}}const ke=t.defineComponent({name:"RouterLink",props:{to:{type:[String,Object],required:!0},replace:Boolean,activeClass:String,exactActiveClass:String,custom:Boolean,ariaCurrentValue:{type:String,default:"page"}},useLink:Oe,setup(e,{slots:n}){const r=t.reactive(Oe(e)),{options:o}=t.inject(c),a=t.computed((()=>({[je(e.activeClass,o.linkActiveClass,"router-link-active")]:r.isActive,[je(e.exactActiveClass,o.linkExactActiveClass,"router-link-exact-active")]:r.isExactActive})));return()=>{const o=n.default&&n.default(r);return e.custom?o:t.h("a",{"aria-current":r.isExactActive?e.ariaCurrentValue:null,href:r.href,onClick:r.navigate,class:a.value},o)}}});function Pe(e){return e?e.aliasOf?e.aliasOf.path:e.path:""}const je=(e,t,n)=>null!=e?e:null!=t?t:n;function xe(e,t){if(!e)return null;const n=e(t);return 1===n.length?n[0]:n}const Ce=t.defineComponent({name:"RouterView",inheritAttrs:!1,props:{name:{type:String,default:"default"},route:Object},compatConfig:{MODE:3},setup(e,{attrs:n,slots:r}){const c=t.inject(i),s=t.computed((()=>e.route||c.value)),l=t.inject(a,0),f=t.computed((()=>s.value.matched[l]));t.provide(a,l+1),t.provide(o,f),t.provide(i,s);const p=t.ref();return t.watch((()=>[p.value,f.value,e.name]),(([e,t,n],[r,o,a])=>{t&&(t.instances[n]=e,o&&o!==t&&e&&e===r&&(t.leaveGuards.size||(t.leaveGuards=o.leaveGuards),t.updateGuards.size||(t.updateGuards=o.updateGuards))),!e||!t||o&&g(t,o)&&r||(t.enterCallbacks[n]||[]).forEach((t=>t(e)))}),{flush:"post"}),()=>{const o=s.value,a=f.value,c=a&&a.components[e.name],i=e.name;if(!c)return xe(r.default,{Component:c,route:o});const l=a.props[e.name],h=l?!0===l?o.params:"function"==typeof l?l(o):l:null,d=t.h(c,u({},h,n,{onVnodeUnmounted:e=>{e.component.isUnmounted&&(a.instances[i]=null)},ref:p}));return xe(r.default,{Component:d,route:o})||d}}});function $e(e){return e.reduce(((e,t)=>e.then((()=>t()))),Promise.resolve())}return e.RouterLink=ke,e.RouterView=Ce,e.START_LOCATION=M,e.createMemoryHistory=function(e=""){let t=[],n=[""],r=0;function o(e){r++,r===n.length||n.splice(r),n.push(e)}const a={location:"",state:{},base:e=R(e),createHref:O.bind(null,e),replace(e){n.splice(r--,1),o(e)},push(e,t){o(e)},listen:e=>(t.push(e),()=>{const n=t.indexOf(e);n>-1&&t.splice(n,1)}),destroy(){t=[],n=[""],r=0},go(e,o=!0){const a=this.location,c=e<0?E.back:E.forward;r=Math.max(0,Math.min(r+e,n.length-1)),o&&function(e,n,{direction:r,delta:o}){const a={direction:r,delta:o,type:w.pop};for(const r of t)r(e,n,a)}(this.location,a,{direction:c,delta:e})}};return Object.defineProperty(a,"location",{enumerable:!0,get:()=>n[r]}),a},e.createRouter=function(e){const n=N(e.routes,e),r=e.parseQuery||ve,o=e.stringifyQuery||ye,a=e.history,h=we(),m=we(),y=we(),b=t.shallowRef(M);let E=M;l&&e.scrollBehavior&&"scrollRestoration"in history&&(history.scrollRestoration="manual");const R=f.bind(null,(e=>""+e)),A=f.bind(null,me),O=f.bind(null,ge);function C(e,t){if(t=u({},t||b.value),"string"==typeof e){const o=d(r,e,t.path),c=n.resolve({path:o.path},t),s=a.createHref(o.fullPath);return u(o,c,{params:O(c.params),hash:ge(o.hash),redirectedFrom:void 0,href:s})}let c;if("path"in e)c=u({},e,{path:d(r,e.path,t.path).path});else{const n=u({},e.params);for(const e in n)null==n[e]&&delete n[e];c=u({},e,{params:A(e.params)}),t.params=A(t.params)}const s=n.resolve(c,t),i=e.hash||"";s.params=R(O(s.params));const l=function(e,t){const n=t.query?e(t.query):"";return t.path+(n&&"?")+n+(t.hash||"")}(o,u({},e,{hash:(f=i,he(f).replace(le,"{").replace(fe,"}").replace(se,"^")),path:s.path}));var f;const p=a.createHref(l);return u({fullPath:l,hash:i,query:o===ye?be(e.query):e.query||{}},s,{redirectedFrom:void 0,href:p})}function $(e){return"string"==typeof e?d(r,e,b.value.path):u({},e)}function S(e,t){if(E!==e)return B(8,{from:t,to:e})}function L(e){return T(e)}function _(e){const t=e.matched[e.matched.length-1];if(t&&t.redirect){const{redirect:n}=t;let r="function"==typeof n?n(e):n;return"string"==typeof r&&(r=r.includes("?")||r.includes("#")?r=$(r):{path:r},r.params={}),u({query:e.query,hash:e.hash,params:e.params},r)}}function T(e,t){const n=E=C(e),r=b.value,a=e.state,c=e.force,s=!0===e.replace,i=_(n);if(i)return T(u($(i),{state:a,force:c,replace:s}),t||n);const l=n;let f;return l.redirectedFrom=t,!c&&function(e,t,n){const r=t.matched.length-1,o=n.matched.length-1;return r>-1&&r===o&&g(t.matched[r],n.matched[o])&&v(t.params,n.params)&&e(t.query)===e(n.query)&&t.hash===n.hash}(o,r,n)&&(f=B(16,{to:l,from:r}),Y(r,r,!0,!1)),(f?Promise.resolve(f):I(l,r)).catch((e=>G(e)?G(e,2)?e:X(e):Q(e,l,r))).then((e=>{if(e){if(G(e,2))return T(u($(e.to),{state:a,force:c,replace:s}),t||l)}else e=U(l,r,!0,s,a);return K(l,r,e),e}))}function F(e,t){const n=S(e,t);return n?Promise.reject(n):Promise.resolve()}function I(e,t){let n;const[r,o,a]=function(e,t){const n=[],r=[],o=[],a=Math.max(t.matched.length,e.matched.length);for(let c=0;cg(e,a)))?r.push(a):n.push(a));const s=e.matched[c];s&&(t.matched.find((e=>g(e,s)))||o.push(s))}return[n,r,o]}(e,t);n=Ae(r.reverse(),"beforeRouteLeave",e,t);for(const o of r)o.leaveGuards.forEach((r=>{n.push(Re(r,e,t))}));const c=F.bind(null,e,t);return n.push(c),$e(n).then((()=>{n=[];for(const r of h.list())n.push(Re(r,e,t));return n.push(c),$e(n)})).then((()=>{n=Ae(o,"beforeRouteUpdate",e,t);for(const r of o)r.updateGuards.forEach((r=>{n.push(Re(r,e,t))}));return n.push(c),$e(n)})).then((()=>{n=[];for(const r of e.matched)if(r.beforeEnter&&!t.matched.includes(r))if(Array.isArray(r.beforeEnter))for(const o of r.beforeEnter)n.push(Re(o,e,t));else n.push(Re(r.beforeEnter,e,t));return n.push(c),$e(n)})).then((()=>(e.matched.forEach((e=>e.enterCallbacks={})),n=Ae(a,"beforeRouteEnter",e,t),n.push(c),$e(n)))).then((()=>{n=[];for(const r of m.list())n.push(Re(r,e,t));return n.push(c),$e(n)})).catch((e=>G(e,8)?e:Promise.reject(e)))}function K(e,t,n){for(const r of y.list())r(e,t,n)}function U(e,t,n,r,o){const c=S(e,t);if(c)return c;const s=t===M,i=l?history.state:{};n&&(r||s?a.replace(e.fullPath,u({scroll:s&&i&&i.scroll},o)):a.push(e.fullPath,o)),b.value=e,Y(e,t,n,s),X()}let V;function D(){V||(V=a.listen(((e,t,n)=>{const r=C(e),o=_(r);if(o)return void T(u(o,{replace:!0}),r).catch(p);E=r;const c=b.value;var s,i;l&&(s=j(c.fullPath,n.delta),i=k(),x.set(s,i)),I(r,c).catch((e=>G(e,12)?e:G(e,2)?(T(e.to,r).then((e=>{G(e,20)&&!n.delta&&n.type===w.pop&&a.go(-1,!1)})).catch(p),Promise.reject()):(n.delta&&a.go(-n.delta,!1),Q(e,r,c)))).then((e=>{(e=e||U(r,c,!1))&&(n.delta?a.go(-n.delta,!1):n.type===w.pop&&G(e,20)&&a.go(-1,!1)),K(r,c,e)})).catch(p)})))}let H,W=we(),z=we();function Q(e,t,n){X(e);const r=z.list();return r.length?r.forEach((r=>r(e,t,n))):console.error(e),Promise.reject(e)}function X(e){return H||(H=!e,D(),W.list().forEach((([t,n])=>e?n(e):t())),W.reset()),e}function Y(n,r,o,a){const{scrollBehavior:c}=e;if(!l||!c)return Promise.resolve();const s=!o&&function(e){const t=x.get(e);return x.delete(e),t}(j(n.fullPath,0))||(a||!o)&&history.state&&history.state.scroll||null;return t.nextTick().then((()=>c(n,r,s))).then((e=>e&&P(e))).catch((e=>Q(e,n,r)))}const Z=e=>a.go(e);let J;const ee=new Set,te={currentRoute:b,addRoute:function(e,t){let r,o;return q(e)?(r=n.getRecordMatcher(e),o=t):o=e,n.addRoute(o,r)},removeRoute:function(e){const t=n.getRecordMatcher(e);t&&n.removeRoute(t)},hasRoute:function(e){return!!n.getRecordMatcher(e)},getRoutes:function(){return n.getRoutes().map((e=>e.record))},resolve:C,options:e,push:L,replace:function(e){return L(u($(e),{replace:!0}))},go:Z,back:()=>Z(-1),forward:()=>Z(1),beforeEach:h.add,beforeResolve:m.add,afterEach:y.add,onError:z.add,isReady:function(){return H&&b.value!==M?Promise.resolve():new Promise(((e,t)=>{W.add([e,t])}))},install(e){e.component("RouterLink",ke),e.component("RouterView",Ce),e.config.globalProperties.$router=this,Object.defineProperty(e.config.globalProperties,"$route",{enumerable:!0,get:()=>t.unref(b)}),l&&!J&&b.value===M&&(J=!0,L(a.location).catch((e=>{})));const n={};for(const e in M)n[e]=t.computed((()=>b.value[e]));e.provide(c,this),e.provide(s,t.reactive(n)),e.provide(i,b);const r=e.unmount;ee.add(e),e.unmount=function(){ee.delete(e),ee.size<1&&(E=M,V&&V(),V=null,b.value=M,J=!1,H=!1),r()}}};return te},e.createRouterMatcher=N,e.createWebHashHistory=function(e){return(e=location.host?e||location.pathname+location.search:"").includes("#")||(e+="#"),L(e)},e.createWebHistory=L,e.isNavigationFailure=G,e.matchedRouteKey=o,e.onBeforeRouteLeave=function(e){const n=t.inject(o,{}).value;n&&Ee(n,"leaveGuards",e)},e.onBeforeRouteUpdate=function(e){const n=t.inject(o,{}).value;n&&Ee(n,"updateGuards",e)},e.parseQuery=ve,e.routeLocationKey=s,e.routerKey=c,e.routerViewLocationKey=i,e.stringifyQuery=ye,e.useLink=Oe,e.useRoute=function(){return t.inject(s)},e.useRouter=function(){return t.inject(c)},e.viewDepthKey=a,Object.defineProperty(e,"__esModule",{value:!0}),e}({},Vue); +var VueRouter=function(e,t){"use strict";const n="undefined"!=typeof window;function r(e){return e.__esModule||"Module"===e[Symbol.toStringTag]}const o=Object.assign;function a(e,t){const n={};for(const r in t){const o=t[r];n[r]=s(o)?o.map(e):e(o)}return n}const c=()=>{},s=Array.isArray,i=/\/$/;function l(e,t,n="/"){let r,o={},a="",c="";const s=t.indexOf("#");let i=t.indexOf("?");return s=0&&(i=-1),i>-1&&(r=t.slice(0,i),a=t.slice(i+1,s>-1?s:t.length),o=e(a)),s>-1&&(r=r||t.slice(0,s),c=t.slice(s,t.length)),r=function(e,t){if(e.startsWith("/"))return e;if(!e)return t;const n=t.split("/"),r=e.split("/");let o,a,c=n.length-1;for(o=0;o1&&c--}return n.slice(0,c).join("/")+"/"+r.slice(o-(o===r.length?1:0)).join("/")}(null!=r?r:t,n),{fullPath:r+(a&&"?")+a+c,path:r,query:o,hash:c}}function u(e,t){return t&&e.toLowerCase().startsWith(t.toLowerCase())?e.slice(t.length)||"/":e}function f(e,t){return(e.aliasOf||e)===(t.aliasOf||t)}function p(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(!h(e[n],t[n]))return!1;return!0}function h(e,t){return s(e)?d(e,t):s(t)?d(t,e):e===t}function d(e,t){return s(t)?e.length===t.length&&e.every(((e,n)=>e===t[n])):1===e.length&&e[0]===t}var m,g;!function(e){e.pop="pop",e.push="push"}(m||(m={})),function(e){e.back="back",e.forward="forward",e.unknown=""}(g||(g={}));function v(e){if(!e)if(n){const t=document.querySelector("base");e=(e=t&&t.getAttribute("href")||"/").replace(/^\w+:\/\/[^\/]+/,"")}else e="/";return"/"!==e[0]&&"#"!==e[0]&&(e="/"+e),e.replace(i,"")}const y=/^[^#]+#/;function b(e,t){return e.replace(y,"#")+t}const w=()=>({left:window.pageXOffset,top:window.pageYOffset});function E(e){let t;if("el"in e){const n=e.el,r="string"==typeof n&&n.startsWith("#"),o="string"==typeof n?r?document.getElementById(n.slice(1)):document.querySelector(n):n;if(!o)return;t=function(e,t){const n=document.documentElement.getBoundingClientRect(),r=e.getBoundingClientRect();return{behavior:t.behavior,left:r.left-n.left-(t.left||0),top:r.top-n.top-(t.top||0)}}(o,e)}else t=e;"scrollBehavior"in document.documentElement.style?window.scrollTo(t):window.scrollTo(null!=t.left?t.left:window.pageXOffset,null!=t.top?t.top:window.pageYOffset)}function R(e,t){return(history.state?history.state.position-t:-1)+e}const O=new Map;let k=()=>location.protocol+"//"+location.host;function P(e,t){const{pathname:n,search:r,hash:o}=t,a=e.indexOf("#");if(a>-1){let t=o.includes(e.slice(a))?e.slice(a).length:1,n=o.slice(t);return"/"!==n[0]&&(n="/"+n),u(n,"")}return u(n,e)+r+o}function j(e,t,n,r=!1,o=!1){return{back:e,current:t,forward:n,replaced:r,position:window.history.length,scroll:o?w():null}}function C(e){const t=function(e){const{history:t,location:n}=window,r={value:P(e,n)},a={value:t.state};function c(r,o,c){const s=e.indexOf("#"),i=s>-1?(n.host&&document.querySelector("base")?e:e.slice(s))+r:k()+e+r;try{t[c?"replaceState":"pushState"](o,"",i),a.value=o}catch(e){console.error(e),n[c?"replace":"assign"](i)}}return a.value||c(r.value,{back:null,current:r.value,forward:null,position:t.length-1,replaced:!0,scroll:null},!0),{location:r,state:a,push:function(e,n){const s=o({},a.value,t.state,{forward:e,scroll:w()});c(s.current,s,!0),c(e,o({},j(r.value,e,null),{position:s.position+1},n),!1),r.value=e},replace:function(e,n){c(e,o({},t.state,j(a.value.back,e,a.value.forward,!0),n,{position:a.value.position}),!0),r.value=e}}}(e=v(e)),n=function(e,t,n,r){let a=[],c=[],s=null;const i=({state:o})=>{const c=P(e,location),i=n.value,l=t.value;let u=0;if(o){if(n.value=c,t.value=o,s&&s===i)return void(s=null);u=l?o.position-l.position:0}else r(c);a.forEach((e=>{e(n.value,i,{delta:u,type:m.pop,direction:u?u>0?g.forward:g.back:g.unknown})}))};function l(){const{history:e}=window;e.state&&e.replaceState(o({},e.state,{scroll:w()}),"")}return window.addEventListener("popstate",i),window.addEventListener("beforeunload",l),{pauseListeners:function(){s=n.value},listen:function(e){a.push(e);const t=()=>{const t=a.indexOf(e);t>-1&&a.splice(t,1)};return c.push(t),t},destroy:function(){for(const e of c)e();c=[],window.removeEventListener("popstate",i),window.removeEventListener("beforeunload",l)}}}(e,t.state,t.location,t.replace);const r=o({location:"",base:e,go:function(e,t=!0){t||n.pauseListeners(),history.go(e)},createHref:b.bind(null,e)},t,n);return Object.defineProperty(r,"location",{enumerable:!0,get:()=>t.location.value}),Object.defineProperty(r,"state",{enumerable:!0,get:()=>t.state.value}),r}function x(e){return"string"==typeof e||"symbol"==typeof e}const $={path:"/",name:void 0,params:{},query:{},hash:"",fullPath:"/",matched:[],meta:{},redirectedFrom:void 0},S=Symbol("");var A;function L(e,t){return o(new Error,{type:e,[S]:!0},t)}function M(e,t){return e instanceof Error&&S in e&&(null==t||!!(e.type&t))}e.NavigationFailureType=void 0,(A=e.NavigationFailureType||(e.NavigationFailureType={}))[A.aborted=4]="aborted",A[A.cancelled=8]="cancelled",A[A.duplicated=16]="duplicated";const q="[^/]+?",B={sensitive:!1,strict:!1,start:!0,end:!0},T=/[.+*?^${}()[\]/\\]/g;function _(e,t){let n=0;for(;nt.length?1===t.length&&80===t[0]?1:-1:0}function G(e,t){let n=0;const r=e.score,o=t.score;for(;n0&&t[t.length-1]<0}const D={type:0,value:""},I=/[a-zA-Z0-9_]/;function K(e,t,n){const r=function(e,t){const n=o({},B,t),r=[];let a=n.start?"^":"";const c=[];for(const t of e){const e=t.length?[]:[90];n.strict&&!t.length&&(a+="/");for(let r=0;r1&&("*"===s||"+"===s)&&t(`A repeatable param (${l}) must be alone in its segment. eg: '/:ids+.`),a.push({type:1,value:l,regexp:u,repeatable:"*"===s||"+"===s,optional:"*"===s||"?"===s})):t("Invalid state to consume buffer"),l="")}function p(){l+=s}for(;i{s(d)}:c}function s(e){if(x(e)){const t=r.get(e);t&&(r.delete(e),n.splice(n.indexOf(t),1),t.children.forEach(s),t.alias.forEach(s))}else{const t=n.indexOf(e);t>-1&&(n.splice(t,1),e.record.name&&r.delete(e.record.name),e.children.forEach(s),e.alias.forEach(s))}}function i(e){let t=0;for(;t=0&&(e.record.path!==n[t].record.path||!Q(e,n[t]));)t++;n.splice(t,0,e),e.record.name&&!W(e)&&r.set(e.record.name,e)}return t=z({strict:!1,end:!0,sensitive:!1},t),e.forEach((e=>a(e))),{addRoute:a,resolve:function(e,t){let a,c,s,i={};if("name"in e&&e.name){if(a=r.get(e.name),!a)throw L(1,{location:e});s=a.record.name,i=o(V(t.params,a.keys.filter((e=>!e.optional)).map((e=>e.name))),e.params&&V(e.params,a.keys.map((e=>e.name)))),c=a.stringify(i)}else if("path"in e)c=e.path,a=n.find((e=>e.re.test(c))),a&&(i=a.parse(c),s=a.record.name);else{if(a=t.name?r.get(t.name):n.find((e=>e.re.test(t.path))),!a)throw L(1,{location:e,currentLocation:t});s=a.record.name,i=o({},t.params,e.params),c=a.stringify(i)}const l=[];let u=a;for(;u;)l.unshift(u.record),u=u.parent;return{name:s,path:c,params:i,matched:l,meta:N(l)}},removeRoute:s,getRoutes:function(){return n},getRecordMatcher:function(e){return r.get(e)}}}function V(e,t){const n={};for(const r of t)r in e&&(n[r]=e[r]);return n}function H(e){const t={},n=e.props||!1;if("component"in e)t.default=n;else for(const r in e.components)t[r]="boolean"==typeof n?n:n[r];return t}function W(e){for(;e;){if(e.record.aliasOf)return!0;e=e.parent}return!1}function N(e){return e.reduce(((e,t)=>o(e,t.meta)),{})}function z(e,t){const n={};for(const r in e)n[r]=r in t?t[r]:e[r];return n}function Q(e,t){return t.children.some((t=>t===e||Q(e,t)))}const X=/#/g,Y=/&/g,Z=/\//g,J=/=/g,ee=/\?/g,te=/\+/g,ne=/%5B/g,re=/%5D/g,oe=/%5E/g,ae=/%60/g,ce=/%7B/g,se=/%7C/g,ie=/%7D/g,le=/%20/g;function ue(e){return encodeURI(""+e).replace(se,"|").replace(ne,"[").replace(re,"]")}function fe(e){return ue(e).replace(te,"%2B").replace(le,"+").replace(X,"%23").replace(Y,"%26").replace(ae,"`").replace(ce,"{").replace(ie,"}").replace(oe,"^")}function pe(e){return null==e?"":function(e){return ue(e).replace(X,"%23").replace(ee,"%3F")}(e).replace(Z,"%2F")}function he(e){try{return decodeURIComponent(""+e)}catch(e){}return""+e}function de(e){const t={};if(""===e||"?"===e)return t;const n=("?"===e[0]?e.slice(1):e).split("&");for(let e=0;ee&&fe(e))):[r&&fe(r)]).forEach((e=>{void 0!==e&&(t+=(t.length?"&":"")+n,null!=e&&(t+="="+e))}))}return t}function ge(e){const t={};for(const n in e){const r=e[n];void 0!==r&&(t[n]=s(r)?r.map((e=>null==e?null:""+e)):null==r?r:""+r)}return t}const ve=Symbol(""),ye=Symbol(""),be=Symbol(""),we=Symbol(""),Ee=Symbol("");function Re(){let e=[];return{add:function(t){return e.push(t),()=>{const n=e.indexOf(t);n>-1&&e.splice(n,1)}},list:()=>e,reset:function(){e=[]}}}function Oe(e,n,r){const o=()=>{e[n].delete(r)};t.onUnmounted(o),t.onDeactivated(o),t.onActivated((()=>{e[n].add(r)})),e[n].add(r)}function ke(e,t,n,r,o){const a=r&&(r.enterCallbacks[o]=r.enterCallbacks[o]||[]);return()=>new Promise(((c,s)=>{const i=e=>{var i;!1===e?s(L(4,{from:n,to:t})):e instanceof Error?s(e):"string"==typeof(i=e)||i&&"object"==typeof i?s(L(2,{from:t,to:e})):(a&&r.enterCallbacks[o]===a&&"function"==typeof e&&a.push(e),c())},l=e.call(r&&r.instances[o],t,n,i);let u=Promise.resolve(l);e.length<3&&(u=u.then(i)),u.catch((e=>s(e)))}))}function Pe(e,t,n,o){const a=[];for(const s of e)for(const e in s.components){let i=s.components[e];if("beforeRouteEnter"===t||s.instances[e])if("object"==typeof(c=i)||"displayName"in c||"props"in c||"__vccOpts"in c){const r=(i.__vccOpts||i)[t];r&&a.push(ke(r,n,o,s,e))}else{let c=i();a.push((()=>c.then((a=>{if(!a)return Promise.reject(new Error(`Couldn't resolve component "${e}" at "${s.path}"`));const c=r(a)?a.default:a;s.components[e]=c;const i=(c.__vccOpts||c)[t];return i&&ke(i,n,o,s,e)()}))))}}var c;return a}function je(e){const n=t.inject(be),r=t.inject(we),o=t.computed((()=>n.resolve(t.unref(e.to)))),a=t.computed((()=>{const{matched:e}=o.value,{length:t}=e,n=e[t-1],a=r.matched;if(!n||!a.length)return-1;const c=a.findIndex(f.bind(null,n));if(c>-1)return c;const s=xe(e[t-2]);return t>1&&xe(n)===s&&a[a.length-1].path!==s?a.findIndex(f.bind(null,e[t-2])):c})),i=t.computed((()=>a.value>-1&&function(e,t){for(const n in t){const r=t[n],o=e[n];if("string"==typeof r){if(r!==o)return!1}else if(!s(o)||o.length!==r.length||r.some(((e,t)=>e!==o[t])))return!1}return!0}(r.params,o.value.params))),l=t.computed((()=>a.value>-1&&a.value===r.matched.length-1&&p(r.params,o.value.params)));return{route:o,href:t.computed((()=>o.value.href)),isActive:i,isExactActive:l,navigate:function(r={}){return function(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return;if(e.defaultPrevented)return;if(void 0!==e.button&&0!==e.button)return;if(e.currentTarget&&e.currentTarget.getAttribute){const t=e.currentTarget.getAttribute("target");if(/\b_blank\b/i.test(t))return}e.preventDefault&&e.preventDefault();return!0}(r)?n[t.unref(e.replace)?"replace":"push"](t.unref(e.to)).catch(c):Promise.resolve()}}}const Ce=t.defineComponent({name:"RouterLink",compatConfig:{MODE:3},props:{to:{type:[String,Object],required:!0},replace:Boolean,activeClass:String,exactActiveClass:String,custom:Boolean,ariaCurrentValue:{type:String,default:"page"}},useLink:je,setup(e,{slots:n}){const r=t.reactive(je(e)),{options:o}=t.inject(be),a=t.computed((()=>({[$e(e.activeClass,o.linkActiveClass,"router-link-active")]:r.isActive,[$e(e.exactActiveClass,o.linkExactActiveClass,"router-link-exact-active")]:r.isExactActive})));return()=>{const o=n.default&&n.default(r);return e.custom?o:t.h("a",{"aria-current":r.isExactActive?e.ariaCurrentValue:null,href:r.href,onClick:r.navigate,class:a.value},o)}}});function xe(e){return e?e.aliasOf?e.aliasOf.path:e.path:""}const $e=(e,t,n)=>null!=e?e:null!=t?t:n;function Se(e,t){if(!e)return null;const n=e(t);return 1===n.length?n[0]:n}const Ae=t.defineComponent({name:"RouterView",inheritAttrs:!1,props:{name:{type:String,default:"default"},route:Object},compatConfig:{MODE:3},setup(e,{attrs:n,slots:r}){const a=t.inject(Ee),c=t.computed((()=>e.route||a.value)),s=t.inject(ye,0),i=t.computed((()=>{let e=t.unref(s);const{matched:n}=c.value;let r;for(;(r=n[e])&&!r.components;)e++;return e})),l=t.computed((()=>c.value.matched[i.value]));t.provide(ye,t.computed((()=>i.value+1))),t.provide(ve,l),t.provide(Ee,c);const u=t.ref();return t.watch((()=>[u.value,l.value,e.name]),(([e,t,n],[r,o,a])=>{t&&(t.instances[n]=e,o&&o!==t&&e&&e===r&&(t.leaveGuards.size||(t.leaveGuards=o.leaveGuards),t.updateGuards.size||(t.updateGuards=o.updateGuards))),!e||!t||o&&f(t,o)&&r||(t.enterCallbacks[n]||[]).forEach((t=>t(e)))}),{flush:"post"}),()=>{const a=c.value,s=e.name,i=l.value,f=i&&i.components[s];if(!f)return Se(r.default,{Component:f,route:a});const p=i.props[s],h=p?!0===p?a.params:"function"==typeof p?p(a):p:null,d=t.h(f,o({},h,n,{onVnodeUnmounted:e=>{e.component.isUnmounted&&(i.instances[s]=null)},ref:u}));return Se(r.default,{Component:d,route:a})||d}}});function Le(e){return e.reduce(((e,t)=>e.then((()=>t()))),Promise.resolve())}return e.RouterLink=Ce,e.RouterView=Ae,e.START_LOCATION=$,e.createMemoryHistory=function(e=""){let t=[],n=[""],r=0;function o(e){r++,r===n.length||n.splice(r),n.push(e)}const a={location:"",state:{},base:e=v(e),createHref:b.bind(null,e),replace(e){n.splice(r--,1),o(e)},push(e,t){o(e)},listen:e=>(t.push(e),()=>{const n=t.indexOf(e);n>-1&&t.splice(n,1)}),destroy(){t=[],n=[""],r=0},go(e,o=!0){const a=this.location,c=e<0?g.back:g.forward;r=Math.max(0,Math.min(r+e,n.length-1)),o&&function(e,n,{direction:r,delta:o}){const a={direction:r,delta:o,type:m.pop};for(const r of t)r(e,n,a)}(this.location,a,{direction:c,delta:e})}};return Object.defineProperty(a,"location",{enumerable:!0,get:()=>n[r]}),a},e.createRouter=function(e){const r=U(e.routes,e),i=e.parseQuery||de,u=e.stringifyQuery||me,h=e.history,d=Re(),g=Re(),v=Re(),y=t.shallowRef($);let b=$;n&&e.scrollBehavior&&"scrollRestoration"in history&&(history.scrollRestoration="manual");const k=a.bind(null,(e=>""+e)),P=a.bind(null,pe),j=a.bind(null,he);function C(e,t){if(t=o({},t||y.value),"string"==typeof e){const n=l(i,e,t.path),a=r.resolve({path:n.path},t),c=h.createHref(n.fullPath);return o(n,a,{params:j(a.params),hash:he(n.hash),redirectedFrom:void 0,href:c})}let n;if("path"in e)n=o({},e,{path:l(i,e.path,t.path).path});else{const r=o({},e.params);for(const e in r)null==r[e]&&delete r[e];n=o({},e,{params:P(e.params)}),t.params=P(t.params)}const a=r.resolve(n,t),c=e.hash||"";a.params=k(j(a.params));const s=function(e,t){const n=t.query?e(t.query):"";return t.path+(n&&"?")+n+(t.hash||"")}(u,o({},e,{hash:(f=c,ue(f).replace(ce,"{").replace(ie,"}").replace(oe,"^")),path:a.path}));var f;const p=h.createHref(s);return o({fullPath:s,hash:c,query:u===me?ge(e.query):e.query||{}},a,{redirectedFrom:void 0,href:p})}function S(e){return"string"==typeof e?l(i,e,y.value.path):o({},e)}function A(e,t){if(b!==e)return L(8,{from:t,to:e})}function q(e){return T(e)}function B(e){const t=e.matched[e.matched.length-1];if(t&&t.redirect){const{redirect:n}=t;let r="function"==typeof n?n(e):n;return"string"==typeof r&&(r=r.includes("?")||r.includes("#")?r=S(r):{path:r},r.params={}),o({query:e.query,hash:e.hash,params:"path"in r?{}:e.params},r)}}function T(e,t){const n=b=C(e),r=y.value,a=e.state,c=e.force,s=!0===e.replace,i=B(n);if(i)return T(o(S(i),{state:"object"==typeof i?o({},a,i.state):a,force:c,replace:s}),t||n);const l=n;let h;return l.redirectedFrom=t,!c&&function(e,t,n){const r=t.matched.length-1,o=n.matched.length-1;return r>-1&&r===o&&f(t.matched[r],n.matched[o])&&p(t.params,n.params)&&e(t.query)===e(n.query)&&t.hash===n.hash}(u,r,n)&&(h=L(16,{to:l,from:r}),Q(r,r,!0,!1)),(h?Promise.resolve(h):G(l,r)).catch((e=>M(e)?M(e,2)?e:z(e):N(e,l,r))).then((e=>{if(e){if(M(e,2))return T(o({replace:s},S(e.to),{state:"object"==typeof e.to?o({},a,e.to.state):a,force:c}),t||l)}else e=D(l,r,!0,s,a);return F(l,r,e),e}))}function _(e,t){const n=A(e,t);return n?Promise.reject(n):Promise.resolve()}function G(e,t){let n;const[r,o,a]=function(e,t){const n=[],r=[],o=[],a=Math.max(t.matched.length,e.matched.length);for(let c=0;cf(e,a)))?r.push(a):n.push(a));const s=e.matched[c];s&&(t.matched.find((e=>f(e,s)))||o.push(s))}return[n,r,o]}(e,t);n=Pe(r.reverse(),"beforeRouteLeave",e,t);for(const o of r)o.leaveGuards.forEach((r=>{n.push(ke(r,e,t))}));const c=_.bind(null,e,t);return n.push(c),Le(n).then((()=>{n=[];for(const r of d.list())n.push(ke(r,e,t));return n.push(c),Le(n)})).then((()=>{n=Pe(o,"beforeRouteUpdate",e,t);for(const r of o)r.updateGuards.forEach((r=>{n.push(ke(r,e,t))}));return n.push(c),Le(n)})).then((()=>{n=[];for(const r of e.matched)if(r.beforeEnter&&!t.matched.includes(r))if(s(r.beforeEnter))for(const o of r.beforeEnter)n.push(ke(o,e,t));else n.push(ke(r.beforeEnter,e,t));return n.push(c),Le(n)})).then((()=>(e.matched.forEach((e=>e.enterCallbacks={})),n=Pe(a,"beforeRouteEnter",e,t),n.push(c),Le(n)))).then((()=>{n=[];for(const r of g.list())n.push(ke(r,e,t));return n.push(c),Le(n)})).catch((e=>M(e,8)?e:Promise.reject(e)))}function F(e,t,n){for(const r of v.list())r(e,t,n)}function D(e,t,r,a,c){const s=A(e,t);if(s)return s;const i=t===$,l=n?history.state:{};r&&(a||i?h.replace(e.fullPath,o({scroll:i&&l&&l.scroll},c)):h.push(e.fullPath,c)),y.value=e,Q(e,t,r,i),z()}let I;function K(){I||(I=h.listen(((e,t,r)=>{if(!J.listening)return;const a=C(e),s=B(a);if(s)return void T(o(s,{replace:!0}),a).catch(c);b=a;const i=y.value;var l,u;n&&(l=R(i.fullPath,r.delta),u=w(),O.set(l,u)),G(a,i).catch((e=>M(e,12)?e:M(e,2)?(T(e.to,a).then((e=>{M(e,20)&&!r.delta&&r.type===m.pop&&h.go(-1,!1)})).catch(c),Promise.reject()):(r.delta&&h.go(-r.delta,!1),N(e,a,i)))).then((e=>{(e=e||D(a,i,!1))&&(r.delta&&!M(e,8)?h.go(-r.delta,!1):r.type===m.pop&&M(e,20)&&h.go(-1,!1)),F(a,i,e)})).catch(c)})))}let V,H=Re(),W=Re();function N(e,t,n){z(e);const r=W.list();return r.length?r.forEach((r=>r(e,t,n))):console.error(e),Promise.reject(e)}function z(e){return V||(V=!e,K(),H.list().forEach((([t,n])=>e?n(e):t())),H.reset()),e}function Q(r,o,a,c){const{scrollBehavior:s}=e;if(!n||!s)return Promise.resolve();const i=!a&&function(e){const t=O.get(e);return O.delete(e),t}(R(r.fullPath,0))||(c||!a)&&history.state&&history.state.scroll||null;return t.nextTick().then((()=>s(r,o,i))).then((e=>e&&E(e))).catch((e=>N(e,r,o)))}const X=e=>h.go(e);let Y;const Z=new Set,J={currentRoute:y,listening:!0,addRoute:function(e,t){let n,o;return x(e)?(n=r.getRecordMatcher(e),o=t):o=e,r.addRoute(o,n)},removeRoute:function(e){const t=r.getRecordMatcher(e);t&&r.removeRoute(t)},hasRoute:function(e){return!!r.getRecordMatcher(e)},getRoutes:function(){return r.getRoutes().map((e=>e.record))},resolve:C,options:e,push:q,replace:function(e){return q(o(S(e),{replace:!0}))},go:X,back:()=>X(-1),forward:()=>X(1),beforeEach:d.add,beforeResolve:g.add,afterEach:v.add,onError:W.add,isReady:function(){return V&&y.value!==$?Promise.resolve():new Promise(((e,t)=>{H.add([e,t])}))},install(e){e.component("RouterLink",Ce),e.component("RouterView",Ae),e.config.globalProperties.$router=this,Object.defineProperty(e.config.globalProperties,"$route",{enumerable:!0,get:()=>t.unref(y)}),n&&!Y&&y.value===$&&(Y=!0,q(h.location).catch((e=>{})));const r={};for(const e in $)r[e]=t.computed((()=>y.value[e]));e.provide(be,this),e.provide(we,t.reactive(r)),e.provide(Ee,y);const o=e.unmount;Z.add(e),e.unmount=function(){Z.delete(e),Z.size<1&&(b=$,I&&I(),I=null,y.value=$,Y=!1,V=!1),o()}}};return J},e.createRouterMatcher=U,e.createWebHashHistory=function(e){return(e=location.host?e||location.pathname+location.search:"").includes("#")||(e+="#"),C(e)},e.createWebHistory=C,e.isNavigationFailure=M,e.loadRouteLocation=function(e){return e.matched.every((e=>e.redirect))?Promise.reject(new Error("Cannot load a route that redirects.")):Promise.all(e.matched.map((e=>e.components&&Promise.all(Object.keys(e.components).reduce(((t,n)=>{const o=e.components[n];return"function"!=typeof o||"displayName"in o||t.push(o().then((t=>{if(!t)return Promise.reject(new Error(`Couldn't resolve component "${n}" at "${e.path}". Ensure you passed a function that returns a promise.`));const o=r(t)?t.default:t;e.components[n]=o}))),t}),[]))))).then((()=>e))},e.matchedRouteKey=ve,e.onBeforeRouteLeave=function(e){const n=t.inject(ve,{}).value;n&&Oe(n,"leaveGuards",e)},e.onBeforeRouteUpdate=function(e){const n=t.inject(ve,{}).value;n&&Oe(n,"updateGuards",e)},e.parseQuery=de,e.routeLocationKey=we,e.routerKey=be,e.routerViewLocationKey=Ee,e.stringifyQuery=me,e.useLink=je,e.useRoute=function(){return t.inject(we)},e.useRouter=function(){return t.inject(be)},e.viewDepthKey=ye,Object.defineProperty(e,"__esModule",{value:!0}),e}({},Vue); diff --git a/node_modules/vue-router/package.json b/node_modules/vue-router/package.json index 910bc54..56a59ba 100644 --- a/node_modules/vue-router/package.json +++ b/node_modules/vue-router/package.json @@ -1,146 +1,114 @@ { - "_from": "vue-router@^4.0.14", - "_id": "vue-router@4.0.15", - "_inBundle": false, - "_integrity": "sha512-xa+pIN9ZqORdIW1MkN2+d9Ui2pCM1b/UMgwYUCZOiFYHAvz/slKKBDha8DLrh5aCG/RibtrpyhKjKOZ85tYyWg==", - "_location": "/vue-router", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "vue-router@^4.0.14", - "name": "vue-router", - "escapedName": "vue-router", - "rawSpec": "^4.0.14", - "saveSpec": null, - "fetchSpec": "^4.0.14" + "name": "vue-router", + "version": "4.1.5", + "main": "index.js", + "unpkg": "dist/vue-router.global.js", + "jsdelivr": "dist/vue-router.global.js", + "module": "dist/vue-router.mjs", + "types": "dist/vue-router.d.ts", + "exports": { + ".": { + "types": "./dist/vue-router.d.ts", + "node": { + "import": { + "production": "./dist/vue-router.node.mjs", + "development": "./dist/vue-router.node.mjs", + "default": "./dist/vue-router.node.mjs" + }, + "require": { + "production": "./dist/vue-router.prod.cjs", + "development": "./dist/vue-router.cjs", + "default": "./index.js" + } + }, + "import": "./dist/vue-router.mjs", + "require": "./index.js" + }, + "./dist/*": "./dist/*", + "./vetur/*": "./vetur/*", + "./package.json": "./package.json" + }, + "sideEffects": false, + "funding": "https://github.com/sponsors/posva", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/vuejs/router.git" }, - "_requiredBy": [ - "/" - ], - "_resolved": "https://registry.npmmirror.com/vue-router/-/vue-router-4.0.15.tgz", - "_shasum": "b4a0661efe197f8c724e0f233308f8776e2c3667", - "_spec": "vue-router@^4.0.14", - "_where": "D:\\workbench\\personal\\bnyer-cloud-tiktok", "bugs": { "url": "https://github.com/vuejs/router/issues" }, - "bundleDependencies": false, + "homepage": "https://github.com/vuejs/router#readme", + "files": [ + "index.js", + "dist/*.{js,cjs,mjs}", + "dist/vue-router.d.ts", + "vetur/tags.json", + "vetur/attributes.json", + "README.md" + ], + "peerDependencies": { + "vue": "^3.2.0" + }, + "vetur": { + "tags": "vetur/tags.json", + "attributes": "vetur/attributes.json" + }, "dependencies": { - "@vue/devtools-api": "^6.0.0" + "@vue/devtools-api": "^6.1.4" }, - "deprecated": false, - "description": "> This is the repository for Vue Router 4 (for Vue 3)", "devDependencies": { - "@microsoft/api-extractor": "^7.18.11", + "@microsoft/api-extractor": "^7.29.2", "@rollup/plugin-alias": "^3.1.4", - "@rollup/plugin-commonjs": "^21.0.2", + "@rollup/plugin-commonjs": "^22.0.2", "@rollup/plugin-node-resolve": "^13.0.5", "@rollup/plugin-replace": "^4.0.0", "@sucrase/jest-plugin": "^2.1.1", "@types/jest": "^27.4.1", "@types/jsdom": "^16.2.13", - "@types/webpack": "^5.28.0", - "@types/webpack-env": "^1.16.2", - "@vitejs/plugin-vue": "^2.2.2", + "@types/nightwatch": "^2.3.3", + "@vitejs/plugin-vue": "^2.3.3", "@vue/compiler-sfc": "^3.2.31", - "@vue/server-renderer": "^3.2.31", - "@vue/test-utils": "^2.0.0-rc.3", - "axios": "^0.26.0", - "brotli": "^1.3.2", + "@vue/server-renderer": "^3.2.37", + "@vue/test-utils": "^2.0.2", "browserstack-local": "^1.4.5", - "chalk": "^4.1.0", - "chromedriver": "^97.0.4", + "chromedriver": "^102.0.0", "connect-history-api-fallback": "^1.6.0", "conventional-changelog-cli": "^2.1.1", - "css-loader": "^6.3.0", "dotenv": "^16.0.0", "faked-promise": "^2.2.2", - "html-webpack-plugin": "^5.3.2", + "geckodriver": "^3.0.2", "jest": "^27.5.1", "jest-mock-warn": "^1.1.0", - "lint-staged": "^12.3.4", - "nightwatch": "^1.7.11", + "nightwatch": "^2.3.0", "nightwatch-helpers": "^1.2.0", - "prettier": "^2.4.1", - "rollup": "^2.68.0", + "rimraf": "^3.0.2", + "rollup": "^2.78.0", "rollup-plugin-analyzer": "^4.0.0", "rollup-plugin-terser": "^7.0.2", - "rollup-plugin-typescript2": "^0.31.0", - "selenium-server": "^3.141.59", - "serve-handler": "^6.1.3", - "typescript": "~4.4.3", - "vite": "~2.8.4", - "vitepress": "^0.20.0", - "vue": "^3.2.31", - "vue-tsc": "^0.32.0", - "yorkie": "^2.0.0" - }, - "files": [ - "dist/*.js", - "dist/vue-router.d.ts", - "vetur/tags.json", - "vetur/attributes.json", - "README.md" - ], - "funding": "https://github.com/sponsors/posva", - "gitHooks": { - "pre-commit": "lint-staged", - "commit-msg": "node scripts/verifyCommit.js" - }, - "homepage": "https://github.com/vuejs/router#readme", - "jsdelivr": "dist/vue-router.global.js", - "license": "MIT", - "lint-staged": { - "*.js": [ - "prettier --write" - ], - "*.ts?(x)": [ - "prettier --parser=typescript --write" - ] - }, - "main": "dist/vue-router.cjs.js", - "module": "dist/vue-router.esm-bundler.js", - "name": "vue-router", - "peerDependencies": { - "vue": "^3.2.0" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/vuejs/router.git" + "rollup-plugin-typescript2": "^0.32.1", + "typescript": "~4.7.4", + "vite": "^2.9.9", + "vue": "^3.2.37" }, "scripts": { - "build": "rollup -c rollup.config.js", - "build:dts": "api-extractor run --local --verbose && tail -n +7 src/globalExtensions.ts >> dist/vue-router.d.ts", - "build:e2e": "vue-tsc --noEmit && vite build --config e2e/vite.config.js", - "build:playground": "vue-tsc --noEmit && vite build --config playground/vite.config.js", - "build:size": "yarn run build && rollup -c size-checks/rollup.config.js", + "dev": "jest --watch", "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 1", - "dev": "vite --config playground/vite.config.js", + "build": "rimraf dist && rollup -c rollup.config.js", + "build:dts": "api-extractor run --local --verbose && tail -n +10 src/globalExtensions.ts >> dist/vue-router.d.ts", + "build:playground": "vue-tsc --noEmit && vite build --config playground/vite.config.js", + "build:e2e": "vue-tsc --noEmit && vite build --config e2e/vite.config.js", + "build:size": "pnpm run build && rollup -c size-checks/rollup.config.js", "dev:e2e": "vite --config e2e/vite.config.js", - "docs": "vitepress dev docs", - "docs:build": "vitepress build docs", - "lint": "yarn run lint:script && yarn run lint:html", - "lint:fix": "yarn run lint:script --write && yarn run lint:html --write", - "lint:html": "prettier -c --parser html \"{playground,e2e}/**/*.html\"", - "lint:script": "prettier -c --parser typescript \"{src,__tests__,e2e,playground}/**/*.[jt]s?(x)\"", - "release": "bash scripts/release.sh", - "test": "yarn run test:types && yarn run test:unit && yarn run build && yarn run build:dts && yarn run test:e2e", - "test:dts": "tsc -p ./test-dts/tsconfig.json", - "test:e2e": "yarn run test:e2e:headless && yarn run test:e2e:native", - "test:e2e:bs": "node e2e/runner.js --local -e edge_pre_chrome,android44 -c e2e/nightwatch.browserstack.js --tag browserstack", - "test:e2e:ci": "node e2e/runner.js -e firefox --retries 2", - "test:e2e:headless": "node e2e/runner.js -e chrome-headless --skiptags no-headless", - "test:e2e:native": "node e2e/runner.js -e chrome --tag no-headless", "test:types": "tsc --build tsconfig.json", - "test:unit": "jest --coverage" - }, - "sideEffects": false, - "types": "dist/vue-router.d.ts", - "unpkg": "dist/vue-router.global.js", - "version": "4.0.15", - "vetur": { - "tags": "vetur/tags.json", - "attributes": "vetur/attributes.json" + "test:dts": "tsc -p ./test-dts/tsconfig.json", + "test:unit": "jest --coverage", + "test": "pnpm run test:types && pnpm run test:unit && pnpm run build && pnpm run build:dts && pnpm run test:e2e", + "test:e2e": "pnpm run test:e2e:headless", + "test:e2e:headless": "node e2e/runner.js --env chrome-headless", + "test:e2e:native": "node e2e/runner.js --env chrome", + "test:e2e:ci": "node e2e/runner.js --env chrome-headless --retries 2", + "test:e2e:bs": "node e2e/runner.js --local -e android5 --tag browserstack", + "test:e2e:bs-test": "node e2e/runner.js --local --env browserstack.local_chrome --tag browserstack" } -} +} \ No newline at end of file diff --git a/node_modules/vuex/package.json b/node_modules/vuex/package.json index e811a90..3aae30a 100644 --- a/node_modules/vuex/package.json +++ b/node_modules/vuex/package.json @@ -1,40 +1,62 @@ { - "_from": "vuex@^4.0.2", - "_id": "vuex@4.0.2", - "_inBundle": false, - "_integrity": "sha512-M6r8uxELjZIK8kTKDGgZTYX/ahzblnzC4isU1tpmEuOIIKmV+TRdc+H4s8ds2NuZ7wpUTdGRzJRtoj+lI+pc0Q==", - "_location": "/vuex", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "vuex@^4.0.2", - "name": "vuex", - "escapedName": "vuex", - "rawSpec": "^4.0.2", - "saveSpec": null, - "fetchSpec": "^4.0.2" + "name": "vuex", + "version": "4.0.2", + "description": "state management for Vue.js", + "main": "dist/vuex.cjs.js", + "exports": { + ".": { + "module": "./dist/vuex.esm-bundler.js", + "require": "./dist/vuex.cjs.js", + "import": "./dist/vuex.mjs" + }, + "./": "./" }, - "_requiredBy": [ - "/" + "module": "dist/vuex.esm-bundler.js", + "browser": "dist/vuex.esm-browser.js", + "unpkg": "dist/vuex.global.js", + "jsdelivr": "dist/vuex.global.js", + "typings": "types/index.d.ts", + "sideEffects": false, + "files": [ + "dist", + "types/index.d.ts", + "types/helpers.d.ts", + "types/logger.d.ts", + "types/vue.d.ts" ], - "_resolved": "https://registry.npmmirror.com/vuex/-/vuex-4.0.2.tgz", - "_shasum": "f896dbd5bf2a0e963f00c67e9b610de749ccacc9", - "_spec": "vuex@^4.0.2", - "_where": "D:\\workbench\\personal\\bnyer-cloud-tiktok", - "author": { - "name": "Evan You" + "scripts": { + "dev": "node examples/server.js", + "build": "node scripts/build.js", + "lint": "eslint src test", + "test": "npm run lint && npm run build && npm run test:types && npm run test:unit && npm run test:ssr && npm run test:e2e && npm run test:esm", + "test:unit": "jest --testPathIgnorePatterns test/e2e", + "test:e2e": "start-server-and-test dev http://localhost:8080 \"jest --testPathIgnorePatterns test/unit\"", + "test:ssr": "cross-env VUE_ENV=server jest --testPathIgnorePatterns test/e2e", + "test:types": "tsc -p types/test", + "test:esm": "node test/esm/esm-test.js", + "coverage": "jest --testPathIgnorePatterns test/e2e --coverage", + "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s", + "release": "node scripts/release.js", + "docs": "vitepress dev docs", + "docs:build": "vitepress build docs", + "docs:serve": "yarn docs:build && vitepress serve docs" }, - "browser": "dist/vuex.esm-browser.js", + "repository": { + "type": "git", + "url": "git+https://github.com/vuejs/vuex.git" + }, + "author": "Evan You", + "license": "MIT", "bugs": { "url": "https://github.com/vuejs/vuex/issues" }, - "bundleDependencies": false, + "homepage": "https://github.com/vuejs/vuex#readme", + "peerDependencies": { + "vue": "^3.0.2" + }, "dependencies": { "@vue/devtools-api": "^6.0.0-beta.11" }, - "deprecated": false, - "description": "state management for Vue.js", "devDependencies": { "@babel/core": "^7.14.3", "@babel/preset-env": "^7.14.2", @@ -73,54 +95,5 @@ "webpack": "^4.43.0", "webpack-dev-middleware": "^3.7.2", "webpack-hot-middleware": "^2.25.0" - }, - "exports": { - ".": { - "module": "./dist/vuex.esm-bundler.js", - "require": "./dist/vuex.cjs.js", - "import": "./dist/vuex.mjs" - }, - "./": "./" - }, - "files": [ - "dist", - "types/index.d.ts", - "types/helpers.d.ts", - "types/logger.d.ts", - "types/vue.d.ts" - ], - "homepage": "https://github.com/vuejs/vuex#readme", - "jsdelivr": "dist/vuex.global.js", - "license": "MIT", - "main": "dist/vuex.cjs.js", - "module": "dist/vuex.esm-bundler.js", - "name": "vuex", - "peerDependencies": { - "vue": "^3.0.2" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/vuejs/vuex.git" - }, - "scripts": { - "build": "node scripts/build.js", - "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s", - "coverage": "jest --testPathIgnorePatterns test/e2e --coverage", - "dev": "node examples/server.js", - "docs": "vitepress dev docs", - "docs:build": "vitepress build docs", - "docs:serve": "yarn docs:build && vitepress serve docs", - "lint": "eslint src test", - "release": "node scripts/release.js", - "test": "npm run lint && npm run build && npm run test:types && npm run test:unit && npm run test:ssr && npm run test:e2e && npm run test:esm", - "test:e2e": "start-server-and-test dev http://localhost:8080 \"jest --testPathIgnorePatterns test/unit\"", - "test:esm": "node test/esm/esm-test.js", - "test:ssr": "cross-env VUE_ENV=server jest --testPathIgnorePatterns test/e2e", - "test:types": "tsc -p types/test", - "test:unit": "jest --testPathIgnorePatterns test/e2e" - }, - "sideEffects": false, - "typings": "types/index.d.ts", - "unpkg": "dist/vuex.global.js", - "version": "4.0.2" + } } diff --git a/pages.json b/pages.json index 9a462c9..8577252 100644 --- a/pages.json +++ b/pages.json @@ -94,7 +94,8 @@ "navigationBarTextStyle": "black", "navigationBarTitleText": "bnyer", "navigationBarBackgroundColor": "#F8F8F8", - "backgroundColor": "#F8F8F8" + "backgroundColor": "#F8F8F8", + "navigationStyle": "custom" }, //底部跳转tab "tabBar": { @@ -108,24 +109,25 @@ "selectedIconPath": "static/index-select.png", "text": "首页" }, - { - "pagePath": "pages/creator/creator", - "iconPath": "static/theme-default.png", - "selectedIconPath": "static/theme-select.png", - "text": "艺术家" - }, + // { + // "pagePath": "pages/creator/creator", + // "iconPath": "static/theme-default.png", + // "selectedIconPath": "static/theme-select.png", + // "text": "艺术家" + // }, { "pagePath": "pages/atlas/atlas", "iconPath": "static/theme-default.png", "selectedIconPath": "static/theme-select.png", - "text": "精彩图集" - }, - { - "pagePath": "pages/userInfo/userInfo", - "iconPath": "static/mine-default.png", - "selectedIconPath": "static/mine-select.png", - "text": "我的" + // "text": "精彩图集" + "text": "分类" } + // { + // "pagePath": "pages/userInfo/userInfo", + // "iconPath": "static/mine-default.png", + // "selectedIconPath": "static/mine-select.png", + // "text": "我的" + // } ] } } diff --git a/pages/index/index - 副本.vue b/pages/index/index - 副本.vue new file mode 100644 index 0000000..c33802b --- /dev/null +++ b/pages/index/index - 副本.vue @@ -0,0 +1,253 @@ + + + + + diff --git a/pages/index/index.vue b/pages/index/index.vue index 0fa9ccb..277cc0d 100644 --- a/pages/index/index.vue +++ b/pages/index/index.vue @@ -1,6 +1,92 @@ @@ -37,10 +123,30 @@ return { hotCreatorList: [], isTarget: true, - showChoiceness:false + showChoiceness: false, + isLeftActive: false, + isRightActive: false, + userInfo: {}, // 用户信息 + menuList: [ // 抽屉菜单 + { + title: '我的好友' + }, + { + title: '我的订单' + }, + { + title: '我的收藏' + }, + { + title: '反馈意见' + }, + { + title: '联系客服' + }, + ], } }, - components:{ + components: { Choiceness, }, // 下拉刷新 @@ -56,7 +162,7 @@ } else { console.log('have userInfo') } - this.getHotCreatorList() + this.checkBtn(1) }, onPageScroll(e) { // 传入scrollTop值并触发所有easy-loadimage组件下的滚动监听事件 @@ -69,6 +175,62 @@ } }, methods: { + // 打开窗口 + showDrawer(e) { + const userInfo = uni.getStorageSync('userInfo') + if (!userInfo) { + console.log('havent userInfo') + this.getUserInfo() + } else { + this.userInfo = userInfo + } + this.$refs[e].open() + }, + // 关闭窗口 + closeDrawer(e) { + this.$refs[e].close() + }, + // 抽屉状态发生变化触发 + change(e, type) { + console.log((type === 'showLeft' ? '左窗口' : '右窗口') + (e ? '打开' : '关闭')); + this[type] = e + }, + targetPage(item) { + switch (item.title) { + case '我的好友': + console.log('我的好友') + break; + case '我的订单': + console.log('我的订单') + break; + case '我的收藏': + uni.navigateTo({ + url: '../userInfo/myCollection/myCollection' + }) + break; + case '反馈意见': + uni.navigateTo({ + url: '../userInfo/question/question' + }) + break; + case '联系客服': + uni.navigateTo({ + url: '../userInfo/contactUs/contactUs' + }) + break; + } + }, + checkBtn(num) { + if (num === 1) { + this.isLeftActive = true + this.isRightActive = false + this.getHotCreatorList() + } else if (num === 2) { + this.isLeftActive = false + this.isRightActive = true + this.getHotCreatorList() + } + }, // 搜索 search(res) { if (res.value) { @@ -84,10 +246,10 @@ }, // 获取用户信息 getUserInfo() { - tt.login({ + uni.login({ force: true, success: res => { - tt.getUserInfo({ + uni.getUserInfo({ withCredentials: true, success: userInfo => { const params = { @@ -102,6 +264,7 @@ key: 'userInfo', data: res.data.data.userInfo, }) + } else { uni.showToast({ title: res.data.msg, @@ -152,7 +315,7 @@ }) } }) - + } else { uni.showToast({ title: res.data.msg, @@ -178,76 +341,211 @@ diff --git a/yarn.lock b/yarn.lock new file mode 100644 index 0000000..d3a9a7b --- /dev/null +++ b/yarn.lock @@ -0,0 +1,89 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@vue/devtools-api@^6.0.0-beta.11", "@vue/devtools-api@^6.1.4": + version "6.4.2" + resolved "https://registry.yarnpkg.com/@vue/devtools-api/-/devtools-api-6.4.2.tgz#faf303a70cd9f8662896d663a195df41a8af1e53" + integrity sha512-6hNZ23h1M2Llky+SIAmVhL7s6BjLtZBCzjIz9iRSBUsysjE7kC39ulW0dH4o/eZtycmSt4qEr6RDVGTIuWu+ow== + +axios@^0.26.1: + version "0.26.1" + resolved "https://registry.yarnpkg.com/axios/-/axios-0.26.1.tgz#1ede41c51fcf51bbbd6fd43669caaa4f0495aaa9" + integrity sha512-fPwcX4EvnSHuInCMItEhAGnaSEXRBjtzh9fOtsE6E1G6p7vl7edEeZe11QHf18+6+9gR5PbKV/sGKNaD8YaMeA== + dependencies: + follow-redirects "^1.14.8" + +call-bind@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.2.tgz#b1d4e89e688119c3c9a903ad30abb2f6a919be3c" + integrity sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA== + dependencies: + function-bind "^1.1.1" + get-intrinsic "^1.0.2" + +follow-redirects@^1.14.8: + version "1.15.2" + resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.2.tgz#b460864144ba63f2681096f274c4e57026da2c13" + integrity sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA== + +function-bind@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" + integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== + +get-intrinsic@^1.0.2: + version "1.1.3" + resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.1.3.tgz#063c84329ad93e83893c7f4f243ef63ffa351385" + integrity sha512-QJVz1Tj7MS099PevUG5jvnt9tSkXN8K14dxQlikJuPt4uD9hHAHjLyLBiLR5zELelBdD9QNRAXZzsJx0WaDL9A== + dependencies: + function-bind "^1.1.1" + has "^1.0.3" + has-symbols "^1.0.3" + +has-symbols@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.3.tgz#bb7b2c4349251dce87b125f7bdf874aa7c8b39f8" + integrity sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A== + +has@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796" + integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw== + dependencies: + function-bind "^1.1.1" + +object-inspect@^1.9.0: + version "1.12.2" + resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.2.tgz#c0641f26394532f28ab8d796ab954e43c009a8ea" + integrity sha512-z+cPxW0QGUp0mcqcsgQyLVRDoXFQbXOwBaqyF7VIgI4TWNQsDHrBpUQslRmIfAoYWdYzs6UlKJtB2XJpTaNSpQ== + +qs@^6.10.3: + version "6.11.0" + resolved "https://registry.yarnpkg.com/qs/-/qs-6.11.0.tgz#fd0d963446f7a65e1367e01abd85429453f0c37a" + integrity sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q== + dependencies: + side-channel "^1.0.4" + +side-channel@^1.0.4: + version "1.0.4" + resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.0.4.tgz#efce5c8fdc104ee751b25c58d4290011fa5ea2cf" + integrity sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw== + dependencies: + call-bind "^1.0.0" + get-intrinsic "^1.0.2" + object-inspect "^1.9.0" + +vue-router@^4.0.14: + version "4.1.5" + resolved "https://registry.yarnpkg.com/vue-router/-/vue-router-4.1.5.tgz#256f597e3f5a281a23352a6193aa6e342c8d9f9a" + integrity sha512-IsvoF5D2GQ/EGTs/Th4NQms9gd2NSqV+yylxIyp/OYp8xOwxmU8Kj/74E9DTSYAyH5LX7idVUngN3JSj1X4xcQ== + dependencies: + "@vue/devtools-api" "^6.1.4" + +vuex@^4.0.2: + version "4.0.2" + resolved "https://registry.yarnpkg.com/vuex/-/vuex-4.0.2.tgz#f896dbd5bf2a0e963f00c67e9b610de749ccacc9" + integrity sha512-M6r8uxELjZIK8kTKDGgZTYX/ahzblnzC4isU1tpmEuOIIKmV+TRdc+H4s8ds2NuZ7wpUTdGRzJRtoj+lI+pc0Q== + dependencies: + "@vue/devtools-api" "^6.0.0-beta.11"