fix: 修复关闭SSH终端标签页时会话状态未更新的问题

This commit is contained in:
2026-04-18 02:35:38 +08:00
commit 6e2e2f9387
43467 changed files with 5489040 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019-present chenshuai2144 (qixian.cs@outlook.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+64
View File
@@ -0,0 +1,64 @@
![](https://codecov.io/gh/umijs/route-utils/branch/master/graph/badge.svg) [![npm package](https://img.shields.io/npm/v/@umijs/route-utils.svg?style=flat-square?style=flat-square)](https://www.npmjs.com/package/@umijs/route-utils)
# @umijs/route-utils
## Usage
```bash
# npm
npm i @umijs/route-utils --save
## yarn
yarn add @umijs/route-utils
```
## API
```tsx
import { transformRoute, getMatchMenu } from '@umijs/route-utils';
const routes = [
{
path: '/welcome',
name: 'welcome',
},
{
path: '/admin',
name: 'admin',
access: 'canAdmin',
},
{
name: 'list.table-list',
path: '/list',
},
];
const { menuData, breadcrumb } = transformRoute(routes);
console.log(menuData[0].name); // welcome
console.log(breadcrumb.get('/welcome').name); // welcome
```
### MenuDataItem
```tsx
import { MenuDataItem } from '@umijs/route-utils';
export interface MenuDataItem {
routes?: MenuDataItem[];
hideChildrenInMenu?: boolean;
hideInMenu?: boolean;
icon?: React.ReactNode;
locale?: string | false;
name?: string;
key?: string;
pro_layout_parentKeys?: string[];
path?: string;
[key: string]: any;
}
```
## LICENSE
MIT
@@ -0,0 +1,8 @@
import type { MenuDataItem } from '../types';
/**
* 获取打平的 menuData
* 以 path 为 key
* @param menuData
*/
export declare const getFlatMenus: (menuData?: MenuDataItem[]) => Record<string, MenuDataItem>;
export default getFlatMenus;
+30
View File
@@ -0,0 +1,30 @@
import { stripQueryStringAndHashFromPath, childrenPropsName, } from '../transformRoute/transformRoute';
/**
* 获取打平的 menuData
* 以 path 为 key
* @param menuData
*/
export const getFlatMenus = (menuData = []) => {
let menus = {};
menuData.forEach((mapItem) => {
const item = { ...mapItem };
if (!item || !item.key) {
return;
}
if (!item.children && item[childrenPropsName]) {
item.children = item[childrenPropsName];
delete item[childrenPropsName];
}
const routerChildren = item.children || [];
menus[stripQueryStringAndHashFromPath(item.path || item.key || '/')] = {
...item,
};
menus[item.key || item.path || '/'] = { ...item };
if (routerChildren) {
menus = { ...menus, ...getFlatMenus(routerChildren) };
}
});
return menus;
};
export default getFlatMenus;
//# sourceMappingURL=getFlatMenus.js.map
@@ -0,0 +1 @@
{"version":3,"file":"getFlatMenus.js","sourceRoot":"","sources":["../../src/getFlatMenus/getFlatMenus.ts"],"names":[],"mappings":"AACA,OAAO,EACL,+BAA+B,EAC/B,iBAAiB,GAClB,MAAM,kCAAkC,CAAC;AAE1C;;;;GAIG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAC1B,WAA2B,EAAE,EACC,EAAE;IAChC,IAAI,KAAK,GAAiC,EAAE,CAAC;IAC7C,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC3B,MAAM,IAAI,GAAG,EAAE,GAAG,OAAO,EAAE,CAAC;QAC5B,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE;YACtB,OAAO;SACR;QACD,IAAI,CAAC,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,iBAAiB,CAAC,EAAE;YAC7C,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,iBAAiB,CAAC,CAAC;YACxC,OAAO,IAAI,CAAC,iBAAiB,CAAC,CAAC;SAChC;QACD,MAAM,cAAc,GAAG,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC;QAC3C,KAAK,CAAC,+BAA+B,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG;YACrE,GAAG,IAAI;SACR,CAAC;QACF,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,IAAI,IAAI,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,EAAE,CAAC;QAElD,IAAI,cAAc,EAAE;YAClB,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,GAAG,YAAY,CAAC,cAAc,CAAC,EAAE,CAAC;SACvD;IACH,CAAC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC;AACf,CAAC,CAAC;AAEF,eAAe,YAAY,CAAC"}
@@ -0,0 +1,10 @@
import type { MenuDataItem } from '../types';
export declare const getMenuMatches: (flatMenuKeys: string[] | undefined, path: string, exact?: boolean | undefined) => string[] | undefined;
/**
* 获取当前的选中菜单列表
* @param pathname
* @param menuData
* @returns MenuDataItem[]
*/
export declare const getMatchMenu: (pathname: string, menuData: MenuDataItem[], fullKeys?: boolean | undefined, exact?: boolean | undefined) => MenuDataItem[];
export default getMatchMenu;
+89
View File
@@ -0,0 +1,89 @@
//@ts-ignore
import { pathToRegexp } from '../path-to-regexp';
import getFlatMenu from '../getFlatMenus/getFlatMenus';
import { isUrl, stripQueryStringAndHashFromPath, } from '../transformRoute/transformRoute';
export const getMenuMatches = (flatMenuKeys = [], path, exact) => flatMenuKeys
.filter((item) => {
if (item === '/' && path === '/') {
return true;
}
if (item !== '/' && item !== '/*' && item && !isUrl(item)) {
const pathKey = stripQueryStringAndHashFromPath(item);
try {
// exact
if (exact) {
if (pathToRegexp(`${pathKey}`).test(path)) {
return true;
}
}
// /a
if (pathToRegexp(`${pathKey}`, []).test(path)) {
return true;
}
// /a/b/b
if (pathToRegexp(`${pathKey}/(.*)`).test(path)) {
return true;
}
}
catch (error) {
// console.log(error, path);
}
}
return false;
})
.sort((a, b) => {
// 如果完全匹配放到最后面
if (a === path) {
return 10;
}
if (b === path) {
return -10;
}
return a.substr(1).split('/').length - b.substr(1).split('/').length;
});
/**
* 获取当前的选中菜单列表
* @param pathname
* @param menuData
* @returns MenuDataItem[]
*/
export const getMatchMenu = (pathname, menuData,
/**
* 要不要展示全部的 key
*/
fullKeys, exact) => {
const flatMenus = getFlatMenu(menuData);
const flatMenuKeys = Object.keys(flatMenus);
let menuPathKeys = getMenuMatches(flatMenuKeys, pathname || '/', exact);
if (!menuPathKeys || menuPathKeys.length < 1) {
return [];
}
if (!fullKeys) {
menuPathKeys = [menuPathKeys[menuPathKeys.length - 1]];
}
return menuPathKeys
.map((menuPathKey) => {
const menuItem = flatMenus[menuPathKey] || {
pro_layout_parentKeys: '',
key: '',
};
// 去重
const map = new Map();
const parentItems = (menuItem.pro_layout_parentKeys || [])
.map((key) => {
if (map.has(key)) {
return null;
}
map.set(key, true);
return flatMenus[key];
})
.filter((item) => item);
if (menuItem.key) {
parentItems.push(menuItem);
}
return parentItems;
})
.flat(1);
};
export default getMatchMenu;
//# sourceMappingURL=getMatchMenu.js.map
@@ -0,0 +1 @@
{"version":3,"file":"getMatchMenu.js","sourceRoot":"","sources":["../../src/getMatchMenu/getMatchMenu.ts"],"names":[],"mappings":"AAAA,YAAY;AACZ,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,OAAO,WAAW,MAAM,8BAA8B,CAAC;AACvD,OAAO,EACL,KAAK,EACL,+BAA+B,GAChC,MAAM,kCAAkC,CAAC;AAE1C,MAAM,CAAC,MAAM,cAAc,GAAG,CAC5B,eAAyB,EAAE,EAC3B,IAAY,EACZ,KAAe,EACO,EAAE,CACxB,YAAY;KACT,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE;IACf,IAAI,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,GAAG,EAAE;QAChC,OAAO,IAAI,CAAC;KACb;IACD,IAAI,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE;QACzD,MAAM,OAAO,GAAG,+BAA+B,CAAC,IAAI,CAAC,CAAC;QACtD,IAAI;YACF,QAAQ;YACR,IAAI,KAAK,EAAE;gBACT,IAAI,YAAY,CAAC,GAAG,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;oBACzC,OAAO,IAAI,CAAC;iBACb;aACF;YACD,KAAK;YACL,IAAI,YAAY,CAAC,GAAG,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;gBAC7C,OAAO,IAAI,CAAC;aACb;YACD,SAAS;YACT,IAAI,YAAY,CAAC,GAAG,OAAO,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;gBAC9C,OAAO,IAAI,CAAC;aACb;SACF;QAAC,OAAO,KAAK,EAAE;YACd,4BAA4B;SAC7B;KACF;IACD,OAAO,KAAK,CAAC;AACf,CAAC,CAAC;KACD,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;IACb,cAAc;IACd,IAAI,CAAC,KAAK,IAAI,EAAE;QACd,OAAO,EAAE,CAAC;KACX;IACD,IAAI,CAAC,KAAK,IAAI,EAAE;QACd,OAAO,CAAC,EAAE,CAAC;KACZ;IACD,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC;AACvE,CAAC,CAAa,CAAC;AAEnB;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAC1B,QAAgB,EAChB,QAAwB;AACxB;;GAEG;AACH,QAAkB,EAClB,KAAe,EACC,EAAE;IAClB,MAAM,SAAS,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC;IACxC,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC5C,IAAI,YAAY,GAAG,cAAc,CAAC,YAAY,EAAE,QAAQ,IAAI,GAAG,EAAE,KAAK,CAAC,CAAC;IACxE,IAAI,CAAC,YAAY,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE;QAC5C,OAAO,EAAE,CAAC;KACX;IACD,IAAI,CAAC,QAAQ,EAAE;QACb,YAAY,GAAG,CAAC,YAAY,CAAC,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;KACxD;IACD,OAAO,YAAY;SAChB,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE;QACnB,MAAM,QAAQ,GAAG,SAAS,CAAC,WAAW,CAAC,IAAI;YACzC,qBAAqB,EAAE,EAAE;YACzB,GAAG,EAAE,EAAE;SACR,CAAC;QAEF,KAAK;QACL,MAAM,GAAG,GAAG,IAAI,GAAG,EAAE,CAAC;QACtB,MAAM,WAAW,GAAG,CAAC,QAAQ,CAAC,qBAAqB,IAAI,EAAE,CAAC;aACvD,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE;YACX,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;gBAChB,OAAO,IAAI,CAAC;aACb;YACD,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;YACnB,OAAO,SAAS,CAAC,GAAG,CAAC,CAAC;QACxB,CAAC,CAAC;aACD,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAmB,CAAC;QAC5C,IAAI,QAAQ,CAAC,GAAG,EAAE;YAChB,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;SAC5B;QACD,OAAO,WAAW,CAAC;IACrB,CAAC,CAAC;SACD,IAAI,CAAC,CAAC,CAAC,CAAC;AACb,CAAC,CAAC;AAEF,eAAe,YAAY,CAAC"}
+5
View File
@@ -0,0 +1,5 @@
import type { MenuDataItem } from './types';
export { default as transformRoute } from './transformRoute/transformRoute';
export { default as getFlatMenus } from './getFlatMenus/getFlatMenus';
export { default as getMatchMenu } from './getMatchMenu/getMatchMenu';
export type { MenuDataItem };
+4
View File
@@ -0,0 +1,4 @@
export { default as transformRoute } from './transformRoute/transformRoute';
export { default as getFlatMenus } from './getFlatMenus/getFlatMenus';
export { default as getMatchMenu } from './getMatchMenu/getMatchMenu';
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAC5E,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,6BAA6B,CAAC"}
+2
View File
@@ -0,0 +1,2 @@
declare function digest(data: string): String;
export default digest;
+308
View File
@@ -0,0 +1,308 @@
/* eslint-disable no-redeclare */
/* eslint-disable no-multi-assign */
/* eslint-disable no-param-reassign */
/* eslint-disable no-return-assign */
/* eslint-disable no-new-wrappers */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable no-var */
/* eslint-disable no-plusplus */
/* eslint-disable prefer-destructuring */
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable block-scoped-var */
/* eslint-disable vars-on-top */
/* eslint-disable no-bitwise */
/* eslint-disable no-cond-assign */
/*
* A JavaScript implementation of the SHA256 hash function.
*
* FILE: sha256.js
* VERSION: 0.8
* AUTHOR: Christoph Bichlmeier <informatik@zombiearena.de>
*
* NOTE: This version is not tested thoroughly!
*
* Copyright (c) 2003, Christoph Bichlmeier
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* ======================================================================
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* SHA256 logical functions */
function rotateRight(n, x) {
return (x >>> n) | (x << (32 - n));
}
function choice(x, y, z) {
return (x & y) ^ (~x & z);
}
function majority(x, y, z) {
return (x & y) ^ (x & z) ^ (y & z);
}
function sha256_Sigma0(x) {
return rotateRight(2, x) ^ rotateRight(13, x) ^ rotateRight(22, x);
}
function sha256_Sigma1(x) {
return rotateRight(6, x) ^ rotateRight(11, x) ^ rotateRight(25, x);
}
function sha256_sigma0(x) {
return rotateRight(7, x) ^ rotateRight(18, x) ^ (x >>> 3);
}
function sha256_sigma1(x) {
return rotateRight(17, x) ^ rotateRight(19, x) ^ (x >>> 10);
}
function sha256_expand(W, j) {
return (W[j & 0x0f] +=
sha256_sigma1(W[(j + 14) & 0x0f]) +
W[(j + 9) & 0x0f] +
sha256_sigma0(W[(j + 1) & 0x0f]));
}
/* Hash constant words K: */
const K256 = [
0x428a2f98,
0x71374491,
0xb5c0fbcf,
0xe9b5dba5,
0x3956c25b,
0x59f111f1,
0x923f82a4,
0xab1c5ed5,
0xd807aa98,
0x12835b01,
0x243185be,
0x550c7dc3,
0x72be5d74,
0x80deb1fe,
0x9bdc06a7,
0xc19bf174,
0xe49b69c1,
0xefbe4786,
0x0fc19dc6,
0x240ca1cc,
0x2de92c6f,
0x4a7484aa,
0x5cb0a9dc,
0x76f988da,
0x983e5152,
0xa831c66d,
0xb00327c8,
0xbf597fc7,
0xc6e00bf3,
0xd5a79147,
0x06ca6351,
0x14292967,
0x27b70a85,
0x2e1b2138,
0x4d2c6dfc,
0x53380d13,
0x650a7354,
0x766a0abb,
0x81c2c92e,
0x92722c85,
0xa2bfe8a1,
0xa81a664b,
0xc24b8b70,
0xc76c51a3,
0xd192e819,
0xd6990624,
0xf40e3585,
0x106aa070,
0x19a4c116,
0x1e376c08,
0x2748774c,
0x34b0bcb5,
0x391c0cb3,
0x4ed8aa4a,
0x5b9cca4f,
0x682e6ff3,
0x748f82ee,
0x78a5636f,
0x84c87814,
0x8cc70208,
0x90befffa,
0xa4506ceb,
0xbef9a3f7,
0xc67178f2,
];
/* global arrays */
let ihash;
let count;
let buffer;
const sha256_hex_digits = '0123456789abcdef';
/* Add 32-bit integers with 16-bit operations (bug in some JS-interpreters:
overflow) */
function safe_add(x, y) {
const lsw = (x & 0xffff) + (y & 0xffff);
const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xffff);
}
/* Initialise the SHA256 computation */
function sha256_init() {
ihash = new Array(8);
count = new Array(2);
buffer = new Array(64);
count[0] = count[1] = 0;
ihash[0] = 0x6a09e667;
ihash[1] = 0xbb67ae85;
ihash[2] = 0x3c6ef372;
ihash[3] = 0xa54ff53a;
ihash[4] = 0x510e527f;
ihash[5] = 0x9b05688c;
ihash[6] = 0x1f83d9ab;
ihash[7] = 0x5be0cd19;
}
/* Transform a 512-bit message block */
function sha256_transform() {
let a;
let b;
let c;
let d;
let e;
let f;
let g;
let h;
let T1;
let T2;
const W = new Array(16);
/* Initialize registers with the previous intermediate value */
a = ihash[0];
b = ihash[1];
c = ihash[2];
d = ihash[3];
e = ihash[4];
f = ihash[5];
g = ihash[6];
h = ihash[7];
/* make 32-bit words */
for (let i = 0; i < 16; i++)
W[i] =
buffer[(i << 2) + 3] |
(buffer[(i << 2) + 2] << 8) |
(buffer[(i << 2) + 1] << 16) |
(buffer[i << 2] << 24);
for (let j = 0; j < 64; j++) {
T1 = h + sha256_Sigma1(e) + choice(e, f, g) + K256[j];
if (j < 16)
T1 += W[j];
else
T1 += sha256_expand(W, j);
T2 = sha256_Sigma0(a) + majority(a, b, c);
h = g;
g = f;
f = e;
e = safe_add(d, T1);
d = c;
c = b;
b = a;
a = safe_add(T1, T2);
}
/* Compute the current intermediate hash value */
ihash[0] += a;
ihash[1] += b;
ihash[2] += c;
ihash[3] += d;
ihash[4] += e;
ihash[5] += f;
ihash[6] += g;
ihash[7] += h;
}
/* Read the next chunk of data and update the SHA256 computation */
function sha256_update(data, inputLen) {
let i;
let index;
let curpos = 0;
/* Compute number of bytes mod 64 */
index = (count[0] >> 3) & 0x3f;
const remainder = inputLen & 0x3f;
/* Update number of bits */
if ((count[0] += inputLen << 3) < inputLen << 3)
count[1]++;
count[1] += inputLen >> 29;
/* Transform as many times as possible */
for (i = 0; i + 63 < inputLen; i += 64) {
for (let j = index; j < 64; j++)
buffer[j] = data.charCodeAt(curpos++);
sha256_transform();
index = 0;
}
/* Buffer remaining input */
for (let j = 0; j < remainder; j++)
buffer[j] = data.charCodeAt(curpos++);
}
/* Finish the computation by operations such as padding */
function sha256_final() {
let index = (count[0] >> 3) & 0x3f;
buffer[index++] = 0x80;
if (index <= 56) {
for (let i = index; i < 56; i++)
buffer[i] = 0;
}
else {
for (let i = index; i < 64; i++)
buffer[i] = 0;
sha256_transform();
for (let i = 0; i < 56; i++)
buffer[i] = 0;
}
buffer[56] = (count[1] >>> 24) & 0xff;
buffer[57] = (count[1] >>> 16) & 0xff;
buffer[58] = (count[1] >>> 8) & 0xff;
buffer[59] = count[1] & 0xff;
buffer[60] = (count[0] >>> 24) & 0xff;
buffer[61] = (count[0] >>> 16) & 0xff;
buffer[62] = (count[0] >>> 8) & 0xff;
buffer[63] = count[0] & 0xff;
sha256_transform();
}
/* Split the internal hash values into an array of bytes */
function sha256_encode_bytes() {
let j = 0;
const output = new Array(32);
for (let i = 0; i < 8; i++) {
output[j++] = (ihash[i] >>> 24) & 0xff;
output[j++] = (ihash[i] >>> 16) & 0xff;
output[j++] = (ihash[i] >>> 8) & 0xff;
output[j++] = ihash[i] & 0xff;
}
return output;
}
/* Get the internal hash as a hex string */
function sha256_encode_hex() {
let output = new String();
for (let i = 0; i < 8; i++) {
for (let j = 28; j >= 0; j -= 4)
output += sha256_hex_digits.charAt((ihash[i] >>> j) & 0x0f);
}
return output;
}
/* Main function: returns a hex string representing the SHA256 value of the
given data */
function digest(data) {
sha256_init();
sha256_update(data, data.length);
sha256_final();
return sha256_encode_hex();
}
export default digest;
//# sourceMappingURL=sha265.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,17 @@
import type { MenuDataItem, Route, MessageDescriptor } from '../types';
export declare const childrenPropsName = "routes";
export declare function stripQueryStringAndHashFromPath(url: string): string;
export declare const isUrl: (path: string) => boolean;
export declare const getKeyByPath: (item: MenuDataItem) => string | undefined;
/**
* @param routeList 路由配置
* @param locale 是否使用国际化
* @param formatMessage 国际化的程序
* @param ignoreFilter 是否筛选掉不展示的 menuItem 项,plugin-layout需要所有项目来计算布局样式
* @returns { breadcrumb, menuData}
*/
declare const transformRoute: (routeList: Route[], locale?: boolean | undefined, formatMessage?: ((message: MessageDescriptor) => string) | undefined, ignoreFilter?: boolean | undefined) => {
breadcrumb: Map<string, MenuDataItem>;
menuData: MenuDataItem[];
};
export default transformRoute;
@@ -0,0 +1,336 @@
//@ts-ignore
import { pathToRegexp } from '../path-to-regexp';
import sha265 from '../sha265';
export const childrenPropsName = 'routes';
export function stripQueryStringAndHashFromPath(url) {
return url.split('?')[0].split('#')[0];
}
export const isUrl = (path) => {
if (!path.startsWith('http')) {
return false;
}
try {
const url = new URL(path);
return !!url;
}
catch (error) {
return false;
}
};
export const getKeyByPath = (item) => {
const { path } = item;
if (!path || path === '/') {
// 如果还是没有,用对象的hash 生成一个
try {
return `/${sha265(JSON.stringify(item))}`;
}
catch (error) {
// dom some thing
}
}
return path ? stripQueryStringAndHashFromPath(path) : path;
};
/**
* 获取locale,增加了一个功能,如果 locale = false,将不使用国际化
* @param item
* @param parentName
*/
const getItemLocaleName = (item, parentName) => {
const { name, locale } = item;
// 如果配置了 locale 并且 locale 为 false或 ""
if (('locale' in item && locale === false) || !name) {
return false;
}
return item.locale || `${parentName}.${name}`;
};
/**
* 如果不是 / 开头的和父节点做一下合并
* 如果是 / 开头的不作任何处理
* 如果是 url 也直接返回
* @param path
* @param parentPath
*/
const mergePath = (path = '', parentPath = '/') => {
if (path.endsWith('/*')) {
return path.replace('/*', '/');
}
if ((path || parentPath).startsWith('/')) {
return path;
}
if (isUrl(path)) {
return path;
}
return `/${parentPath}/${path}`.replace(/\/\//g, '/').replace(/\/\//g, '/');
};
// bigfish 的兼容准话
const bigfishCompatibleConversions = (route, props) => {
const { menu = {}, indexRoute, path = '' } = route;
const routerChildren = route.children || [];
const { name = route.name, icon = route.icon, hideChildren = route.hideChildren, flatMenu = route.flatMenu, } = menu; // 兼容平铺式写法
// 拼接 childrenRoutes, 处理存在 indexRoute 时的逻辑
const childrenList = indexRoute &&
// 如果只有 redirect,不用处理的
Object.keys(indexRoute).join(',') !== 'redirect'
? [
{
path,
menu,
...indexRoute,
},
].concat(routerChildren || [])
: routerChildren;
// 拼接返回的 menu 数据
const result = {
...route,
};
if (name) {
result.name = name;
}
if (icon) {
result.icon = icon;
}
if (childrenList && childrenList.length) {
/** 在菜单中隐藏子项 */
if (hideChildren) {
delete result.children;
return result;
}
// 需要重新进行一次
const finalChildren = formatter({
...props,
data: childrenList,
}, route);
/** 在菜单中只隐藏此项,子项往上提,仍旧展示 */
if (flatMenu) {
return finalChildren;
}
delete result[childrenPropsName];
}
return result;
};
const notNullArray = (value) => Array.isArray(value) && value.length > 0;
/**
*
* @param props
* @param parent
*/
function formatter(props, parent = { path: '/' }) {
const { data, formatMessage, parentName, locale: menuLocale } = props;
if (!data || !Array.isArray(data)) {
return [];
}
return data
.filter((item) => {
if (!item)
return false;
if (notNullArray(item.children))
return true;
if (item.path)
return true;
if (item.originPath)
return true;
if (item.layout)
return true;
// 重定向
if (item.redirect)
return false;
if (item.unaccessible)
return false;
return false;
})
.filter((item) => {
if (item?.menu?.name || item?.flatMenu || item?.menu?.flatMenu) {
return true;
}
// 显示指定在 menu 中隐藏该项
// layout 插件的功能,其实不应该存在的
if (item.menu === false) {
return false;
}
return true;
})
.map((finallyItem) => {
const item = {
...finallyItem,
path: finallyItem.path || finallyItem.originPath,
};
if (!item.children && item[childrenPropsName]) {
item.children = item[childrenPropsName];
delete item[childrenPropsName];
}
// 是否没有权限查看
// 这样就不会显示,是一个兼容性的方式
if (item.unaccessible) {
// eslint-disable-next-line no-param-reassign
delete item.name;
}
if (item.path === '*') {
item.path = '.';
}
if (item.path === '/*') {
item.path = '.';
}
if (!item.path && item.originPath) {
item.path = item.originPath;
}
return item;
})
.map((item = { path: '/' }) => {
const routerChildren = item.children || item[childrenPropsName] || [];
const path = mergePath(item.path, parent ? parent.path : '/');
const { name } = item;
const locale = getItemLocaleName(item, parentName || 'menu');
// if enableMenuLocale use item.name,
// close menu international
const localeName = locale !== false && menuLocale !== false && formatMessage && locale
? formatMessage({ id: locale, defaultMessage: name })
: name;
const {
// eslint-disable-next-line @typescript-eslint/naming-convention
pro_layout_parentKeys = [], children, icon, flatMenu, indexRoute, routes, ...restParent } = parent;
const item_pro_layout_parentKeys = new Set([
...pro_layout_parentKeys,
...(item.parentKeys || []),
]);
if (parent.key) {
item_pro_layout_parentKeys.add(parent.key);
}
const finallyItem = {
...restParent,
menu: undefined,
...item,
path,
locale,
key: item.key || getKeyByPath({ ...item, path }),
pro_layout_parentKeys: Array.from(item_pro_layout_parentKeys).filter((key) => key && key !== '/'),
};
if (localeName) {
finallyItem.name = localeName;
}
else {
delete finallyItem.name;
}
if (finallyItem.menu === undefined) {
delete finallyItem.menu;
}
if (notNullArray(routerChildren)) {
const formatterChildren = formatter({
...props,
data: routerChildren,
parentName: locale || '',
}, finallyItem);
if (notNullArray(formatterChildren)) {
finallyItem.children = formatterChildren;
}
}
return bigfishCompatibleConversions(finallyItem, props);
})
.flat(1);
}
/**
* 删除 hideInMenu 和 item.name 不存在的
*/
const defaultFilterMenuData = (menuData = []) => menuData
.filter((item) => item &&
(item.name || notNullArray(item.children)) &&
!item.hideInMenu &&
!item.redirect)
.map((item) => {
const newItem = { ...item };
const routerChildren = newItem.children || item[childrenPropsName] || [];
delete newItem[childrenPropsName];
if (notNullArray(routerChildren) &&
!newItem.hideChildrenInMenu &&
routerChildren.some((child) => child && !!child.name)) {
const newChildren = defaultFilterMenuData(routerChildren);
if (newChildren.length)
return {
...newItem,
children: newChildren,
};
}
return { ...item };
})
.filter((item) => item);
/**
* support pathToRegexp get string
*/
class RouteListMap extends Map {
get(pathname) {
let routeValue;
try {
// eslint-disable-next-line no-restricted-syntax
for (const [key, value] of this.entries()) {
const path = stripQueryStringAndHashFromPath(key);
if (!isUrl(key) &&
pathToRegexp(path, []).test(pathname)) {
routeValue = value;
break;
}
}
}
catch (error) {
routeValue = undefined;
}
return routeValue;
}
}
/**
* 获取面包屑映射
* @param MenuDataItem[] menuData 菜单配置
*/
const getBreadcrumbNameMap = (menuData) => {
// Map is used to ensure the order of keys
const routerMap = new RouteListMap();
const flattenMenuData = (data, parent) => {
data.forEach((menuItem) => {
const routerChildren = menuItem.children || menuItem[childrenPropsName] || [];
if (notNullArray(routerChildren)) {
flattenMenuData(routerChildren, menuItem);
}
// Reduce memory usage
const path = mergePath(menuItem.path, parent ? parent.path : '/');
routerMap.set(stripQueryStringAndHashFromPath(path), menuItem);
});
};
flattenMenuData(menuData);
return routerMap;
};
const clearChildren = (menuData = []) => {
return menuData
.map((item) => {
const routerChildren = item.children || item[childrenPropsName];
if (notNullArray(routerChildren)) {
const newChildren = clearChildren(routerChildren);
if (newChildren.length)
return { ...item };
}
const finallyItem = { ...item };
delete finallyItem[childrenPropsName];
delete finallyItem.children;
return finallyItem;
})
.filter((item) => item);
};
/**
* @param routeList 路由配置
* @param locale 是否使用国际化
* @param formatMessage 国际化的程序
* @param ignoreFilter 是否筛选掉不展示的 menuItem 项,plugin-layout需要所有项目来计算布局样式
* @returns { breadcrumb, menuData}
*/
const transformRoute = (routeList, locale, formatMessage, ignoreFilter) => {
const originalMenuData = formatter({
data: [...routeList].map((item) => ({ ...item })),
formatMessage,
locale,
});
const menuData = ignoreFilter
? clearChildren(originalMenuData)
: defaultFilterMenuData(originalMenuData);
// Map type used for internal logic
const breadcrumb = getBreadcrumbNameMap(originalMenuData);
return { breadcrumb, menuData };
};
export default transformRoute;
//# sourceMappingURL=transformRoute.js.map
File diff suppressed because one or more lines are too long
+21
View File
@@ -0,0 +1,21 @@
export interface Route extends MenuDataItem {
children?: Route[];
}
export interface MessageDescriptor {
id: any;
description?: string;
defaultMessage?: string;
}
export interface MenuDataItem {
children?: MenuDataItem[];
hideChildrenInMenu?: boolean;
hideInMenu?: boolean;
icon?: any;
locale?: string | false;
name?: string;
key?: string;
pro_layout_parentKeys?: string[];
path?: string;
parentKeys?: string[];
[key: string]: any;
}
+1
View File
@@ -0,0 +1 @@
//# sourceMappingURL=types.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
+35
View File
@@ -0,0 +1,35 @@
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { stripQueryStringAndHashFromPath, childrenPropsName } from '../transformRoute/transformRoute';
/**
* 获取打平的 menuData
* 以 path 为 key
* @param menuData
*/
var _getFlatMenus = function getFlatMenus() {
var menuData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var menus = {};
menuData.forEach(function (mapItem) {
var item = _objectSpread({}, mapItem);
if (!item || !item.key) {
return;
}
if (!item.children && item[childrenPropsName]) {
item.children = item[childrenPropsName];
delete item[childrenPropsName];
}
var routerChildren = item.children || [];
menus[stripQueryStringAndHashFromPath(item.path || item.key || '/')] = _objectSpread({}, item);
menus[item.key || item.path || '/'] = _objectSpread({}, item);
if (routerChildren) {
menus = _objectSpread(_objectSpread({}, menus), _getFlatMenus(routerChildren));
}
});
return menus;
};
export { _getFlatMenus as getFlatMenus };
export default _getFlatMenus;
+88
View File
@@ -0,0 +1,88 @@
//@ts-ignore
import { pathToRegexp } from '../path-to-regexp';
import getFlatMenu from '../getFlatMenus/getFlatMenus';
import { isUrl, stripQueryStringAndHashFromPath } from '../transformRoute/transformRoute';
export var getMenuMatches = function getMenuMatches() {
var flatMenuKeys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var path = arguments.length > 1 ? arguments[1] : undefined;
var exact = arguments.length > 2 ? arguments[2] : undefined;
return flatMenuKeys.filter(function (item) {
if (item === '/' && path === '/') {
return true;
}
if (item !== '/' && item !== '/*' && item && !isUrl(item)) {
var pathKey = stripQueryStringAndHashFromPath(item);
try {
// exact
if (exact) {
if (pathToRegexp("".concat(pathKey)).test(path)) {
return true;
}
}
// /a
if (pathToRegexp("".concat(pathKey), []).test(path)) {
return true;
}
// /a/b/b
if (pathToRegexp("".concat(pathKey, "/(.*)")).test(path)) {
return true;
}
} catch (error) {
// console.log(error, path);
}
}
return false;
}).sort(function (a, b) {
// 如果完全匹配放到最后面
if (a === path) {
return 10;
}
if (b === path) {
return -10;
}
return a.substr(1).split('/').length - b.substr(1).split('/').length;
});
};
/**
* 获取当前的选中菜单列表
* @param pathname
* @param menuData
* @returns MenuDataItem[]
*/
export var getMatchMenu = function getMatchMenu(pathname, menuData,
/**
* 要不要展示全部的 key
*/
fullKeys, exact) {
var flatMenus = getFlatMenu(menuData);
var flatMenuKeys = Object.keys(flatMenus);
var menuPathKeys = getMenuMatches(flatMenuKeys, pathname || '/', exact);
if (!menuPathKeys || menuPathKeys.length < 1) {
return [];
}
if (!fullKeys) {
menuPathKeys = [menuPathKeys[menuPathKeys.length - 1]];
}
return menuPathKeys.map(function (menuPathKey) {
var menuItem = flatMenus[menuPathKey] || {
pro_layout_parentKeys: '',
key: ''
};
// 去重
var map = new Map();
var parentItems = (menuItem.pro_layout_parentKeys || []).map(function (key) {
if (map.has(key)) {
return null;
}
map.set(key, true);
return flatMenus[key];
}).filter(function (item) {
return item;
});
if (menuItem.key) {
parentItems.push(menuItem);
}
return parentItems;
}).flat(1);
};
export default getMatchMenu;
+3
View File
@@ -0,0 +1,3 @@
export { default as transformRoute } from './transformRoute/transformRoute';
export { default as getFlatMenus } from './getFlatMenus/getFlatMenus';
export { default as getMatchMenu } from './getMatchMenu/getMatchMenu';
+457
View File
@@ -0,0 +1,457 @@
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.pathToRegexp = exports.tokensToRegexp = exports.regexpToFunction = exports.match = exports.tokensToFunction = exports.compile = exports.parse = void 0;
/**
* Tokenize input string.
*/
function lexer(str) {
var tokens = [];
var i = 0;
while (i < str.length) {
var char = str[i];
if (char === '*' || char === '+' || char === '?') {
tokens.push({
type: 'MODIFIER',
index: i,
value: str[i++]
});
continue;
}
if (char === '\\') {
tokens.push({
type: 'ESCAPED_CHAR',
index: i++,
value: str[i++]
});
continue;
}
if (char === '{') {
tokens.push({
type: 'OPEN',
index: i,
value: str[i++]
});
continue;
}
if (char === '}') {
tokens.push({
type: 'CLOSE',
index: i,
value: str[i++]
});
continue;
}
if (char === ':') {
var name = '';
var j = i + 1;
while (j < str.length) {
var code = str.charCodeAt(j);
if (
// `0-9`
code >= 48 && code <= 57 ||
// `A-Z`
code >= 65 && code <= 90 ||
// `a-z`
code >= 97 && code <= 122 ||
// `_`
code === 95) {
name += str[j++];
continue;
}
break;
}
if (!name) throw new TypeError('Missing parameter name at ' + i);
tokens.push({
type: 'NAME',
index: i,
value: name
});
i = j;
continue;
}
if (char === '(') {
var count = 1;
var pattern = '';
var j = i + 1;
if (str[j] === '?') {
throw new TypeError('Pattern cannot start with "?" at ' + j);
}
while (j < str.length) {
if (str[j] === '\\') {
pattern += str[j++] + str[j++];
continue;
}
if (str[j] === ')') {
count--;
if (count === 0) {
j++;
break;
}
} else if (str[j] === '(') {
count++;
if (str[j + 1] !== '?') {
throw new TypeError('Capturing groups are not allowed at ' + j);
}
}
pattern += str[j++];
}
if (count) throw new TypeError('Unbalanced pattern at ' + i);
if (!pattern) throw new TypeError('Missing pattern at ' + i);
tokens.push({
type: 'PATTERN',
index: i,
value: pattern
});
i = j;
continue;
}
tokens.push({
type: 'CHAR',
index: i,
value: str[i++]
});
}
tokens.push({
type: 'END',
index: i,
value: ''
});
return tokens;
}
/**
* Parse a string for the raw tokens.
*/
function parse(str, options) {
if (options === void 0) {
// eslint-disable-next-line no-param-reassign
options = {};
}
var tokens = lexer(str);
var _a = options.prefixes,
prefixes = _a === void 0 ? './' : _a;
var defaultPattern = '[^' + escapeString(options.delimiter || '/#?') + ']+?';
var result = [];
var key = 0;
var i = 0;
var path = '';
var tryConsume = function tryConsume(type) {
if (i < tokens.length && tokens[i].type === type) return tokens[i++].value;
};
var mustConsume = function mustConsume(type) {
var value = tryConsume(type);
if (value !== undefined) return value;
var _a = tokens[i],
nextType = _a.type,
index = _a.index;
throw new TypeError('Unexpected ' + nextType + ' at ' + index + ', expected ' + type);
};
var consumeText = function consumeText() {
var result = '';
var value;
// tslint:disable-next-line
while (value = tryConsume('CHAR') || tryConsume('ESCAPED_CHAR')) {
result += value;
}
return result;
};
while (i < tokens.length) {
var char = tryConsume('CHAR');
var name = tryConsume('NAME');
var pattern = tryConsume('PATTERN');
if (name || pattern) {
var prefix = char || '';
if (prefixes.indexOf(prefix) === -1) {
path += prefix;
prefix = '';
}
if (path) {
result.push(path);
path = '';
}
result.push({
name: name || key++,
prefix: prefix,
suffix: '',
pattern: pattern || defaultPattern,
modifier: tryConsume('MODIFIER') || ''
});
continue;
}
var value = char || tryConsume('ESCAPED_CHAR');
if (value) {
path += value;
continue;
}
if (path) {
result.push(path);
path = '';
}
var open = tryConsume('OPEN');
if (open) {
var prefix = consumeText();
var name_1 = tryConsume('NAME') || '';
var pattern_1 = tryConsume('PATTERN') || '';
var suffix = consumeText();
mustConsume('CLOSE');
result.push({
name: name_1 || (pattern_1 ? key++ : ''),
pattern: name_1 && !pattern_1 ? defaultPattern : pattern_1,
prefix: prefix,
suffix: suffix,
modifier: tryConsume('MODIFIER') || ''
});
continue;
}
mustConsume('END');
}
return result;
}
exports.parse = parse;
/**
* Compile a string to a template function for the path.
*/
function compile(str, options) {
return tokensToFunction(parse(str, options), options);
}
exports.compile = compile;
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction(tokens, options) {
if (options === void 0) {
// eslint-disable-next-line no-param-reassign
options = {};
}
var reFlags = flags(options);
var _a = options.encode,
encode = _a === void 0 ? function (x) {
return x;
} : _a,
_b = options.validate,
validate = _b === void 0 ? true : _b;
// Compile all the tokens into regexps.
var matches = tokens.map(function (token) {
if (_typeof(token) === 'object') {
return new RegExp('^(?:' + token.pattern + ')$', reFlags);
}
});
return function (data) {
var path = '';
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === 'string') {
path += token;
continue;
}
var value = data ? data[token.name] : undefined;
var optional = token.modifier === '?' || token.modifier === '*';
var repeat = token.modifier === '*' || token.modifier === '+';
if (Array.isArray(value)) {
if (!repeat) {
throw new TypeError('Expected "' + token.name + '" to not repeat, but got an array');
}
if (value.length === 0) {
if (optional) continue;
throw new TypeError('Expected "' + token.name + '" to not be empty');
}
for (var j = 0; j < value.length; j++) {
var segment = encode(value[j], token);
if (validate && !matches[i].test(segment)) {
throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"');
}
path += token.prefix + segment + token.suffix;
}
continue;
}
if (typeof value === 'string' || typeof value === 'number') {
var segment = encode(String(value), token);
if (validate && !matches[i].test(segment)) {
throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"');
}
path += token.prefix + segment + token.suffix;
continue;
}
if (optional) continue;
var typeOfMessage = repeat ? 'an array' : 'a string';
throw new TypeError('Expected "' + token.name + '" to be ' + typeOfMessage);
}
return path;
};
}
exports.tokensToFunction = tokensToFunction;
/**
* Create path match function from `path-to-regexp` spec.
*/
function match(str, options) {
var keys = [];
var re = pathToRegexp(str, keys, options);
return regexpToFunction(re, keys, options);
}
exports.match = match;
/**
* Create a path match function from `path-to-regexp` output.
*/
function regexpToFunction(re, keys, options) {
if (options === void 0) {
// eslint-disable-next-line no-param-reassign
options = {};
}
var _a = options.decode,
decode = _a === void 0 ? function (x) {
return x;
} : _a;
return function (pathname) {
var m = re.exec(pathname);
if (!m) return false;
var path = m[0],
index = m.index;
var params = Object.create(null);
var _loop_1 = function _loop_1(i) {
// tslint:disable-next-line
if (m[i] === undefined) return 'continue';
var key = keys[i - 1];
if (key.modifier === '*' || key.modifier === '+') {
params[key.name] = m[i].split(key.prefix + key.suffix).map(function (value) {
return decode(value, key);
});
} else {
params[key.name] = decode(m[i], key);
}
};
for (var i = 1; i < m.length; i++) {
_loop_1(i);
}
return {
path: path,
index: index,
params: params
};
};
}
exports.regexpToFunction = regexpToFunction;
/**
* Escape a regular expression string.
*/
function escapeString(str) {
return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1');
}
/**
* Get the flags for a regexp from the options.
*/
function flags(options) {
return options && options.sensitive ? '' : 'i';
}
/**
* Pull out keys from a regexp.
*/
function regexpToRegexp(path, keys) {
if (!keys) return path;
// Use a negative lookahead to match only capturing groups.
var groups = path.source.match(/\((?!\?)/g);
if (groups) {
for (var i = 0; i < groups.length; i++) {
keys.push({
name: i,
prefix: '',
suffix: '',
modifier: '',
pattern: ''
});
}
}
return path;
}
/**
* Transform an array into a regexp.
*/
function arrayToRegexp(paths, keys, options) {
var parts = paths.map(function (path) {
return pathToRegexp(path, keys, options).source;
});
return new RegExp('(?:' + parts.join('|') + ')', flags(options));
}
/**
* Create a path regexp from string input.
*/
function stringToRegexp(path, keys, options) {
return tokensToRegexp(parse(path, options), keys, options);
}
/**
* Expose a function for taking tokens and returning a RegExp.
*/
function tokensToRegexp(tokens, keys, options) {
if (options === void 0) {
// eslint-disable-next-line no-param-reassign
options = {};
}
var _a = options.strict,
strict = _a === void 0 ? false : _a,
_b = options.start,
start = _b === void 0 ? true : _b,
_c = options.end,
end = _c === void 0 ? true : _c,
_d = options.encode,
encode = _d === void 0 ? function (x) {
return x;
} : _d;
var endsWith = '[' + escapeString(options.endsWith || '') + ']|$';
var delimiter = '[' + escapeString(options.delimiter || '/#?') + ']';
var route = start ? '^' : '';
// Iterate over the tokens and create our regexp string.
for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
var token = tokens_1[_i];
if (typeof token === 'string') {
route += escapeString(encode(token));
} else {
var prefix = escapeString(encode(token.prefix));
var suffix = escapeString(encode(token.suffix));
if (token.pattern) {
if (keys) keys.push(token);
if (prefix || suffix) {
if (token.modifier === '+' || token.modifier === '*') {
var mod = token.modifier === '*' ? '?' : '';
route += '(?:' + prefix + '((?:' + token.pattern + ')(?:' + suffix + prefix + '(?:' + token.pattern + '))*)' + suffix + ')' + mod;
} else {
route += '(?:' + prefix + '(' + token.pattern + ')' + suffix + ')' + token.modifier;
}
} else {
route += '(' + token.pattern + ')' + token.modifier;
}
} else {
route += '(?:' + prefix + suffix + ')' + token.modifier;
}
}
}
if (end) {
if (!strict) route += delimiter + '?';
route += !options.endsWith ? '$' : '(?=' + endsWith + ')';
} else {
var endToken = tokens[tokens.length - 1];
var isEndDelimited = typeof endToken === 'string' ? delimiter.indexOf(endToken[endToken.length - 1]) > -1 :
// tslint:disable-next-line
endToken === undefined;
if (!strict) {
route += '(?:' + delimiter + '(?=' + endsWith + '))?';
}
if (!isEndDelimited) {
route += '(?=' + delimiter + '|' + endsWith + ')';
}
}
return new RegExp(route, flags(options));
}
exports.tokensToRegexp = tokensToRegexp;
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array can be passed in for the keys, which will hold the
* placeholder key descriptions. For example, using `/user/:id`, `keys` will
* contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
*/
function pathToRegexp(path, keys, options) {
if (path instanceof RegExp) return regexpToRegexp(path, keys);
if (Array.isArray(path)) return arrayToRegexp(path, keys, options);
return stringToRegexp(path, keys, options);
}
exports.pathToRegexp = pathToRegexp;
+223
View File
@@ -0,0 +1,223 @@
/* eslint-disable no-redeclare */
/* eslint-disable no-multi-assign */
/* eslint-disable no-param-reassign */
/* eslint-disable no-return-assign */
/* eslint-disable no-new-wrappers */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable no-var */
/* eslint-disable no-plusplus */
/* eslint-disable prefer-destructuring */
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable block-scoped-var */
/* eslint-disable vars-on-top */
/* eslint-disable no-bitwise */
/* eslint-disable no-cond-assign */
/*
* A JavaScript implementation of the SHA256 hash function.
*
* FILE: sha256.js
* VERSION: 0.8
* AUTHOR: Christoph Bichlmeier <informatik@zombiearena.de>
*
* NOTE: This version is not tested thoroughly!
*
* Copyright (c) 2003, Christoph Bichlmeier
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* ======================================================================
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* SHA256 logical functions */
function rotateRight(n, x) {
return x >>> n | x << 32 - n;
}
function choice(x, y, z) {
return x & y ^ ~x & z;
}
function majority(x, y, z) {
return x & y ^ x & z ^ y & z;
}
function sha256_Sigma0(x) {
return rotateRight(2, x) ^ rotateRight(13, x) ^ rotateRight(22, x);
}
function sha256_Sigma1(x) {
return rotateRight(6, x) ^ rotateRight(11, x) ^ rotateRight(25, x);
}
function sha256_sigma0(x) {
return rotateRight(7, x) ^ rotateRight(18, x) ^ x >>> 3;
}
function sha256_sigma1(x) {
return rotateRight(17, x) ^ rotateRight(19, x) ^ x >>> 10;
}
function sha256_expand(W, j) {
return W[j & 0x0f] += sha256_sigma1(W[j + 14 & 0x0f]) + W[j + 9 & 0x0f] + sha256_sigma0(W[j + 1 & 0x0f]);
}
/* Hash constant words K: */
var K256 = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
/* global arrays */
var ihash;
var count;
var buffer;
var sha256_hex_digits = '0123456789abcdef';
/* Add 32-bit integers with 16-bit operations (bug in some JS-interpreters:
overflow) */
function safe_add(x, y) {
var lsw = (x & 0xffff) + (y & 0xffff);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return msw << 16 | lsw & 0xffff;
}
/* Initialise the SHA256 computation */
function sha256_init() {
ihash = new Array(8);
count = new Array(2);
buffer = new Array(64);
count[0] = count[1] = 0;
ihash[0] = 0x6a09e667;
ihash[1] = 0xbb67ae85;
ihash[2] = 0x3c6ef372;
ihash[3] = 0xa54ff53a;
ihash[4] = 0x510e527f;
ihash[5] = 0x9b05688c;
ihash[6] = 0x1f83d9ab;
ihash[7] = 0x5be0cd19;
}
/* Transform a 512-bit message block */
function sha256_transform() {
var a;
var b;
var c;
var d;
var e;
var f;
var g;
var h;
var T1;
var T2;
var W = new Array(16);
/* Initialize registers with the previous intermediate value */
a = ihash[0];
b = ihash[1];
c = ihash[2];
d = ihash[3];
e = ihash[4];
f = ihash[5];
g = ihash[6];
h = ihash[7];
/* make 32-bit words */
for (var i = 0; i < 16; i++) W[i] = buffer[(i << 2) + 3] | buffer[(i << 2) + 2] << 8 | buffer[(i << 2) + 1] << 16 | buffer[i << 2] << 24;
for (var j = 0; j < 64; j++) {
T1 = h + sha256_Sigma1(e) + choice(e, f, g) + K256[j];
if (j < 16) T1 += W[j];else T1 += sha256_expand(W, j);
T2 = sha256_Sigma0(a) + majority(a, b, c);
h = g;
g = f;
f = e;
e = safe_add(d, T1);
d = c;
c = b;
b = a;
a = safe_add(T1, T2);
}
/* Compute the current intermediate hash value */
ihash[0] += a;
ihash[1] += b;
ihash[2] += c;
ihash[3] += d;
ihash[4] += e;
ihash[5] += f;
ihash[6] += g;
ihash[7] += h;
}
/* Read the next chunk of data and update the SHA256 computation */
function sha256_update(data, inputLen) {
var i;
var index;
var curpos = 0;
/* Compute number of bytes mod 64 */
index = count[0] >> 3 & 0x3f;
var remainder = inputLen & 0x3f;
/* Update number of bits */
if ((count[0] += inputLen << 3) < inputLen << 3) count[1]++;
count[1] += inputLen >> 29;
/* Transform as many times as possible */
for (i = 0; i + 63 < inputLen; i += 64) {
for (var j = index; j < 64; j++) buffer[j] = data.charCodeAt(curpos++);
sha256_transform();
index = 0;
}
/* Buffer remaining input */
for (var _j = 0; _j < remainder; _j++) buffer[_j] = data.charCodeAt(curpos++);
}
/* Finish the computation by operations such as padding */
function sha256_final() {
var index = count[0] >> 3 & 0x3f;
buffer[index++] = 0x80;
if (index <= 56) {
for (var i = index; i < 56; i++) buffer[i] = 0;
} else {
for (var _i = index; _i < 64; _i++) buffer[_i] = 0;
sha256_transform();
for (var _i2 = 0; _i2 < 56; _i2++) buffer[_i2] = 0;
}
buffer[56] = count[1] >>> 24 & 0xff;
buffer[57] = count[1] >>> 16 & 0xff;
buffer[58] = count[1] >>> 8 & 0xff;
buffer[59] = count[1] & 0xff;
buffer[60] = count[0] >>> 24 & 0xff;
buffer[61] = count[0] >>> 16 & 0xff;
buffer[62] = count[0] >>> 8 & 0xff;
buffer[63] = count[0] & 0xff;
sha256_transform();
}
/* Split the internal hash values into an array of bytes */
function sha256_encode_bytes() {
var j = 0;
var output = new Array(32);
for (var i = 0; i < 8; i++) {
output[j++] = ihash[i] >>> 24 & 0xff;
output[j++] = ihash[i] >>> 16 & 0xff;
output[j++] = ihash[i] >>> 8 & 0xff;
output[j++] = ihash[i] & 0xff;
}
return output;
}
/* Get the internal hash as a hex string */
function sha256_encode_hex() {
var output = new String();
for (var i = 0; i < 8; i++) {
for (var j = 28; j >= 0; j -= 4) output += sha256_hex_digits.charAt(ihash[i] >>> j & 0x0f);
}
return output;
}
/* Main function: returns a hex string representing the SHA256 value of the
given data */
function digest(data) {
sha256_init();
sha256_update(data, data.length);
sha256_final();
return sha256_encode_hex();
}
export default digest;
+394
View File
@@ -0,0 +1,394 @@
var _excluded = ["pro_layout_parentKeys", "children", "icon", "flatMenu", "indexRoute", "routes"];
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); }
function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
//@ts-ignore
import { pathToRegexp } from '../path-to-regexp';
import sha265 from '../sha265';
export var childrenPropsName = 'routes';
export function stripQueryStringAndHashFromPath(url) {
return url.split('?')[0].split('#')[0];
}
export var isUrl = function isUrl(path) {
if (!path.startsWith('http')) {
return false;
}
try {
var url = new URL(path);
return !!url;
} catch (error) {
return false;
}
};
export var getKeyByPath = function getKeyByPath(item) {
var path = item.path;
if (!path || path === '/') {
// 如果还是没有,用对象的hash 生成一个
try {
return "/".concat(sha265(JSON.stringify(item)));
} catch (error) {
// dom some thing
}
}
return path ? stripQueryStringAndHashFromPath(path) : path;
};
/**
* 获取locale,增加了一个功能,如果 locale = false,将不使用国际化
* @param item
* @param parentName
*/
var getItemLocaleName = function getItemLocaleName(item, parentName) {
var name = item.name,
locale = item.locale;
// 如果配置了 locale 并且 locale 为 false或 ""
if ('locale' in item && locale === false || !name) {
return false;
}
return item.locale || "".concat(parentName, ".").concat(name);
};
/**
* 如果不是 / 开头的和父节点做一下合并
* 如果是 / 开头的不作任何处理
* 如果是 url 也直接返回
* @param path
* @param parentPath
*/
var mergePath = function mergePath() {
var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var parentPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '/';
if (path.endsWith('/*')) {
return path.replace('/*', '/');
}
if ((path || parentPath).startsWith('/')) {
return path;
}
if (isUrl(path)) {
return path;
}
return "/".concat(parentPath, "/").concat(path).replace(/\/\//g, '/').replace(/\/\//g, '/');
};
// bigfish 的兼容准话
var bigfishCompatibleConversions = function bigfishCompatibleConversions(route, props) {
var _route$menu = route.menu,
menu = _route$menu === void 0 ? {} : _route$menu,
indexRoute = route.indexRoute,
_route$path = route.path,
path = _route$path === void 0 ? '' : _route$path;
var routerChildren = route.children || [];
var _menu$name = menu.name,
name = _menu$name === void 0 ? route.name : _menu$name,
_menu$icon = menu.icon,
icon = _menu$icon === void 0 ? route.icon : _menu$icon,
_menu$hideChildren = menu.hideChildren,
hideChildren = _menu$hideChildren === void 0 ? route.hideChildren : _menu$hideChildren,
_menu$flatMenu = menu.flatMenu,
flatMenu = _menu$flatMenu === void 0 ? route.flatMenu : _menu$flatMenu; // 兼容平铺式写法
// 拼接 childrenRoutes, 处理存在 indexRoute 时的逻辑
var childrenList = indexRoute &&
// 如果只有 redirect,不用处理的
Object.keys(indexRoute).join(',') !== 'redirect' ? [_objectSpread({
path: path,
menu: menu
}, indexRoute)].concat(routerChildren || []) : routerChildren;
// 拼接返回的 menu 数据
var result = _objectSpread({}, route);
if (name) {
result.name = name;
}
if (icon) {
result.icon = icon;
}
if (childrenList && childrenList.length) {
/** 在菜单中隐藏子项 */
if (hideChildren) {
delete result.children;
return result;
}
// 需要重新进行一次
var finalChildren = formatter(_objectSpread(_objectSpread({}, props), {}, {
data: childrenList
}), route);
/** 在菜单中只隐藏此项,子项往上提,仍旧展示 */
if (flatMenu) {
return finalChildren;
}
delete result[childrenPropsName];
}
return result;
};
var notNullArray = function notNullArray(value) {
return Array.isArray(value) && value.length > 0;
};
/**
*
* @param props
* @param parent
*/
function formatter(props) {
var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
path: '/'
};
var data = props.data,
formatMessage = props.formatMessage,
parentName = props.parentName,
menuLocale = props.locale;
if (!data || !Array.isArray(data)) {
return [];
}
return data.filter(function (item) {
if (!item) return false;
if (notNullArray(item.children)) return true;
if (item.path) return true;
if (item.originPath) return true;
if (item.layout) return true;
// 重定向
if (item.redirect) return false;
if (item.unaccessible) return false;
return false;
}).filter(function (item) {
var _item$menu, _item$menu2;
if ((item === null || item === void 0 ? void 0 : (_item$menu = item.menu) === null || _item$menu === void 0 ? void 0 : _item$menu.name) || (item === null || item === void 0 ? void 0 : item.flatMenu) || (item === null || item === void 0 ? void 0 : (_item$menu2 = item.menu) === null || _item$menu2 === void 0 ? void 0 : _item$menu2.flatMenu)) {
return true;
}
// 显示指定在 menu 中隐藏该项
// layout 插件的功能,其实不应该存在的
if (item.menu === false) {
return false;
}
return true;
}).map(function (finallyItem) {
var item = _objectSpread(_objectSpread({}, finallyItem), {}, {
path: finallyItem.path || finallyItem.originPath
});
if (!item.children && item[childrenPropsName]) {
item.children = item[childrenPropsName];
delete item[childrenPropsName];
}
// 是否没有权限查看
// 这样就不会显示,是一个兼容性的方式
if (item.unaccessible) {
// eslint-disable-next-line no-param-reassign
delete item.name;
}
if (item.path === '*') {
item.path = '.';
}
if (item.path === '/*') {
item.path = '.';
}
if (!item.path && item.originPath) {
item.path = item.originPath;
}
return item;
}).map(function () {
var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
path: '/'
};
var routerChildren = item.children || item[childrenPropsName] || [];
var path = mergePath(item.path, parent ? parent.path : '/');
var name = item.name;
var locale = getItemLocaleName(item, parentName || 'menu');
// if enableMenuLocale use item.name,
// close menu international
var localeName = locale !== false && menuLocale !== false && formatMessage && locale ? formatMessage({
id: locale,
defaultMessage: name
}) : name;
var _parent$pro_layout_pa = parent.pro_layout_parentKeys,
pro_layout_parentKeys = _parent$pro_layout_pa === void 0 ? [] : _parent$pro_layout_pa,
children = parent.children,
icon = parent.icon,
flatMenu = parent.flatMenu,
indexRoute = parent.indexRoute,
routes = parent.routes,
restParent = _objectWithoutProperties(parent, _excluded);
var item_pro_layout_parentKeys = new Set([].concat(_toConsumableArray(pro_layout_parentKeys), _toConsumableArray(item.parentKeys || [])));
if (parent.key) {
item_pro_layout_parentKeys.add(parent.key);
}
var finallyItem = _objectSpread(_objectSpread(_objectSpread({}, restParent), {}, {
menu: undefined
}, item), {}, {
path: path,
locale: locale,
key: item.key || getKeyByPath(_objectSpread(_objectSpread({}, item), {}, {
path: path
})),
pro_layout_parentKeys: Array.from(item_pro_layout_parentKeys).filter(function (key) {
return key && key !== '/';
})
});
if (localeName) {
finallyItem.name = localeName;
} else {
delete finallyItem.name;
}
if (finallyItem.menu === undefined) {
delete finallyItem.menu;
}
if (notNullArray(routerChildren)) {
var formatterChildren = formatter(_objectSpread(_objectSpread({}, props), {}, {
data: routerChildren,
parentName: locale || ''
}), finallyItem);
if (notNullArray(formatterChildren)) {
finallyItem.children = formatterChildren;
}
}
return bigfishCompatibleConversions(finallyItem, props);
}).flat(1);
}
/**
* 删除 hideInMenu 和 item.name 不存在的
*/
var _defaultFilterMenuData = function defaultFilterMenuData() {
var menuData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
return menuData.filter(function (item) {
return item && (item.name || notNullArray(item.children)) && !item.hideInMenu && !item.redirect;
}).map(function (item) {
var newItem = _objectSpread({}, item);
var routerChildren = newItem.children || item[childrenPropsName] || [];
delete newItem[childrenPropsName];
if (notNullArray(routerChildren) && !newItem.hideChildrenInMenu && routerChildren.some(function (child) {
return child && !!child.name;
})) {
var newChildren = _defaultFilterMenuData(routerChildren);
if (newChildren.length) return _objectSpread(_objectSpread({}, newItem), {}, {
children: newChildren
});
}
return _objectSpread({}, item);
}).filter(function (item) {
return item;
});
};
/**
* support pathToRegexp get string
*/
var RouteListMap = /*#__PURE__*/function (_Map) {
function RouteListMap() {
_classCallCheck(this, RouteListMap);
return _callSuper(this, RouteListMap, arguments);
}
_inherits(RouteListMap, _Map);
return _createClass(RouteListMap, [{
key: "get",
value: function get(pathname) {
var routeValue;
try {
// eslint-disable-next-line no-restricted-syntax
var _iterator = _createForOfIteratorHelper(this.entries()),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray(_step.value, 2),
key = _step$value[0],
value = _step$value[1];
var path = stripQueryStringAndHashFromPath(key);
if (!isUrl(key) && pathToRegexp(path, []).test(pathname)) {
routeValue = value;
break;
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
} catch (error) {
routeValue = undefined;
}
return routeValue;
}
}]);
}(/*#__PURE__*/_wrapNativeSuper(Map));
/**
* 获取面包屑映射
* @param MenuDataItem[] menuData 菜单配置
*/
var getBreadcrumbNameMap = function getBreadcrumbNameMap(menuData) {
// Map is used to ensure the order of keys
var routerMap = new RouteListMap();
var _flattenMenuData = function flattenMenuData(data, parent) {
data.forEach(function (menuItem) {
var routerChildren = menuItem.children || menuItem[childrenPropsName] || [];
if (notNullArray(routerChildren)) {
_flattenMenuData(routerChildren, menuItem);
}
// Reduce memory usage
var path = mergePath(menuItem.path, parent ? parent.path : '/');
routerMap.set(stripQueryStringAndHashFromPath(path), menuItem);
});
};
_flattenMenuData(menuData);
return routerMap;
};
var _clearChildren = function clearChildren() {
var menuData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
return menuData.map(function (item) {
var routerChildren = item.children || item[childrenPropsName];
if (notNullArray(routerChildren)) {
var newChildren = _clearChildren(routerChildren);
if (newChildren.length) return _objectSpread({}, item);
}
var finallyItem = _objectSpread({}, item);
delete finallyItem[childrenPropsName];
delete finallyItem.children;
return finallyItem;
}).filter(function (item) {
return item;
});
};
/**
* @param routeList 路由配置
* @param locale 是否使用国际化
* @param formatMessage 国际化的程序
* @param ignoreFilter 是否筛选掉不展示的 menuItem 项,plugin-layout需要所有项目来计算布局样式
* @returns { breadcrumb, menuData}
*/
var transformRoute = function transformRoute(routeList, locale, formatMessage, ignoreFilter) {
var originalMenuData = formatter({
data: _toConsumableArray(routeList).map(function (item) {
return _objectSpread({}, item);
}),
formatMessage: formatMessage,
locale: locale
});
var menuData = ignoreFilter ? _clearChildren(originalMenuData) : _defaultFilterMenuData(originalMenuData);
// Map type used for internal logic
var breadcrumb = getBreadcrumbNameMap(originalMenuData);
return {
breadcrumb: breadcrumb,
menuData: menuData
};
};
export default transformRoute;
+1
View File
@@ -0,0 +1 @@
export {};
+40
View File
@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getFlatMenus = exports.default = void 0;
var _transformRoute = require("../transformRoute/transformRoute");
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
/**
* 获取打平的 menuData
* 以 path 为 key
* @param menuData
*/
var _getFlatMenus = exports.getFlatMenus = function getFlatMenus() {
var menuData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var menus = {};
menuData.forEach(function (mapItem) {
var item = _objectSpread({}, mapItem);
if (!item || !item.key) {
return;
}
if (!item.children && item[_transformRoute.childrenPropsName]) {
item.children = item[_transformRoute.childrenPropsName];
delete item[_transformRoute.childrenPropsName];
}
var routerChildren = item.children || [];
menus[(0, _transformRoute.stripQueryStringAndHashFromPath)(item.path || item.key || '/')] = _objectSpread({}, item);
menus[item.key || item.path || '/'] = _objectSpread({}, item);
if (routerChildren) {
menus = _objectSpread(_objectSpread({}, menus), _getFlatMenus(routerChildren));
}
});
return menus;
};
var _default = exports.default = _getFlatMenus;
+96
View File
@@ -0,0 +1,96 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getMenuMatches = exports.getMatchMenu = exports.default = void 0;
var _pathToRegexp = require("../path-to-regexp");
var _getFlatMenus = _interopRequireDefault(require("../getFlatMenus/getFlatMenus"));
var _transformRoute = require("../transformRoute/transformRoute");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
//@ts-ignore
var getMenuMatches = exports.getMenuMatches = function getMenuMatches() {
var flatMenuKeys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var path = arguments.length > 1 ? arguments[1] : undefined;
var exact = arguments.length > 2 ? arguments[2] : undefined;
return flatMenuKeys.filter(function (item) {
if (item === '/' && path === '/') {
return true;
}
if (item !== '/' && item !== '/*' && item && !(0, _transformRoute.isUrl)(item)) {
var pathKey = (0, _transformRoute.stripQueryStringAndHashFromPath)(item);
try {
// exact
if (exact) {
if ((0, _pathToRegexp.pathToRegexp)("".concat(pathKey)).test(path)) {
return true;
}
}
// /a
if ((0, _pathToRegexp.pathToRegexp)("".concat(pathKey), []).test(path)) {
return true;
}
// /a/b/b
if ((0, _pathToRegexp.pathToRegexp)("".concat(pathKey, "/(.*)")).test(path)) {
return true;
}
} catch (error) {
// console.log(error, path);
}
}
return false;
}).sort(function (a, b) {
// 如果完全匹配放到最后面
if (a === path) {
return 10;
}
if (b === path) {
return -10;
}
return a.substr(1).split('/').length - b.substr(1).split('/').length;
});
};
/**
* 获取当前的选中菜单列表
* @param pathname
* @param menuData
* @returns MenuDataItem[]
*/
var getMatchMenu = exports.getMatchMenu = function getMatchMenu(pathname, menuData,
/**
* 要不要展示全部的 key
*/
fullKeys, exact) {
var flatMenus = (0, _getFlatMenus.default)(menuData);
var flatMenuKeys = Object.keys(flatMenus);
var menuPathKeys = getMenuMatches(flatMenuKeys, pathname || '/', exact);
if (!menuPathKeys || menuPathKeys.length < 1) {
return [];
}
if (!fullKeys) {
menuPathKeys = [menuPathKeys[menuPathKeys.length - 1]];
}
return menuPathKeys.map(function (menuPathKey) {
var menuItem = flatMenus[menuPathKey] || {
pro_layout_parentKeys: '',
key: ''
};
// 去重
var map = new Map();
var parentItems = (menuItem.pro_layout_parentKeys || []).map(function (key) {
if (map.has(key)) {
return null;
}
map.set(key, true);
return flatMenus[key];
}).filter(function (item) {
return item;
});
if (menuItem.key) {
parentItems.push(menuItem);
}
return parentItems;
}).flat(1);
};
var _default = exports.default = getMatchMenu;
+27
View File
@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getFlatMenus", {
enumerable: true,
get: function get() {
return _getFlatMenus.default;
}
});
Object.defineProperty(exports, "getMatchMenu", {
enumerable: true,
get: function get() {
return _getMatchMenu.default;
}
});
Object.defineProperty(exports, "transformRoute", {
enumerable: true,
get: function get() {
return _transformRoute.default;
}
});
var _transformRoute = _interopRequireDefault(require("./transformRoute/transformRoute"));
var _getFlatMenus = _interopRequireDefault(require("./getFlatMenus/getFlatMenus"));
var _getMatchMenu = _interopRequireDefault(require("./getMatchMenu/getMatchMenu"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
+459
View File
@@ -0,0 +1,459 @@
"use strict";
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.pathToRegexp = exports.tokensToRegexp = exports.regexpToFunction = exports.match = exports.tokensToFunction = exports.compile = exports.parse = void 0;
/**
* Tokenize input string.
*/
function lexer(str) {
var tokens = [];
var i = 0;
while (i < str.length) {
var char = str[i];
if (char === '*' || char === '+' || char === '?') {
tokens.push({
type: 'MODIFIER',
index: i,
value: str[i++]
});
continue;
}
if (char === '\\') {
tokens.push({
type: 'ESCAPED_CHAR',
index: i++,
value: str[i++]
});
continue;
}
if (char === '{') {
tokens.push({
type: 'OPEN',
index: i,
value: str[i++]
});
continue;
}
if (char === '}') {
tokens.push({
type: 'CLOSE',
index: i,
value: str[i++]
});
continue;
}
if (char === ':') {
var name = '';
var j = i + 1;
while (j < str.length) {
var code = str.charCodeAt(j);
if (
// `0-9`
code >= 48 && code <= 57 ||
// `A-Z`
code >= 65 && code <= 90 ||
// `a-z`
code >= 97 && code <= 122 ||
// `_`
code === 95) {
name += str[j++];
continue;
}
break;
}
if (!name) throw new TypeError('Missing parameter name at ' + i);
tokens.push({
type: 'NAME',
index: i,
value: name
});
i = j;
continue;
}
if (char === '(') {
var count = 1;
var pattern = '';
var j = i + 1;
if (str[j] === '?') {
throw new TypeError('Pattern cannot start with "?" at ' + j);
}
while (j < str.length) {
if (str[j] === '\\') {
pattern += str[j++] + str[j++];
continue;
}
if (str[j] === ')') {
count--;
if (count === 0) {
j++;
break;
}
} else if (str[j] === '(') {
count++;
if (str[j + 1] !== '?') {
throw new TypeError('Capturing groups are not allowed at ' + j);
}
}
pattern += str[j++];
}
if (count) throw new TypeError('Unbalanced pattern at ' + i);
if (!pattern) throw new TypeError('Missing pattern at ' + i);
tokens.push({
type: 'PATTERN',
index: i,
value: pattern
});
i = j;
continue;
}
tokens.push({
type: 'CHAR',
index: i,
value: str[i++]
});
}
tokens.push({
type: 'END',
index: i,
value: ''
});
return tokens;
}
/**
* Parse a string for the raw tokens.
*/
function parse(str, options) {
if (options === void 0) {
// eslint-disable-next-line no-param-reassign
options = {};
}
var tokens = lexer(str);
var _a = options.prefixes,
prefixes = _a === void 0 ? './' : _a;
var defaultPattern = '[^' + escapeString(options.delimiter || '/#?') + ']+?';
var result = [];
var key = 0;
var i = 0;
var path = '';
var tryConsume = function tryConsume(type) {
if (i < tokens.length && tokens[i].type === type) return tokens[i++].value;
};
var mustConsume = function mustConsume(type) {
var value = tryConsume(type);
if (value !== undefined) return value;
var _a = tokens[i],
nextType = _a.type,
index = _a.index;
throw new TypeError('Unexpected ' + nextType + ' at ' + index + ', expected ' + type);
};
var consumeText = function consumeText() {
var result = '';
var value;
// tslint:disable-next-line
while (value = tryConsume('CHAR') || tryConsume('ESCAPED_CHAR')) {
result += value;
}
return result;
};
while (i < tokens.length) {
var char = tryConsume('CHAR');
var name = tryConsume('NAME');
var pattern = tryConsume('PATTERN');
if (name || pattern) {
var prefix = char || '';
if (prefixes.indexOf(prefix) === -1) {
path += prefix;
prefix = '';
}
if (path) {
result.push(path);
path = '';
}
result.push({
name: name || key++,
prefix: prefix,
suffix: '',
pattern: pattern || defaultPattern,
modifier: tryConsume('MODIFIER') || ''
});
continue;
}
var value = char || tryConsume('ESCAPED_CHAR');
if (value) {
path += value;
continue;
}
if (path) {
result.push(path);
path = '';
}
var open = tryConsume('OPEN');
if (open) {
var prefix = consumeText();
var name_1 = tryConsume('NAME') || '';
var pattern_1 = tryConsume('PATTERN') || '';
var suffix = consumeText();
mustConsume('CLOSE');
result.push({
name: name_1 || (pattern_1 ? key++ : ''),
pattern: name_1 && !pattern_1 ? defaultPattern : pattern_1,
prefix: prefix,
suffix: suffix,
modifier: tryConsume('MODIFIER') || ''
});
continue;
}
mustConsume('END');
}
return result;
}
exports.parse = parse;
/**
* Compile a string to a template function for the path.
*/
function compile(str, options) {
return tokensToFunction(parse(str, options), options);
}
exports.compile = compile;
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction(tokens, options) {
if (options === void 0) {
// eslint-disable-next-line no-param-reassign
options = {};
}
var reFlags = flags(options);
var _a = options.encode,
encode = _a === void 0 ? function (x) {
return x;
} : _a,
_b = options.validate,
validate = _b === void 0 ? true : _b;
// Compile all the tokens into regexps.
var matches = tokens.map(function (token) {
if (_typeof(token) === 'object') {
return new RegExp('^(?:' + token.pattern + ')$', reFlags);
}
});
return function (data) {
var path = '';
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === 'string') {
path += token;
continue;
}
var value = data ? data[token.name] : undefined;
var optional = token.modifier === '?' || token.modifier === '*';
var repeat = token.modifier === '*' || token.modifier === '+';
if (Array.isArray(value)) {
if (!repeat) {
throw new TypeError('Expected "' + token.name + '" to not repeat, but got an array');
}
if (value.length === 0) {
if (optional) continue;
throw new TypeError('Expected "' + token.name + '" to not be empty');
}
for (var j = 0; j < value.length; j++) {
var segment = encode(value[j], token);
if (validate && !matches[i].test(segment)) {
throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"');
}
path += token.prefix + segment + token.suffix;
}
continue;
}
if (typeof value === 'string' || typeof value === 'number') {
var segment = encode(String(value), token);
if (validate && !matches[i].test(segment)) {
throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"');
}
path += token.prefix + segment + token.suffix;
continue;
}
if (optional) continue;
var typeOfMessage = repeat ? 'an array' : 'a string';
throw new TypeError('Expected "' + token.name + '" to be ' + typeOfMessage);
}
return path;
};
}
exports.tokensToFunction = tokensToFunction;
/**
* Create path match function from `path-to-regexp` spec.
*/
function match(str, options) {
var keys = [];
var re = pathToRegexp(str, keys, options);
return regexpToFunction(re, keys, options);
}
exports.match = match;
/**
* Create a path match function from `path-to-regexp` output.
*/
function regexpToFunction(re, keys, options) {
if (options === void 0) {
// eslint-disable-next-line no-param-reassign
options = {};
}
var _a = options.decode,
decode = _a === void 0 ? function (x) {
return x;
} : _a;
return function (pathname) {
var m = re.exec(pathname);
if (!m) return false;
var path = m[0],
index = m.index;
var params = Object.create(null);
var _loop_1 = function _loop_1(i) {
// tslint:disable-next-line
if (m[i] === undefined) return 'continue';
var key = keys[i - 1];
if (key.modifier === '*' || key.modifier === '+') {
params[key.name] = m[i].split(key.prefix + key.suffix).map(function (value) {
return decode(value, key);
});
} else {
params[key.name] = decode(m[i], key);
}
};
for (var i = 1; i < m.length; i++) {
_loop_1(i);
}
return {
path: path,
index: index,
params: params
};
};
}
exports.regexpToFunction = regexpToFunction;
/**
* Escape a regular expression string.
*/
function escapeString(str) {
return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1');
}
/**
* Get the flags for a regexp from the options.
*/
function flags(options) {
return options && options.sensitive ? '' : 'i';
}
/**
* Pull out keys from a regexp.
*/
function regexpToRegexp(path, keys) {
if (!keys) return path;
// Use a negative lookahead to match only capturing groups.
var groups = path.source.match(/\((?!\?)/g);
if (groups) {
for (var i = 0; i < groups.length; i++) {
keys.push({
name: i,
prefix: '',
suffix: '',
modifier: '',
pattern: ''
});
}
}
return path;
}
/**
* Transform an array into a regexp.
*/
function arrayToRegexp(paths, keys, options) {
var parts = paths.map(function (path) {
return pathToRegexp(path, keys, options).source;
});
return new RegExp('(?:' + parts.join('|') + ')', flags(options));
}
/**
* Create a path regexp from string input.
*/
function stringToRegexp(path, keys, options) {
return tokensToRegexp(parse(path, options), keys, options);
}
/**
* Expose a function for taking tokens and returning a RegExp.
*/
function tokensToRegexp(tokens, keys, options) {
if (options === void 0) {
// eslint-disable-next-line no-param-reassign
options = {};
}
var _a = options.strict,
strict = _a === void 0 ? false : _a,
_b = options.start,
start = _b === void 0 ? true : _b,
_c = options.end,
end = _c === void 0 ? true : _c,
_d = options.encode,
encode = _d === void 0 ? function (x) {
return x;
} : _d;
var endsWith = '[' + escapeString(options.endsWith || '') + ']|$';
var delimiter = '[' + escapeString(options.delimiter || '/#?') + ']';
var route = start ? '^' : '';
// Iterate over the tokens and create our regexp string.
for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
var token = tokens_1[_i];
if (typeof token === 'string') {
route += escapeString(encode(token));
} else {
var prefix = escapeString(encode(token.prefix));
var suffix = escapeString(encode(token.suffix));
if (token.pattern) {
if (keys) keys.push(token);
if (prefix || suffix) {
if (token.modifier === '+' || token.modifier === '*') {
var mod = token.modifier === '*' ? '?' : '';
route += '(?:' + prefix + '((?:' + token.pattern + ')(?:' + suffix + prefix + '(?:' + token.pattern + '))*)' + suffix + ')' + mod;
} else {
route += '(?:' + prefix + '(' + token.pattern + ')' + suffix + ')' + token.modifier;
}
} else {
route += '(' + token.pattern + ')' + token.modifier;
}
} else {
route += '(?:' + prefix + suffix + ')' + token.modifier;
}
}
}
if (end) {
if (!strict) route += delimiter + '?';
route += !options.endsWith ? '$' : '(?=' + endsWith + ')';
} else {
var endToken = tokens[tokens.length - 1];
var isEndDelimited = typeof endToken === 'string' ? delimiter.indexOf(endToken[endToken.length - 1]) > -1 :
// tslint:disable-next-line
endToken === undefined;
if (!strict) {
route += '(?:' + delimiter + '(?=' + endsWith + '))?';
}
if (!isEndDelimited) {
route += '(?=' + delimiter + '|' + endsWith + ')';
}
}
return new RegExp(route, flags(options));
}
exports.tokensToRegexp = tokensToRegexp;
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array can be passed in for the keys, which will hold the
* placeholder key descriptions. For example, using `/user/:id`, `keys` will
* contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
*/
function pathToRegexp(path, keys, options) {
if (path instanceof RegExp) return regexpToRegexp(path, keys);
if (Array.isArray(path)) return arrayToRegexp(path, keys, options);
return stringToRegexp(path, keys, options);
}
exports.pathToRegexp = pathToRegexp;
+229
View File
@@ -0,0 +1,229 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/* eslint-disable no-redeclare */
/* eslint-disable no-multi-assign */
/* eslint-disable no-param-reassign */
/* eslint-disable no-return-assign */
/* eslint-disable no-new-wrappers */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable no-var */
/* eslint-disable no-plusplus */
/* eslint-disable prefer-destructuring */
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable block-scoped-var */
/* eslint-disable vars-on-top */
/* eslint-disable no-bitwise */
/* eslint-disable no-cond-assign */
/*
* A JavaScript implementation of the SHA256 hash function.
*
* FILE: sha256.js
* VERSION: 0.8
* AUTHOR: Christoph Bichlmeier <informatik@zombiearena.de>
*
* NOTE: This version is not tested thoroughly!
*
* Copyright (c) 2003, Christoph Bichlmeier
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* ======================================================================
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* SHA256 logical functions */
function rotateRight(n, x) {
return x >>> n | x << 32 - n;
}
function choice(x, y, z) {
return x & y ^ ~x & z;
}
function majority(x, y, z) {
return x & y ^ x & z ^ y & z;
}
function sha256_Sigma0(x) {
return rotateRight(2, x) ^ rotateRight(13, x) ^ rotateRight(22, x);
}
function sha256_Sigma1(x) {
return rotateRight(6, x) ^ rotateRight(11, x) ^ rotateRight(25, x);
}
function sha256_sigma0(x) {
return rotateRight(7, x) ^ rotateRight(18, x) ^ x >>> 3;
}
function sha256_sigma1(x) {
return rotateRight(17, x) ^ rotateRight(19, x) ^ x >>> 10;
}
function sha256_expand(W, j) {
return W[j & 0x0f] += sha256_sigma1(W[j + 14 & 0x0f]) + W[j + 9 & 0x0f] + sha256_sigma0(W[j + 1 & 0x0f]);
}
/* Hash constant words K: */
var K256 = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
/* global arrays */
var ihash;
var count;
var buffer;
var sha256_hex_digits = '0123456789abcdef';
/* Add 32-bit integers with 16-bit operations (bug in some JS-interpreters:
overflow) */
function safe_add(x, y) {
var lsw = (x & 0xffff) + (y & 0xffff);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return msw << 16 | lsw & 0xffff;
}
/* Initialise the SHA256 computation */
function sha256_init() {
ihash = new Array(8);
count = new Array(2);
buffer = new Array(64);
count[0] = count[1] = 0;
ihash[0] = 0x6a09e667;
ihash[1] = 0xbb67ae85;
ihash[2] = 0x3c6ef372;
ihash[3] = 0xa54ff53a;
ihash[4] = 0x510e527f;
ihash[5] = 0x9b05688c;
ihash[6] = 0x1f83d9ab;
ihash[7] = 0x5be0cd19;
}
/* Transform a 512-bit message block */
function sha256_transform() {
var a;
var b;
var c;
var d;
var e;
var f;
var g;
var h;
var T1;
var T2;
var W = new Array(16);
/* Initialize registers with the previous intermediate value */
a = ihash[0];
b = ihash[1];
c = ihash[2];
d = ihash[3];
e = ihash[4];
f = ihash[5];
g = ihash[6];
h = ihash[7];
/* make 32-bit words */
for (var i = 0; i < 16; i++) W[i] = buffer[(i << 2) + 3] | buffer[(i << 2) + 2] << 8 | buffer[(i << 2) + 1] << 16 | buffer[i << 2] << 24;
for (var j = 0; j < 64; j++) {
T1 = h + sha256_Sigma1(e) + choice(e, f, g) + K256[j];
if (j < 16) T1 += W[j];else T1 += sha256_expand(W, j);
T2 = sha256_Sigma0(a) + majority(a, b, c);
h = g;
g = f;
f = e;
e = safe_add(d, T1);
d = c;
c = b;
b = a;
a = safe_add(T1, T2);
}
/* Compute the current intermediate hash value */
ihash[0] += a;
ihash[1] += b;
ihash[2] += c;
ihash[3] += d;
ihash[4] += e;
ihash[5] += f;
ihash[6] += g;
ihash[7] += h;
}
/* Read the next chunk of data and update the SHA256 computation */
function sha256_update(data, inputLen) {
var i;
var index;
var curpos = 0;
/* Compute number of bytes mod 64 */
index = count[0] >> 3 & 0x3f;
var remainder = inputLen & 0x3f;
/* Update number of bits */
if ((count[0] += inputLen << 3) < inputLen << 3) count[1]++;
count[1] += inputLen >> 29;
/* Transform as many times as possible */
for (i = 0; i + 63 < inputLen; i += 64) {
for (var j = index; j < 64; j++) buffer[j] = data.charCodeAt(curpos++);
sha256_transform();
index = 0;
}
/* Buffer remaining input */
for (var _j = 0; _j < remainder; _j++) buffer[_j] = data.charCodeAt(curpos++);
}
/* Finish the computation by operations such as padding */
function sha256_final() {
var index = count[0] >> 3 & 0x3f;
buffer[index++] = 0x80;
if (index <= 56) {
for (var i = index; i < 56; i++) buffer[i] = 0;
} else {
for (var _i = index; _i < 64; _i++) buffer[_i] = 0;
sha256_transform();
for (var _i2 = 0; _i2 < 56; _i2++) buffer[_i2] = 0;
}
buffer[56] = count[1] >>> 24 & 0xff;
buffer[57] = count[1] >>> 16 & 0xff;
buffer[58] = count[1] >>> 8 & 0xff;
buffer[59] = count[1] & 0xff;
buffer[60] = count[0] >>> 24 & 0xff;
buffer[61] = count[0] >>> 16 & 0xff;
buffer[62] = count[0] >>> 8 & 0xff;
buffer[63] = count[0] & 0xff;
sha256_transform();
}
/* Split the internal hash values into an array of bytes */
function sha256_encode_bytes() {
var j = 0;
var output = new Array(32);
for (var i = 0; i < 8; i++) {
output[j++] = ihash[i] >>> 24 & 0xff;
output[j++] = ihash[i] >>> 16 & 0xff;
output[j++] = ihash[i] >>> 8 & 0xff;
output[j++] = ihash[i] & 0xff;
}
return output;
}
/* Get the internal hash as a hex string */
function sha256_encode_hex() {
var output = new String();
for (var i = 0; i < 8; i++) {
for (var j = 28; j >= 0; j -= 4) output += sha256_hex_digits.charAt(ihash[i] >>> j & 0x0f);
}
return output;
}
/* Main function: returns a hex string representing the SHA256 value of the
given data */
function digest(data) {
sha256_init();
sha256_update(data, data.length);
sha256_final();
return sha256_encode_hex();
}
var _default = exports.default = digest;
@@ -0,0 +1,401 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isUrl = exports.getKeyByPath = exports.default = exports.childrenPropsName = void 0;
exports.stripQueryStringAndHashFromPath = stripQueryStringAndHashFromPath;
var _pathToRegexp = require("../path-to-regexp");
var _sha = _interopRequireDefault(require("../sha265"));
var _excluded = ["pro_layout_parentKeys", "children", "icon", "flatMenu", "indexRoute", "routes"];
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _wrapNativeSuper(t) { var r = "function" == typeof Map ? new Map() : void 0; return _wrapNativeSuper = function _wrapNativeSuper(t) { if (null === t || !_isNativeFunction(t)) return t; if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t)) return r.get(t); r.set(t, Wrapper); } function Wrapper() { return _construct(t, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t.prototype, { constructor: { value: Wrapper, enumerable: !1, writable: !0, configurable: !0 } }), _setPrototypeOf(Wrapper, t); }, _wrapNativeSuper(t); }
function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } //@ts-ignore
var childrenPropsName = exports.childrenPropsName = 'routes';
function stripQueryStringAndHashFromPath(url) {
return url.split('?')[0].split('#')[0];
}
var isUrl = exports.isUrl = function isUrl(path) {
if (!path.startsWith('http')) {
return false;
}
try {
var url = new URL(path);
return !!url;
} catch (error) {
return false;
}
};
var getKeyByPath = exports.getKeyByPath = function getKeyByPath(item) {
var path = item.path;
if (!path || path === '/') {
// 如果还是没有,用对象的hash 生成一个
try {
return "/".concat((0, _sha.default)(JSON.stringify(item)));
} catch (error) {
// dom some thing
}
}
return path ? stripQueryStringAndHashFromPath(path) : path;
};
/**
* 获取locale,增加了一个功能,如果 locale = false,将不使用国际化
* @param item
* @param parentName
*/
var getItemLocaleName = function getItemLocaleName(item, parentName) {
var name = item.name,
locale = item.locale;
// 如果配置了 locale 并且 locale 为 false或 ""
if ('locale' in item && locale === false || !name) {
return false;
}
return item.locale || "".concat(parentName, ".").concat(name);
};
/**
* 如果不是 / 开头的和父节点做一下合并
* 如果是 / 开头的不作任何处理
* 如果是 url 也直接返回
* @param path
* @param parentPath
*/
var mergePath = function mergePath() {
var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var parentPath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '/';
if (path.endsWith('/*')) {
return path.replace('/*', '/');
}
if ((path || parentPath).startsWith('/')) {
return path;
}
if (isUrl(path)) {
return path;
}
return "/".concat(parentPath, "/").concat(path).replace(/\/\//g, '/').replace(/\/\//g, '/');
};
// bigfish 的兼容准话
var bigfishCompatibleConversions = function bigfishCompatibleConversions(route, props) {
var _route$menu = route.menu,
menu = _route$menu === void 0 ? {} : _route$menu,
indexRoute = route.indexRoute,
_route$path = route.path,
path = _route$path === void 0 ? '' : _route$path;
var routerChildren = route.children || [];
var _menu$name = menu.name,
name = _menu$name === void 0 ? route.name : _menu$name,
_menu$icon = menu.icon,
icon = _menu$icon === void 0 ? route.icon : _menu$icon,
_menu$hideChildren = menu.hideChildren,
hideChildren = _menu$hideChildren === void 0 ? route.hideChildren : _menu$hideChildren,
_menu$flatMenu = menu.flatMenu,
flatMenu = _menu$flatMenu === void 0 ? route.flatMenu : _menu$flatMenu; // 兼容平铺式写法
// 拼接 childrenRoutes, 处理存在 indexRoute 时的逻辑
var childrenList = indexRoute &&
// 如果只有 redirect,不用处理的
Object.keys(indexRoute).join(',') !== 'redirect' ? [_objectSpread({
path: path,
menu: menu
}, indexRoute)].concat(routerChildren || []) : routerChildren;
// 拼接返回的 menu 数据
var result = _objectSpread({}, route);
if (name) {
result.name = name;
}
if (icon) {
result.icon = icon;
}
if (childrenList && childrenList.length) {
/** 在菜单中隐藏子项 */
if (hideChildren) {
delete result.children;
return result;
}
// 需要重新进行一次
var finalChildren = formatter(_objectSpread(_objectSpread({}, props), {}, {
data: childrenList
}), route);
/** 在菜单中只隐藏此项,子项往上提,仍旧展示 */
if (flatMenu) {
return finalChildren;
}
delete result[childrenPropsName];
}
return result;
};
var notNullArray = function notNullArray(value) {
return Array.isArray(value) && value.length > 0;
};
/**
*
* @param props
* @param parent
*/
function formatter(props) {
var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
path: '/'
};
var data = props.data,
formatMessage = props.formatMessage,
parentName = props.parentName,
menuLocale = props.locale;
if (!data || !Array.isArray(data)) {
return [];
}
return data.filter(function (item) {
if (!item) return false;
if (notNullArray(item.children)) return true;
if (item.path) return true;
if (item.originPath) return true;
if (item.layout) return true;
// 重定向
if (item.redirect) return false;
if (item.unaccessible) return false;
return false;
}).filter(function (item) {
var _item$menu, _item$menu2;
if ((item === null || item === void 0 ? void 0 : (_item$menu = item.menu) === null || _item$menu === void 0 ? void 0 : _item$menu.name) || (item === null || item === void 0 ? void 0 : item.flatMenu) || (item === null || item === void 0 ? void 0 : (_item$menu2 = item.menu) === null || _item$menu2 === void 0 ? void 0 : _item$menu2.flatMenu)) {
return true;
}
// 显示指定在 menu 中隐藏该项
// layout 插件的功能,其实不应该存在的
if (item.menu === false) {
return false;
}
return true;
}).map(function (finallyItem) {
var item = _objectSpread(_objectSpread({}, finallyItem), {}, {
path: finallyItem.path || finallyItem.originPath
});
if (!item.children && item[childrenPropsName]) {
item.children = item[childrenPropsName];
delete item[childrenPropsName];
}
// 是否没有权限查看
// 这样就不会显示,是一个兼容性的方式
if (item.unaccessible) {
// eslint-disable-next-line no-param-reassign
delete item.name;
}
if (item.path === '*') {
item.path = '.';
}
if (item.path === '/*') {
item.path = '.';
}
if (!item.path && item.originPath) {
item.path = item.originPath;
}
return item;
}).map(function () {
var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
path: '/'
};
var routerChildren = item.children || item[childrenPropsName] || [];
var path = mergePath(item.path, parent ? parent.path : '/');
var name = item.name;
var locale = getItemLocaleName(item, parentName || 'menu');
// if enableMenuLocale use item.name,
// close menu international
var localeName = locale !== false && menuLocale !== false && formatMessage && locale ? formatMessage({
id: locale,
defaultMessage: name
}) : name;
var _parent$pro_layout_pa = parent.pro_layout_parentKeys,
pro_layout_parentKeys = _parent$pro_layout_pa === void 0 ? [] : _parent$pro_layout_pa,
children = parent.children,
icon = parent.icon,
flatMenu = parent.flatMenu,
indexRoute = parent.indexRoute,
routes = parent.routes,
restParent = _objectWithoutProperties(parent, _excluded);
var item_pro_layout_parentKeys = new Set([].concat(_toConsumableArray(pro_layout_parentKeys), _toConsumableArray(item.parentKeys || [])));
if (parent.key) {
item_pro_layout_parentKeys.add(parent.key);
}
var finallyItem = _objectSpread(_objectSpread(_objectSpread({}, restParent), {}, {
menu: undefined
}, item), {}, {
path: path,
locale: locale,
key: item.key || getKeyByPath(_objectSpread(_objectSpread({}, item), {}, {
path: path
})),
pro_layout_parentKeys: Array.from(item_pro_layout_parentKeys).filter(function (key) {
return key && key !== '/';
})
});
if (localeName) {
finallyItem.name = localeName;
} else {
delete finallyItem.name;
}
if (finallyItem.menu === undefined) {
delete finallyItem.menu;
}
if (notNullArray(routerChildren)) {
var formatterChildren = formatter(_objectSpread(_objectSpread({}, props), {}, {
data: routerChildren,
parentName: locale || ''
}), finallyItem);
if (notNullArray(formatterChildren)) {
finallyItem.children = formatterChildren;
}
}
return bigfishCompatibleConversions(finallyItem, props);
}).flat(1);
}
/**
* 删除 hideInMenu 和 item.name 不存在的
*/
var _defaultFilterMenuData = function defaultFilterMenuData() {
var menuData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
return menuData.filter(function (item) {
return item && (item.name || notNullArray(item.children)) && !item.hideInMenu && !item.redirect;
}).map(function (item) {
var newItem = _objectSpread({}, item);
var routerChildren = newItem.children || item[childrenPropsName] || [];
delete newItem[childrenPropsName];
if (notNullArray(routerChildren) && !newItem.hideChildrenInMenu && routerChildren.some(function (child) {
return child && !!child.name;
})) {
var newChildren = _defaultFilterMenuData(routerChildren);
if (newChildren.length) return _objectSpread(_objectSpread({}, newItem), {}, {
children: newChildren
});
}
return _objectSpread({}, item);
}).filter(function (item) {
return item;
});
};
/**
* support pathToRegexp get string
*/
var RouteListMap = /*#__PURE__*/function (_Map) {
function RouteListMap() {
_classCallCheck(this, RouteListMap);
return _callSuper(this, RouteListMap, arguments);
}
_inherits(RouteListMap, _Map);
return _createClass(RouteListMap, [{
key: "get",
value: function get(pathname) {
var routeValue;
try {
// eslint-disable-next-line no-restricted-syntax
var _iterator = _createForOfIteratorHelper(this.entries()),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray(_step.value, 2),
key = _step$value[0],
value = _step$value[1];
var path = stripQueryStringAndHashFromPath(key);
if (!isUrl(key) && (0, _pathToRegexp.pathToRegexp)(path, []).test(pathname)) {
routeValue = value;
break;
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
} catch (error) {
routeValue = undefined;
}
return routeValue;
}
}]);
}(/*#__PURE__*/_wrapNativeSuper(Map));
/**
* 获取面包屑映射
* @param MenuDataItem[] menuData 菜单配置
*/
var getBreadcrumbNameMap = function getBreadcrumbNameMap(menuData) {
// Map is used to ensure the order of keys
var routerMap = new RouteListMap();
var _flattenMenuData = function flattenMenuData(data, parent) {
data.forEach(function (menuItem) {
var routerChildren = menuItem.children || menuItem[childrenPropsName] || [];
if (notNullArray(routerChildren)) {
_flattenMenuData(routerChildren, menuItem);
}
// Reduce memory usage
var path = mergePath(menuItem.path, parent ? parent.path : '/');
routerMap.set(stripQueryStringAndHashFromPath(path), menuItem);
});
};
_flattenMenuData(menuData);
return routerMap;
};
var _clearChildren = function clearChildren() {
var menuData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
return menuData.map(function (item) {
var routerChildren = item.children || item[childrenPropsName];
if (notNullArray(routerChildren)) {
var newChildren = _clearChildren(routerChildren);
if (newChildren.length) return _objectSpread({}, item);
}
var finallyItem = _objectSpread({}, item);
delete finallyItem[childrenPropsName];
delete finallyItem.children;
return finallyItem;
}).filter(function (item) {
return item;
});
};
/**
* @param routeList 路由配置
* @param locale 是否使用国际化
* @param formatMessage 国际化的程序
* @param ignoreFilter 是否筛选掉不展示的 menuItem 项,plugin-layout需要所有项目来计算布局样式
* @returns { breadcrumb, menuData}
*/
var transformRoute = function transformRoute(routeList, locale, formatMessage, ignoreFilter) {
var originalMenuData = formatter({
data: _toConsumableArray(routeList).map(function (item) {
return _objectSpread({}, item);
}),
formatMessage: formatMessage,
locale: locale
});
var menuData = ignoreFilter ? _clearChildren(originalMenuData) : _defaultFilterMenuData(originalMenuData);
// Map type used for internal logic
var breadcrumb = getBreadcrumbNameMap(originalMenuData);
return {
breadcrumb: breadcrumb,
menuData: menuData
};
};
var _default = exports.default = transformRoute;
+5
View File
@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
+43
View File
@@ -0,0 +1,43 @@
{
"name": "@umijs/route-utils",
"version": "4.0.3",
"description": "Quickly process the routing of umi",
"repository": "https://github.com/umijs/route-utils",
"license": "MIT",
"main": "lib/index.js",
"module": "es/index.js",
"typings": "./dist/index.d.ts",
"files": [
"/lib",
"/es",
"/dist"
],
"scripts": {
"build": "father-build && tsc -d -p tsconfig.build.json",
"lint": "npm run lint-eslint",
"lint-eslint": "eslint --cache --ext .js,.jsx,.ts,.tsx --format=pretty ./src",
"lint:fix": "eslint --fix --cache --ext .js,.jsx,.ts,.tsx --format=pretty",
"test": "umi-test",
"test:coverage": "umi-test ./test --coverage",
"tsc": "tsc --noEmit"
},
"jest": {
"collectCoverage": true,
"coverageDirectory": "./coverage/"
},
"dependencies": {},
"devDependencies": {
"@types/jest": "^25.2.1",
"@umijs/fabric": "^2.0.8",
"eslint": "^7.0.0",
"father-build": "^1.18.1",
"np": "^6.2.3",
"prettier": "^2.0.5",
"typescript": "^3.3.3",
"umi-test": "^1.9.6"
},
"authors": {
"name": "chenshuai2144",
"email": "qixian.cs@outlook.com"
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Rudy Huynh
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+131
View File
@@ -0,0 +1,131 @@
# `useUrlSearchParams()`
[![GitHub license](https://img.shields.io/github/license/Naereen/StrapDown.js.svg)](https://github.com/rudyhuynh/use-url-search-params/blob/master/License)
A React Hook to use [URL query string](https://en.wikipedia.org/wiki/Query_string) as a state management
[Demo](https://rudyhuynh.github.io/use-url-search-params)
## Why you need this
- Your app need to persist its state after user refresh the page (used for simple, non-sensitive data).
- Some page settings (ex: table filter, sorting, paging, etc.) should be saved in the URL so that user can easily pass to others. e.g. Tester can easily send a URL of a page to developer with very least reproduce steps.
- You want to do something (request new data, etc.) every time some URL query value changes.
- Combine all of the above with a URL query as a single source of truth.
## Installation
```
npm install use-url-search-params
```
or
```
yarn add use-url-search-params
```
## How to use
For most of the time you will do something like this:
```js
import React from "react";
import { useUrlSearchParams } from "use-url-search-params";
function App() {
// Your page URL will be like this by default: http://my.page?checked=true
const [params, setParams] = useUrlSearchParams({ checked: true });
React.useEffect(() => {
// do something when `params.checked` is updated.
}, [params.checked]);
return (
<div>
<input
type="checkbox"
checked={params.checked}
onChange={e => setParams({ checked: e.target.checked })}
/>
</div>
);
}
```
## How to control the value parsed from URL query
By default, all values parsed from URL query are string. In case you want to get boolean or number value, pass a second argument to `useUrlSearchParams()` to specify data type you want to get from `params` object. Here is an example:
```js
const initial = {
y: "option1"
};
const types = {
x: Number,
y: Boolean,
z: Date,
t: ["option1", "option2", "option3"]
};
const [params, setParams] = useUrlSearchParams(initial, types);
// `params.x` will be number (or NaN)
// `params.y` will be one of [undefined, true, false]
// `params.z` will be instance of Date (can be Invalid Date)
// `params.t` will be one of ["option1", "option2", "option3"] (can be `undefined` if not specified in `initial`)
```
## Complex data structure
Although you can use `JSON.parse()` and `JSON.stringify()` to get/set arbitrary serializable data to URL query, it is not recommended. URL query is a good place to store and persist page settings as key/value pairs such as table filter, sorting, paging, etc. We should keep it that way for simplicity. **For complex data structure, you should consider using other state management for better performance, security and flexibility.**
> **WARNING**: Be aware of XSS attack. Be careful to validate values from URL query before using it by either using `types` - the second parameter passed to `useUrlSearchParams()` or validate them yourself if neccessary.
But if you still insist, here is an example:
```js
function App() {
const [params, setParams] = useUrlSearchParams(
{},
{
complexData: dataString => {
try {
return JSON.parse(dataString);
} catch (e) {
return {};
}
}
}
);
const onSetParams = data => {
setParams({ complexData: JSON.stringify(data) });
};
return <div>{/*...*/}</div>;
}
```
## React Router
Should just work with React Router or any routing system. Just make sure that your component re-render whenever route changes.
## API
- **useUrlSearchParams([initial, types])**
- `initial` (optional | Object): To set default values for URL query string.
- `types` (optional | Object): Has similar shape with `initial`, help to resolve values from URL query string. Supported types:
- `String` (default)
- `Number`
- `Bool`
- `Date` - [`Date.prototype.toISOString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) is used to parse date to string, e.g date string in your URL query is zero UTC offset
- Array of available string values (like enum)
- A custom resolver function
## Read more (for maintainers)
This library is built base on [URLSearchParams interface](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
## License
MIT
+3
View File
@@ -0,0 +1,3 @@
export declare function useUrlSearchParams(initial?: Record<string, string | number>, config?: {
disabled?: boolean;
}): [Record<string, string | number>, (value: Record<string, string | number>) => void];
+162
View File
@@ -0,0 +1,162 @@
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
/* eslint-disable no-restricted-syntax */
import { useEffect, useMemo, useState } from 'react';
/**
*
* @param {object} params
* @returns {URL}
*/
function setQueryToCurrentUrl(params) {
var _a;
var URL = (typeof window !== 'undefined' ? window : {}).URL;
var url = new URL((_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.href);
Object.keys(params).forEach(function (key) {
var value = params[key];
if (value !== null && value !== undefined) {
if (Array.isArray(value)) {
url.searchParams.delete(key);
value.forEach(function (valueItem) {
url.searchParams.append(key, valueItem);
});
}
else if (value instanceof Date) {
if (!Number.isNaN(value.getTime())) {
url.searchParams.set(key, value.toISOString());
}
}
else if (typeof value === 'object') {
url.searchParams.set(key, JSON.stringify(value));
}
else {
url.searchParams.set(key, value);
}
}
else {
url.searchParams.delete(key);
}
});
return url;
}
export function useUrlSearchParams(initial, config) {
var _a;
if (initial === void 0) { initial = {}; }
if (config === void 0) { config = { disabled: false }; }
/**
* The main idea of this hook is to make things response to change of `window.location.search`,
* so no need for introducing new state (in the mean time).
* Whenever `window.location.search` is changed but not cause re-render, call `forceUpdate()`.
* Whenever the component - user of this hook - re-render, this hook should return
* the query object that corresponse to the current `window.location.search`
*/
var _b = useState(), forceUpdate = _b[1];
var locationSearch = typeof window !== 'undefined' && ((_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.search);
/**
* @type {URLSearchParams}
*/
var urlSearchParams = useMemo(function () {
if (config.disabled)
return {};
return new URLSearchParams(locationSearch || {});
}, [config.disabled, locationSearch]);
var params = useMemo(function () {
if (config.disabled)
return {};
if (typeof window === 'undefined' || !window.URL)
return {};
var result = [];
// @ts-ignore
urlSearchParams.forEach(function (value, key) {
result.push({
key: key,
value: value,
});
});
// group by key
result = result.reduce(function (acc, val) {
(acc[val.key] = acc[val.key] || []).push(val);
return acc;
}, {});
result = Object.keys(result).map(function (key) {
var valueGroup = result[key];
if (valueGroup.length === 1) {
return [key, valueGroup[0].value];
}
return [key, valueGroup.map(function (_a) {
var value = _a.value;
return value;
})];
});
var newParams = __assign({}, initial);
result.forEach(function (_a) {
var key = _a[0], value = _a[1];
newParams[key] = parseValue(key, value, {}, initial);
});
return newParams;
}, [config.disabled, initial, urlSearchParams]);
function redirectToNewSearchParams(newParams) {
if (typeof window === 'undefined' || !window.URL)
return;
var url = setQueryToCurrentUrl(newParams);
if (window.location.search !== url.search) {
window.history.replaceState({}, '', url.toString());
}
if (urlSearchParams.toString() !== url.searchParams.toString()) {
forceUpdate({});
}
}
useEffect(function () {
if (config.disabled)
return;
if (typeof window === 'undefined' || !window.URL)
return;
redirectToNewSearchParams(__assign(__assign({}, initial), params));
}, [config.disabled, params]);
var setParams = function (newParams) {
redirectToNewSearchParams(newParams);
};
useEffect(function () {
if (config.disabled)
return function () { };
if (typeof window === 'undefined' || !window.URL)
return function () { };
var onPopState = function () {
forceUpdate({});
};
window.addEventListener('popstate', onPopState);
return function () {
window.removeEventListener('popstate', onPopState);
};
}, [config.disabled]);
return [params, setParams];
}
var booleanValues = {
true: true,
false: false,
};
function parseValue(key, _value, types, defaultParams) {
if (!types)
return _value;
var type = types[key];
var value = _value === undefined ? defaultParams[key] : _value;
if (type === Number) {
return Number(value);
}
if (type === Boolean || _value === 'true' || _value === 'false') {
return booleanValues[value];
}
if (Array.isArray(type)) {
// eslint-disable-next-line eqeqeq
return type.find(function (item) { return item == value; }) || defaultParams[key];
}
return value;
}
+3
View File
@@ -0,0 +1,3 @@
export declare function useUrlSearchParams(initial?: Record<string, string | number>, config?: {
disabled?: boolean;
}): [Record<string, string | number>, (value: Record<string, string | number>) => void];
+202
View File
@@ -0,0 +1,202 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useUrlSearchParams = useUrlSearchParams;
var _react = require("react");
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var __assign = void 0 && (void 0).__assign || function () {
__assign = Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
}
return t;
};
return __assign.apply(this, arguments);
};
/* eslint-disable no-restricted-syntax */
/**
*
* @param {object} params
* @returns {URL}
*/
function setQueryToCurrentUrl(params) {
var _a;
var URL = (typeof window !== 'undefined' ? window : {}).URL;
var url = new URL((_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.href);
Object.keys(params).forEach(function (key) {
var value = params[key];
if (value !== null && value !== undefined) {
if (Array.isArray(value)) {
url.searchParams.delete(key);
value.forEach(function (valueItem) {
url.searchParams.append(key, valueItem);
});
} else if (value instanceof Date) {
if (!Number.isNaN(value.getTime())) {
url.searchParams.set(key, value.toISOString());
}
} else if (_typeof(value) === 'object') {
url.searchParams.set(key, JSON.stringify(value));
} else {
url.searchParams.set(key, value);
}
} else {
url.searchParams.delete(key);
}
});
return url;
}
function useUrlSearchParams(initial, config) {
var _a;
if (initial === void 0) {
initial = {};
}
if (config === void 0) {
config = {
disabled: false
};
}
/**
* The main idea of this hook is to make things response to change of `window.location.search`,
* so no need for introducing new state (in the mean time).
* Whenever `window.location.search` is changed but not cause re-render, call `forceUpdate()`.
* Whenever the component - user of this hook - re-render, this hook should return
* the query object that corresponse to the current `window.location.search`
*/
var _b = (0, _react.useState)(),
forceUpdate = _b[1];
var locationSearch = typeof window !== 'undefined' && ((_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.search);
/**
* @type {URLSearchParams}
*/
var urlSearchParams = (0, _react.useMemo)(function () {
if (config.disabled) return {};
return new URLSearchParams(locationSearch || {});
}, [config.disabled, locationSearch]);
var params = (0, _react.useMemo)(function () {
if (config.disabled) return {};
if (typeof window === 'undefined' || !window.URL) return {};
var result = []; // @ts-ignore
urlSearchParams.forEach(function (value, key) {
result.push({
key: key,
value: value
});
}); // group by key
result = result.reduce(function (acc, val) {
(acc[val.key] = acc[val.key] || []).push(val);
return acc;
}, {});
result = Object.keys(result).map(function (key) {
var valueGroup = result[key];
if (valueGroup.length === 1) {
return [key, valueGroup[0].value];
}
return [key, valueGroup.map(function (_a) {
var value = _a.value;
return value;
})];
});
var newParams = __assign({}, initial);
result.forEach(function (_a) {
var key = _a[0],
value = _a[1];
newParams[key] = parseValue(key, value, {}, initial);
});
return newParams;
}, [config.disabled, initial, urlSearchParams]);
function redirectToNewSearchParams(newParams) {
if (typeof window === 'undefined' || !window.URL) return;
var url = setQueryToCurrentUrl(newParams);
if (window.location.search !== url.search) {
window.history.replaceState({}, '', url.toString());
}
if (urlSearchParams.toString() !== url.searchParams.toString()) {
forceUpdate({});
}
}
(0, _react.useEffect)(function () {
if (config.disabled) return;
if (typeof window === 'undefined' || !window.URL) return;
redirectToNewSearchParams(__assign(__assign({}, initial), params));
}, [config.disabled, params]);
var setParams = function setParams(newParams) {
redirectToNewSearchParams(newParams);
};
(0, _react.useEffect)(function () {
if (config.disabled) return function () {};
if (typeof window === 'undefined' || !window.URL) return function () {};
var onPopState = function onPopState() {
forceUpdate({});
};
window.addEventListener('popstate', onPopState);
return function () {
window.removeEventListener('popstate', onPopState);
};
}, [config.disabled]);
return [params, setParams];
}
var booleanValues = {
true: true,
false: false
};
function parseValue(key, _value, types, defaultParams) {
if (!types) return _value;
var type = types[key];
var value = _value === undefined ? defaultParams[key] : _value;
if (type === Number) {
return Number(value);
}
if (type === Boolean || _value === 'true' || _value === 'false') {
return booleanValues[value];
}
if (Array.isArray(type)) {
// eslint-disable-next-line eqeqeq
return type.find(function (item) {
return item == value;
}) || defaultParams[key];
}
return value;
}
+37
View File
@@ -0,0 +1,37 @@
{
"name": "@umijs/use-params",
"version": "1.0.9",
"keywords": [
"react",
"react-hooks",
"urlsearchparams",
"url-query",
"url",
"state"
],
"bugs": "https://github.com/chenshuai2144/use-params/issues",
"repository": "https://github.com/chenshuai2144/use-params",
"license": "MIT",
"author": "rudyhuynh <rudyhuynh@>",
"main": "lib/index.js",
"module": "es/index.js",
"types": "es/index.d.ts",
"files": [
"es",
"lib"
],
"scripts": {
"prepublish": "npm run build",
"build": "tsc && father-build"
},
"devDependencies": {
"@types/react": "^17.0.1",
"@umijs/fabric": "^2.5.6",
"father-build": "^1.19.1",
"np": "^5.2.1",
"typescript": "^4.0.0"
},
"peerDependencies": {
"react": "*"
}
}