This commit is contained in:
Tutur33
2023-11-24 22:35:41 +01:00
parent 3c0b507a93
commit 7644b2a0f7
45165 changed files with 4803356 additions and 3 deletions
+166
View File
@@ -0,0 +1,166 @@
'use strict';
const every = require('@arr/every');
const SEP = '/';
// Types ~> static, param, any, optional
const STYPE=0, PTYPE=1, ATYPE=2, OTYPE=3;
// Char Codes ~> / : *
const SLASH=47, COLON=58, ASTER=42, QMARK=63;
function strip(str) {
if (str === SEP) return str;
(str.charCodeAt(0) === SLASH) && (str=str.substring(1));
var len = str.length - 1;
return str.charCodeAt(len) === SLASH ? str.substring(0, len) : str;
}
function split(str) {
return (str=strip(str)) === SEP ? [SEP] : str.split(SEP);
}
function isMatch(arr, obj, idx) {
idx = arr[idx];
if (obj.val === idx && obj.type === STYPE) {
return true
}
if (idx === SEP) {
return obj.type > PTYPE
}
if (obj.type === STYPE) {
return false
}
/**
* When param is not the last param
*/
if (idx === '') {
return obj.end === '' && (!!obj.matcher ? obj.matcher.test(idx) : true)
}
/**
* Last param
*/
if (!idx) {
return obj.end === ''
}
return idx.endsWith(obj.end) && (!!obj.matcher ? obj.matcher.test(idx) : true)
}
function match(str, all) {
let segs=split(str), len=segs.length, l;
let i=0, tmp;
var fn = isMatch.bind(isMatch, segs);
for (; i < all.length; i++) {
tmp = all[i];
if ((l=tmp.length) === len || (l < len && tmp[l-1].type === ATYPE) || (l > len && tmp[l-1].type === OTYPE)) {
if (every(tmp, fn)) return tmp;
}
}
return [];
}
function parse(str, matchers) {
if (str === SEP) {
return [{ old:str, type:STYPE, val:str, end:'' }];
}
if (typeof matchers !== 'object') {
matchers = {};
}
let c, x, t, sfx, val, nxt=strip(str), i=-1, j=0, len=nxt.length, out=[];
while (++i < len) {
c = nxt.charCodeAt(i);
if (c === COLON) {
j = i + 1; // begining of param
t = PTYPE; // set type
x = 0; // reset mark
sfx = '';
while (i < len && nxt.charCodeAt(i) !== SLASH) {
c = nxt.charCodeAt(i);
if (c === QMARK) {
x=i; t=OTYPE;
} else if (c === 46 && sfx.length === 0) {
sfx = nxt.substring(x=i);
}
i++; // move on
}
val = nxt.substring(j, x||i);
const matcher = matchers[val]
out.push({
old: str,
type: t,
val: val,
end: sfx,
matcher: matcher && matcher.match,
cast: matcher && matcher.cast
});
// shorten string & update pointers
nxt=nxt.substring(i); len-=i; i=0;
continue; // loop
} else if (c === ASTER) {
out.push({
old: str,
type: ATYPE,
val: nxt.substring(i),
end: ''
});
continue; // loop
} else {
j = i;
while (i < len && nxt.charCodeAt(i) !== SLASH) {
++i; // skip to next slash
}
val = nxt.substring(j, i);
out.push({
old: str,
type: STYPE,
val: val,
end: ''
});
// shorten string & update pointers
nxt=nxt.substring(i); len-=i; i=j=0;
}
}
return out;
}
function exec(str, arr) {
let i=0, x, y, segs=split(str), out={};
for (; i < arr.length; i++) {
x=segs[i]; y=arr[i];
if (x === SEP) continue;
if (y.val === '*') {
out[y.val] = segs.slice(i)
break
}
if (x !== void 0 && y.type | 2 === OTYPE) {
const value = x.replace(y.end, '');
out[ y.val ] = y.cast ? y.cast(value) : value
}
}
return out;
}
exports.exec = exec;
exports.match = match;
exports.parse = parse;
+9
View File
@@ -0,0 +1,9 @@
# The MIT License
Copyright 2020 Harminder virk, contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+47
View File
@@ -0,0 +1,47 @@
{
"name": "@poppinss/matchit",
"version": "3.1.2",
"description": "Quickly parse & match URLs",
"main": "lib/matchit.js",
"license": "MIT",
"files": [
"lib"
],
"scripts": {
"build": "bundt",
"bench": "node bench",
"pretest": "npm run build",
"prebench": "npm run build",
"test": "tape test/*.js | tap-spec"
},
"keywords": [
"route",
"regexp",
"routing",
"pattern",
"match",
"parse",
"url"
],
"dependencies": {
"@arr/every": "^1.0.0"
},
"devDependencies": {
"bundt": "^1.1.2",
"tap-spec": "^5.0.0",
"tape": "^5.2.2"
},
"directories": {
"lib": "lib",
"test": "test"
},
"repository": {
"type": "git",
"url": "git+https://github.com/poppinss/matchit.git"
},
"author": "virk,poppinss",
"bugs": {
"url": "https://github.com/poppinss/matchit/issues"
},
"homepage": "https://github.com/poppinss/matchit#readme"
}
+172
View File
@@ -0,0 +1,172 @@
# MatchIt
> Quickly parse & match URLs. Forked from `lukeed/matchit`
[![circleci-image]][circleci-url] [![npm-image]][npm-url] [![license-image]][license-url] [![synk-image]][synk-url]
## Install
```
$ npm install --save matchit
```
## Usage
```js
const { exec, match, parse } = require('matchit');
parse('/foo/:bar/:baz?');
//=> [
//=> { old:'/foo/:bar', type:0, val:'foo' },
//=> { old:'/foo/:bar', type:1, val:'bar' },
//=> { old:'/foo/:bar', type:3, val:'baz' }
//=> ]
const routes = ['/', '/foo', 'bar', '/baz', '/baz/:title','/bat/*'].map(parse);
match('/', routes);
//=> [{ old:'/', type:0, val:'/' }]
match('/foo', routes);
//=> [{ old:'/foo', type:0, val:'foo' }]
match('/bar', routes);
//=> [{ old:'bar', type:0, val:'bar' }]
match('/baz', routes);
//=> [{ old:'/baz', type:0, val:'baz' }]
let a = match('/baz/hello', routes);
//=> [{...}, {...}]
let b = exec('/baz/hello', a);
//=> { title:'hello' }
match('/bat/quz/qut', routes);
//=> [
//=> { old:'/bat/*', type:0, val:'bat' },
//=> { old:'/bat/*', type:2, val:'*' }
//=> ]
```
## API
### matchit.parse(route)
Returns: `Array`
The `route` is `split` and parsed into a "definition" array of objects. Each object ("segment") contains a `val`, `type`, and `old` key:
* `old` &mdash; The [`route`](#route)'s original value
* `type` &mdash; An numerical representation of the segment type.
* `0` - static
* `1` - parameter
* `2` - any/wildcard
* `3` - optional param
* `val` &mdash; The current segment's value. This is either a static value of the name of a parameter
#### route
Type: `String`
A single URL pattern.
> **Note:** Input will be stripped of all leading & trailing `/` characters, so there's no need to normalize your own URLs before passing it to `parse`!
### matchit.match(url, routes)
Returns: `Array`
Returns the [`route`](#route)'s encoded definition. See [`matchit.parse`](#matchitparseroute).
#### url
Type: `String`
The true URL you want to be matched.
#### routes
Type: `Array`
_All_ "parsed" route definitions, via [`matchit.parse`](#matchitparseroute).
> **Important:** Multiple routes will require an Array of `matchit.parse` outputs.
### matchit.exec(url, match)
Returns: `Object`
Returns an object an object of `key:val` pairs, as defined by your [`route`](#route) pattern.
#### url
Type: `String`
The URL (`pathname`) to evaluate.
> **Important:** This should be `pathname`s only as any `querystring`s will be included the response.
#### match
Type: `Array`
The route definition to use, via [`matchit.match`](#matchitmatchurl-routes).
## Benchmarks
> Running Node v10.13.0
```
# Parsing
matchit x 1,489,482 ops/sec ±2.89% (97 runs sampled)
regexparam x 406,824 ops/sec ±1.38% (96 runs sampled)
path-to-regexp x 83,439 ops/sec ±0.89% (96 runs sampled)
path-to-regexp.parse x 421,266 ops/sec ±0.13% (97 runs sampled)
# Match (index)
matchit x 132,338,546 ops/sec ±0.14% (96 runs sampled)
regexparam x 49,889,162 ops/sec ±0.21% (95 runs sampled)
path-to-regexp.exec x 7,176,721 ops/sec ±1.23% (94 runs sampled)
path-to-regexp.tokens x 102,021 ops/sec ±0.21% (96 runs sampled)
# Match (param)
matchit x 2,700,618 ops/sec ±0.92% (95 runs sampled)
regexparam x 6,924,653 ops/sec ±0.33% (94 runs sampled)
path-to-regexp.exec x 4,715,483 ops/sec ±0.28% (96 runs sampled)
path-to-regexp.tokens x 98,182 ops/sec ±0.45% (93 runs sampled)
# Match (optional)
matchit x 2,816,313 ops/sec ±0.64% (93 runs sampled)
regexparam x 8,437,064 ops/sec ±0.41% (93 runs sampled)
path-to-regexp.exec x 5,909,510 ops/sec ±0.22% (97 runs sampled)
path-to-regexp.tokens x 101,832 ops/sec ±0.43% (98 runs sampled)
# Match (wildcard)
matchit x 3,409,100 ops/sec ±0.34% (98 runs sampled)
regexparam x 9,740,429 ops/sec ±0.49% (95 runs sampled)
path-to-regexp.exec x 8,740,590 ops/sec ±0.43% (89 runs sampled)
path-to-regexp.tokens x 102,109 ops/sec ±0.35% (96 runs sampled)
# Exec
matchit x 1,558,321 ops/sec ±0.33% (96 runs sampled)
regexparam x 6,966,297 ops/sec ±0.21% (97 runs sampled)
path-to-regexp x 102,250 ops/sec ±0.45% (95 runs sampled)
```
[circleci-image]: https://img.shields.io/circleci/project/github/poppinss/matchit/master.svg?style=for-the-badge&logo=circleci
[circleci-url]: https://circleci.com/gh/poppinss/matchit "circleci"
[npm-image]: https://img.shields.io/npm/v/@poppinss/matchit.svg?style=for-the-badge&logo=npm
[npm-url]: https://npmjs.org/package/@poppinss/matchit "npm"
[license-image]: https://img.shields.io/npm/l/@poppinss/matchit?color=blueviolet&style=for-the-badge
[license-url]: license.md "license"
[synk-image]: https://img.shields.io/snyk/vulnerabilities/github/poppinss/matchit?label=Synk%20Vulnerabilities&style=for-the-badge
[synk-url]: https://snyk.io/test/github/poppinss/matchit?targetFile=package.json "synk"