This commit is contained in:
2024-03-22 03:47:51 +05:30
parent 8bcf3d211e
commit 89819f6fe2
28440 changed files with 3211033 additions and 2 deletions

21
node_modules/serve-handler/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 ZEIT, Inc.
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.

320
node_modules/serve-handler/README.md generated vendored Normal file
View File

@@ -0,0 +1,320 @@
# serve-handler
[![codecov](https://codecov.io/gh/vercel/serve-handler/branch/main/graph/badge.svg)](https://codecov.io/gh/vercel/serve-handler)
[![install size](https://packagephobia.now.sh/badge?p=serve-handler)](https://packagephobia.now.sh/result?p=serve-handler)
This package represents the core of [serve](https://github.com/vercel/serve). It can be plugged into any HTTP server and is responsible for routing requests and handling responses.
In order to customize the default behaviour, you can also pass custom routing rules, provide your own methods for interacting with the file system and much more.
## Usage
Get started by installing the package using [yarn](https://yarnpkg.com/lang/en/):
```sh
yarn add serve-handler
```
You can also use [npm](https://www.npmjs.com/) instead, if you'd like:
```sh
npm install serve-handler
```
Next, add it to your HTTP server. Here's an example using [micro](https://github.com/vercel/micro):
```js
const handler = require('serve-handler');
module.exports = async (request, response) => {
await handler(request, response);
};
```
That's it! :tada:
## Options
If you want to customize the package's default behaviour, you can use the third argument of the function call to pass any of the configuration options listed below. Here's an example:
```js
await handler(request, response, {
cleanUrls: true
});
```
You can use any of the following options:
| Property | Description |
|------------------------------------------------------|-----------------------------------------------------------------------|
| [`public`](#public-string) | Set a sub directory to be served |
| [`cleanUrls`](#cleanurls-booleanarray) | Have the `.html` extension stripped from paths |
| [`rewrites`](#rewrites-array) | Rewrite paths to different paths |
| [`redirects`](#redirects-array) | Forward paths to different paths or external URLs |
| [`headers`](#headers-array) | Set custom headers for specific paths |
| [`directoryListing`](#directorylisting-booleanarray) | Disable directory listing or restrict it to certain paths |
| [`unlisted`](#unlisted-array) | Exclude paths from the directory listing |
| [`trailingSlash`](#trailingslash-boolean) | Remove or add trailing slashes to all paths |
| [`renderSingle`](#rendersingle-boolean) | If a directory only contains one file, render it |
| [`symlinks`](#symlinks-boolean) | Resolve symlinks instead of rendering a 404 error |
| [`etag`](#etag-boolean) | Calculate a strong `ETag` response header, instead of `Last-Modified` |
### public (String)
By default, the current working directory will be served. If you only want to serve a specific path, you can use this options to pass an absolute path or a custom directory to be served relative to the current working directory.
For example, if serving a [Jekyll](https://jekyllrb.com/) app, it would look like this:
```json
{
"public": "_site"
}
```
Using absolute path:
```json
{
"public": "/path/to/your/_site"
}
```
**NOTE:** The path cannot contain globs or regular expressions.
### cleanUrls (Boolean|Array)
By default, all `.html` files can be accessed without their extension.
If one of these extensions is used at the end of a filename, it will automatically perform a redirect with status code [301](https://en.wikipedia.org/wiki/HTTP_301) to the same path, but with the extension dropped.
You can disable the feature like follows:
```json
{
"cleanUrls": false
}
```
However, you can also restrict it to certain paths:
```json
{
"cleanUrls": [
"/app/**",
"/!components/**"
]
}
```
**NOTE:** The paths can only contain globs that are matched using [minimatch](https://github.com/isaacs/minimatch).
### rewrites (Array)
If you want your visitors to receive a response under a certain path, but actually serve a completely different one behind the curtains, this option is what you need.
It's perfect for [single page applications](https://en.wikipedia.org/wiki/Single-page_application) (SPAs), for example:
```json
{
"rewrites": [
{ "source": "app/**", "destination": "/index.html" },
{ "source": "projects/*/edit", "destination": "/edit-project.html" }
]
}
```
You can also use so-called "routing segments" as follows:
```json
{
"rewrites": [
{ "source": "/projects/:id/edit", "destination": "/edit-project-:id.html" },
]
}
```
Now, if a visitor accesses `/projects/123/edit`, it will respond with the file `/edit-project-123.html`.
**NOTE:** The paths can contain globs (matched using [minimatch](https://github.com/isaacs/minimatch)) or regular expressions (match using [path-to-regexp](https://github.com/pillarjs/path-to-regexp)).
### redirects (Array)
In order to redirect visits to a certain path to a different one (or even an external URL), you can use this option:
```json
{
"redirects": [
{ "source": "/from", "destination": "/to" },
{ "source": "/old-pages/**", "destination": "/home" }
]
}
```
By default, all of them are performed with the status code [301](https://en.wikipedia.org/wiki/HTTP_301), but this behavior can be adjusted by setting the `type` property directly on the object (see below).
Just like with [rewrites](#rewrites-array), you can also use routing segments:
```json
{
"redirects": [
{ "source": "/old-docs/:id", "destination": "/new-docs/:id" },
{ "source": "/old", "destination": "/new", "type": 302 }
]
}
```
In the example above, `/old-docs/12` would be forwarded to `/new-docs/12` with status code [301](https://en.wikipedia.org/wiki/HTTP_301). In addition `/old` would be forwarded to `/new` with status code [302](https://en.wikipedia.org/wiki/HTTP_302).
**NOTE:** The paths can contain globs (matched using [minimatch](https://github.com/isaacs/minimatch)) or regular expressions (match using [path-to-regexp](https://github.com/pillarjs/path-to-regexp)).
### headers (Array)
Allows you to set custom headers (and overwrite the default ones) for certain paths:
```json
{
"headers": [
{
"source" : "**/*.@(jpg|jpeg|gif|png)",
"headers" : [{
"key" : "Cache-Control",
"value" : "max-age=7200"
}]
}, {
"source" : "404.html",
"headers" : [{
"key" : "Cache-Control",
"value" : "max-age=300"
}]
}
]
}
```
If you define the `ETag` header for a path, the handler will automatically reply with status code `304` for that path if a request comes in with a matching `If-None-Match` header.
If you set a header `value` to `null` it removes any previous defined header with the same key.
**NOTE:** The paths can only contain globs that are matched using [minimatch](https://github.com/isaacs/minimatch).
### directoryListing (Boolean|Array)
For paths are not files, but directories, the package will automatically render a good-looking list of all the files and directories contained inside that directory.
If you'd like to disable this for all paths, set this option to `false`. Furthermore, you can also restrict it to certain directory paths if you want:
```json
{
"directoryListing": [
"/assets/**",
"/!assets/private"
]
}
```
**NOTE:** The paths can only contain globs that are matched using [minimatch](https://github.com/isaacs/minimatch).
### unlisted (Array)
In certain cases, you might not want a file or directory to appear in the directory listing. In these situations, there are two ways of solving this problem.
Either you disable the directory listing entirely (like shown [here](#directorylisting-booleanarray)), or you exclude certain paths from those listings by adding them all to this config property.
```json
{
"unlisted": [
".DS_Store",
".git"
]
}
```
The items shown above are excluded from the directory listing by default.
**NOTE:** The paths can only contain globs that are matched using [minimatch](https://github.com/isaacs/minimatch).
### trailingSlash (Boolean)
By default, the package will try to make assumptions for when to add trailing slashes to your URLs or not. If you want to remove them, set this property to `false` and `true` if you want to force them on all URLs:
```js
{
"trailingSlash": true
}
```
With the above config, a request to `/test` would now result in a [301](https://en.wikipedia.org/wiki/HTTP_301) redirect to `/test/`.
### renderSingle (Boolean)
Sometimes you might want to have a directory path actually render a file, if the directory only contains one. This is only useful for any files that are not `.html` files (for those, [`cleanUrls`](#cleanurls-booleanarray) is faster).
This is disabled by default and can be enabled like this:
```js
{
"renderSingle": true
}
```
After that, if you access your directory `/test` (for example), you will see an image being rendered if the directory contains a single image file.
### symlinks (Boolean)
For security purposes, symlinks are disabled by default. If `serve-handler` encounters a symlink, it will treat it as if it doesn't exist in the first place. In turn, a 404 error is rendered for that path.
However, this behavior can easily be adjusted:
```js
{
"symlinks": true
}
```
Once this property is set as shown above, all symlinks will automatically be resolved to their targets.
### etag (Boolean)
HTTP response headers will contain a strong [`ETag`][etag] response header, instead of a [`Last-Modified`][last-modified] header. Opt-in because calculating the hash value may be computationally expensive for large files.
Sending an `ETag` header is disabled by default and can be enabled like this:
```js
{
"etag": true
}
```
## Error templates
The handler will automatically determine the right error format if one occurs and then sends it to the client in that format.
Furthermore, this allows you to not just specifiy an error template for `404` errors, but also for all other errors that can occur (e.g. `400` or `500`).
Just add a `<status-code>.html` file to the root directory and you're good.
## Middleware
If you want to replace the methods the package is using for interacting with the file system and sending responses, you can pass them as the fourth argument to the function call.
These are the methods used by the package (they can all return a `Promise` or be asynchronous):
```js
await handler(request, response, undefined, {
lstat(path) {},
realpath(path) {},
createReadStream(path, config) {}
readdir(path) {},
sendError(absolutePath, response, acceptsJSON, root, handlers, config, error) {}
});
```
**NOTE:** It's important that for native methods like `createReadStream`  all arguments are passed on to the native call.
## Author
Leo Lamprecht ([@notquiteleo](https://twitter.com/notquiteleo)) - [Vercel](https://vercel.com)
[etag]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
[last-modified]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified

View File

@@ -0,0 +1,181 @@
2.2.0 / 2018-03-06
==================
* Pass `token` as second argument to `encode` option (e.g. `encode(value, token)`)
2.1.0 / 2017-10-20
==================
* Handle non-ending paths where the final character is a delimiter
* E.g. `/foo/` before required either `/foo/` or `/foo//` to match in non-ending mode
2.0.0 / 2017-08-23
==================
* New option! Ability to set `endsWith` to match paths like `/test?query=string` up to the query string
* New option! Set `delimiters` for specific characters to be treated as parameter prefixes (e.g. `/:test`)
* Remove `isarray` dependency
* Explicitly handle trailing delimiters instead of trimming them (e.g. `/test/` is now treated as `/test/` instead of `/test` when matching)
* Remove overloaded `keys` argument that accepted `options`
* Remove `keys` list attached to the `RegExp` output
* Remove asterisk functionality (it's a real pain to properly encode)
* Change `tokensToFunction` (e.g. `compile`) to accept an `encode` function for pretty encoding (e.g. pass your own implementation)
1.7.0 / 2016-11-08
==================
* Allow a `delimiter` option to be passed in with `tokensToRegExp` which will be used for "non-ending" token match situations
1.6.0 / 2016-10-03
==================
* Populate `RegExp.keys` when using the `tokensToRegExp` method (making it consistent with the main export)
* Allow a `delimiter` option to be passed in with `parse`
* Updated TypeScript definition with `Keys` and `Options` updated
1.5.3 / 2016-06-15
==================
* Add `\\` to the ignore character group to avoid backtracking on mismatched parens
1.5.2 / 2016-06-15
==================
* Escape `\\` in string segments of regexp
1.5.1 / 2016-06-08
==================
* Add `index.d.ts` to NPM package
1.5.0 / 2016-05-20
==================
* Handle partial token segments (better)
* Allow compile to handle asterisk token segments
1.4.0 / 2016-05-18
==================
* Handle RegExp unions in path matching groups
1.3.0 / 2016-05-08
==================
* Clarify README language and named parameter token support
* Support advanced Closure Compiler with type annotations
* Add pretty paths options to compiled function output
* Add TypeScript definition to project
* Improved prefix handling with non-complete segment parameters (E.g. `/:foo?-bar`)
1.2.1 / 2015-08-17
==================
* Encode values before validation with path compilation function
* More examples of using compilation in README
1.2.0 / 2015-05-20
==================
* Add support for matching an asterisk (`*`) as an unnamed match everything group (`(.*)`)
1.1.1 / 2015-05-11
==================
* Expose methods for working with path tokens
1.1.0 / 2015-05-09
==================
* Expose the parser implementation to consumers
* Implement a compiler function to generate valid strings
* Huge refactor of tests to be more DRY and cover new parse and compile functions
* Use chai in tests
* Add .editorconfig
1.0.3 / 2015-01-17
==================
* Optimised function runtime
* Added `files` to `package.json`
1.0.2 / 2014-12-17
==================
* Use `Array.isArray` shim
* Remove ES5 incompatible code
* Fixed repository path
* Added new readme badges
1.0.1 / 2014-08-27
==================
* Ensure installation works correctly on 0.8
1.0.0 / 2014-08-17
==================
* No more API changes
0.2.5 / 2014-08-07
==================
* Allow keys parameter to be omitted
0.2.4 / 2014-08-02
==================
* Code coverage badge
* Updated readme
* Attach keys to the generated regexp
0.2.3 / 2014-07-09
==================
* Add MIT license
0.2.2 / 2014-07-06
==================
* A passed in trailing slash in non-strict mode will become optional
* In non-end mode, the optional trailing slash will only match at the end
0.2.1 / 2014-06-11
==================
* Fixed a major capturing group regexp regression
0.2.0 / 2014-06-09
==================
* Improved support for arrays
* Improved support for regexps
* Better support for non-ending strict mode matches with a trailing slash
* Travis CI support
* Block using regexp special characters in the path
* Removed support for the asterisk to match all
* New support for parameter suffixes - `*`, `+` and `?`
* Updated readme
* Provide delimiter information with keys array
0.1.2 / 2014-03-10
==================
* Move testing dependencies to `devDependencies`
0.1.1 / 2014-03-10
==================
* Match entire substring with `options.end`
* Properly handle ending and non-ending matches
0.1.0 / 2014-03-06
==================
* Add `options.end`
0.0.2 / 2013-02-10
==================
* Update to match current express
* Add .license property to component.json

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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.

View File

@@ -0,0 +1,240 @@
# Path-to-RegExp
> Turn a path string such as `/user/:name` into a regular expression.
[![NPM version][npm-image]][npm-url]
[![Build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![Dependency Status][david-image]][david-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
## Installation
```
npm install path-to-regexp --save
```
## Usage
```javascript
var pathToRegexp = require('path-to-regexp')
// pathToRegexp(path, keys?, options?)
// pathToRegexp.parse(path)
// pathToRegexp.compile(path)
```
- **path** A string, array of strings, or a regular expression.
- **keys** An array to be populated with the keys found in the path.
- **options**
- **sensitive** When `true` the route will be case sensitive. (default: `false`)
- **strict** When `false` the trailing slash is optional. (default: `false`)
- **end** When `false` the path will match at the beginning. (default: `true`)
- Advanced options (use for non-pathname strings, e.g. host names):
- **delimiter** The default delimiter for segments. (default: `'/'`)
- **endsWith** Optional character, or list of characters, to treat as "end" characters.
- **delimiters** List of characters to consider delimiters when parsing. (default: `'./'`)
```javascript
var keys = []
var re = pathToRegexp('/foo/:bar', keys)
// re = /^\/foo\/([^\/]+?)\/?$/i
// keys = [{ name: 'bar', prefix: '/', delimiter: '/', optional: false, repeat: false, pattern: '[^\\/]+?' }]
```
**Please note:** The `RegExp` returned by `path-to-regexp` is intended for ordered data (e.g. pathnames, hostnames). It does not handle arbitrary data (e.g. query strings, URL fragments, JSON, etc).
### Parameters
The path argument is used to define parameters and populate the list of keys.
#### Named Parameters
Named parameters are defined by prefixing a colon to the parameter name (`:foo`). By default, the parameter will match until the following path segment.
```js
var re = pathToRegexp('/:foo/:bar')
// keys = [{ name: 'foo', prefix: '/', ... }, { name: 'bar', prefix: '/', ... }]
re.exec('/test/route')
//=> ['/test/route', 'test', 'route']
```
**Please note:** Parameter names must be made up of "word characters" (`[A-Za-z0-9_]`).
#### Parameter Modifiers
##### Optional
Parameters can be suffixed with a question mark (`?`) to make the parameter optional.
```js
var re = pathToRegexp('/:foo/:bar?')
// keys = [{ name: 'foo', ... }, { name: 'bar', delimiter: '/', optional: true, repeat: false }]
re.exec('/test')
//=> ['/test', 'test', undefined]
re.exec('/test/route')
//=> ['/test', 'test', 'route']
```
**Tip:** If the parameter is the _only_ value in the segment, the prefix is also optional.
##### Zero or more
Parameters can be suffixed with an asterisk (`*`) to denote a zero or more parameter matches. The prefix is taken into account for each match.
```js
var re = pathToRegexp('/:foo*')
// keys = [{ name: 'foo', delimiter: '/', optional: true, repeat: true }]
re.exec('/')
//=> ['/', undefined]
re.exec('/bar/baz')
//=> ['/bar/baz', 'bar/baz']
```
##### One or more
Parameters can be suffixed with a plus sign (`+`) to denote a one or more parameter matches. The prefix is taken into account for each match.
```js
var re = pathToRegexp('/:foo+')
// keys = [{ name: 'foo', delimiter: '/', optional: false, repeat: true }]
re.exec('/')
//=> null
re.exec('/bar/baz')
//=> ['/bar/baz', 'bar/baz']
```
#### Custom Matching Parameters
All parameters can be provided a custom regexp, which overrides the default match (`[^\/]+`). For example, you can match digits in the path:
```js
var re = pathToRegexp('/icon-:foo(\\d+).png')
// keys = [{ name: 'foo', ... }]
re.exec('/icon-123.png')
//=> ['/icon-123.png', '123']
re.exec('/icon-abc.png')
//=> null
```
**Please note:** Backslashes need to be escaped with another backslash in strings.
#### Unnamed Parameters
It is possible to write an unnamed parameter that only consists of a matching group. It works the same as a named parameter, except it will be numerically indexed.
```js
var re = pathToRegexp('/:foo/(.*)')
// keys = [{ name: 'foo', ... }, { name: 0, ... }]
re.exec('/test/route')
//=> ['/test/route', 'test', 'route']
```
### Parse
The parse function is exposed via `pathToRegexp.parse`. This will return an array of strings and keys.
```js
var tokens = pathToRegexp.parse('/route/:foo/(.*)')
console.log(tokens[0])
//=> "/route"
console.log(tokens[1])
//=> { name: 'foo', prefix: '/', delimiter: '/', optional: false, repeat: false, pattern: '[^\\/]+?' }
console.log(tokens[2])
//=> { name: 0, prefix: '/', delimiter: '/', optional: false, repeat: false, pattern: '.*' }
```
**Note:** This method only works with strings.
### Compile ("Reverse" Path-To-RegExp)
Path-To-RegExp exposes a compile function for transforming a string into a valid path.
```js
var toPath = pathToRegexp.compile('/user/:id')
toPath({ id: 123 }) //=> "/user/123"
toPath({ id: 'café' }) //=> "/user/caf%C3%A9"
toPath({ id: '/' }) //=> "/user/%2F"
toPath({ id: ':/' }) //=> "/user/%3A%2F"
toPath({ id: ':/' }, { encode: (value, token) => value }) //=> "/user/:/"
var toPathRepeated = pathToRegexp.compile('/:segment+')
toPathRepeated({ segment: 'foo' }) //=> "/foo"
toPathRepeated({ segment: ['a', 'b', 'c'] }) //=> "/a/b/c"
var toPathRegexp = pathToRegexp.compile('/user/:id(\\d+)')
toPathRegexp({ id: 123 }) //=> "/user/123"
toPathRegexp({ id: '123' }) //=> "/user/123"
toPathRegexp({ id: 'abc' }) //=> Throws `TypeError`.
```
**Note:** The generated function will throw on invalid input. It will do all necessary checks to ensure the generated path is valid. This method only works with strings.
### Working with Tokens
Path-To-RegExp exposes the two functions used internally that accept an array of tokens.
* `pathToRegexp.tokensToRegExp(tokens, keys?, options?)` Transform an array of tokens into a matching regular expression.
* `pathToRegexp.tokensToFunction(tokens)` Transform an array of tokens into a path generator function.
#### Token Information
* `name` The name of the token (`string` for named or `number` for index)
* `prefix` The prefix character for the segment (`/` or `.`)
* `delimiter` The delimiter for the segment (same as prefix or `/`)
* `optional` Indicates the token is optional (`boolean`)
* `repeat` Indicates the token is repeated (`boolean`)
* `partial` Indicates this token is a partial path segment (`boolean`)
* `pattern` The RegExp used to match this token (`string`)
## Compatibility with Express <= 4.x
Path-To-RegExp breaks compatibility with Express <= `4.x`:
* RegExp special characters can only be used in a parameter
* Express.js 4.x used all `RegExp` special characters regardless of position - this considered a bug
* Parameters have suffixes that augment meaning - `*`, `+` and `?`. E.g. `/:user*`
* No wildcard asterisk (`*`) - use parameters instead (`(.*)`)
## TypeScript
Includes a [`.d.ts`](index.d.ts) file for TypeScript users.
## Live Demo
You can see a live demo of this library in use at [express-route-tester](http://forbeslindesay.github.com/express-route-tester/).
## License
MIT
[npm-image]: https://img.shields.io/npm/v/path-to-regexp.svg?style=flat
[npm-url]: https://npmjs.org/package/path-to-regexp
[travis-image]: https://img.shields.io/travis/pillarjs/path-to-regexp.svg?style=flat
[travis-url]: https://travis-ci.org/pillarjs/path-to-regexp
[coveralls-image]: https://img.shields.io/coveralls/pillarjs/path-to-regexp.svg?style=flat
[coveralls-url]: https://coveralls.io/r/pillarjs/path-to-regexp?branch=master
[david-image]: http://img.shields.io/david/pillarjs/path-to-regexp.svg?style=flat
[david-url]: https://david-dm.org/pillarjs/path-to-regexp
[license-image]: http://img.shields.io/npm/l/path-to-regexp.svg?style=flat
[license-url]: LICENSE.md
[downloads-image]: http://img.shields.io/npm/dm/path-to-regexp.svg?style=flat
[downloads-url]: https://npmjs.org/package/path-to-regexp

View File

@@ -0,0 +1,80 @@
declare function pathToRegexp (path: pathToRegexp.Path, keys?: pathToRegexp.Key[], options?: pathToRegexp.RegExpOptions & pathToRegexp.ParseOptions): RegExp;
declare namespace pathToRegexp {
export interface RegExpOptions {
/**
* When `true` the route will be case sensitive. (default: `false`)
*/
sensitive?: boolean;
/**
* When `false` the trailing slash is optional. (default: `false`)
*/
strict?: boolean;
/**
* When `false` the path will match at the beginning. (default: `true`)
*/
end?: boolean;
/**
* Sets the final character for non-ending optimistic matches. (default: `/`)
*/
delimiter?: string;
/**
* List of characters that can also be "end" characters.
*/
endsWith?: string | string[];
}
export interface ParseOptions {
/**
* Set the default delimiter for repeat parameters. (default: `'/'`)
*/
delimiter?: string;
/**
* List of valid delimiter characters. (default: `'./'`)
*/
delimiters?: string | string[];
}
/**
* Parse an Express-style path into an array of tokens.
*/
export function parse (path: string, options?: ParseOptions): Token[];
/**
* Transforming an Express-style path into a valid path.
*/
export function compile (path: string, options?: ParseOptions): PathFunction;
/**
* Transform an array of tokens into a path generator function.
*/
export function tokensToFunction (tokens: Token[]): PathFunction;
/**
* Transform an array of tokens into a matching regular expression.
*/
export function tokensToRegExp (tokens: Token[], keys?: Key[], options?: RegExpOptions): RegExp;
export interface Key {
name: string | number;
prefix: string;
delimiter: string;
optional: boolean;
repeat: boolean;
pattern: string;
partial: boolean;
}
interface PathFunctionOptions {
/**
* Function for encoding input strings for output.
*/
encode?: (value: string, token: Key) => string;
}
export type Token = string | Key;
export type Path = string | RegExp | Array<string | RegExp>;
export type PathFunction = (data?: Object, options?: PathFunctionOptions) => string;
}
export = pathToRegexp;

View File

@@ -0,0 +1,371 @@
/**
* Expose `pathToRegexp`.
*/
module.exports = pathToRegexp
module.exports.parse = parse
module.exports.compile = compile
module.exports.tokensToFunction = tokensToFunction
module.exports.tokensToRegExp = tokensToRegExp
/**
* Default configs.
*/
var DEFAULT_DELIMITER = '/'
var DEFAULT_DELIMITERS = './'
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
var PATH_REGEXP = new RegExp([
// Match escaped characters that would otherwise appear in future matches.
// This allows the user to escape special characters that won't transform.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?"]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined]
'(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?'
].join('|'), 'g')
/**
* Parse a string for the raw tokens.
*
* @param {string} str
* @param {Object=} options
* @return {!Array}
*/
function parse (str, options) {
var tokens = []
var key = 0
var index = 0
var path = ''
var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER
var delimiters = (options && options.delimiters) || DEFAULT_DELIMITERS
var pathEscaped = false
var res
while ((res = PATH_REGEXP.exec(str)) !== null) {
var m = res[0]
var escaped = res[1]
var offset = res.index
path += str.slice(index, offset)
index = offset + m.length
// Ignore already escaped sequences.
if (escaped) {
path += escaped[1]
pathEscaped = true
continue
}
var prev = ''
var next = str[index]
var name = res[2]
var capture = res[3]
var group = res[4]
var modifier = res[5]
if (!pathEscaped && path.length) {
var k = path.length - 1
if (delimiters.indexOf(path[k]) > -1) {
prev = path[k]
path = path.slice(0, k)
}
}
// Push the current path onto the tokens.
if (path) {
tokens.push(path)
path = ''
pathEscaped = false
}
var partial = prev !== '' && next !== undefined && next !== prev
var repeat = modifier === '+' || modifier === '*'
var optional = modifier === '?' || modifier === '*'
var delimiter = prev || defaultDelimiter
var pattern = capture || group
tokens.push({
name: name || key++,
prefix: prev,
delimiter: delimiter,
optional: optional,
repeat: repeat,
partial: partial,
pattern: pattern ? escapeGroup(pattern) : '[^' + escapeString(delimiter) + ']+?'
})
}
// Push any remaining characters.
if (path || index < str.length) {
tokens.push(path + str.substr(index))
}
return tokens
}
/**
* Compile a string to a template function for the path.
*
* @param {string} str
* @param {Object=} options
* @return {!function(Object=, Object=)}
*/
function compile (str, options) {
return tokensToFunction(parse(str, options))
}
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction (tokens) {
// Compile all the tokens into regexps.
var matches = new Array(tokens.length)
// Compile all the patterns before compilation.
for (var i = 0; i < tokens.length; i++) {
if (typeof tokens[i] === 'object') {
matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$')
}
}
return function (data, options) {
var path = ''
var encode = (options && options.encode) || encodeURIComponent
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 segment
if (Array.isArray(value)) {
if (!token.repeat) {
throw new TypeError('Expected "' + token.name + '" to not repeat, but got array')
}
if (value.length === 0) {
if (token.optional) continue
throw new TypeError('Expected "' + token.name + '" to not be empty')
}
for (var j = 0; j < value.length; j++) {
segment = encode(value[j], token)
if (!matches[i].test(segment)) {
throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '"')
}
path += (j === 0 ? token.prefix : token.delimiter) + segment
}
continue
}
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
segment = encode(String(value), token)
if (!matches[i].test(segment)) {
throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"')
}
path += token.prefix + segment
continue
}
if (token.optional) {
// Prepend partial segment prefixes.
if (token.partial) path += token.prefix
continue
}
throw new TypeError('Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string'))
}
return path
}
}
/**
* Escape a regular expression string.
*
* @param {string} str
* @return {string}
*/
function escapeString (str) {
return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1')
}
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {string} group
* @return {string}
*/
function escapeGroup (group) {
return group.replace(/([=!:$/()])/g, '\\$1')
}
/**
* Get the flags for a regexp from the options.
*
* @param {Object} options
* @return {string}
*/
function flags (options) {
return options && options.sensitive ? '' : 'i'
}
/**
* Pull out keys from a regexp.
*
* @param {!RegExp} path
* @param {Array=} keys
* @return {!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: null,
delimiter: null,
optional: false,
repeat: false,
partial: false,
pattern: null
})
}
}
return path
}
/**
* Transform an array into a regexp.
*
* @param {!Array} path
* @param {Array=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function arrayToRegexp (path, keys, options) {
var parts = []
for (var i = 0; i < path.length; i++) {
parts.push(pathToRegexp(path[i], keys, options).source)
}
return new RegExp('(?:' + parts.join('|') + ')', flags(options))
}
/**
* Create a path regexp from string input.
*
* @param {string} path
* @param {Array=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function stringToRegexp (path, keys, options) {
return tokensToRegExp(parse(path, options), keys, options)
}
/**
* Expose a function for taking tokens and returning a RegExp.
*
* @param {!Array} tokens
* @param {Array=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function tokensToRegExp (tokens, keys, options) {
options = options || {}
var strict = options.strict
var end = options.end !== false
var delimiter = escapeString(options.delimiter || DEFAULT_DELIMITER)
var delimiters = options.delimiters || DEFAULT_DELIMITERS
var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|')
var route = ''
var isEndDelimited = tokens.length === 0
// Iterate over the tokens and create our regexp string.
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i]
if (typeof token === 'string') {
route += escapeString(token)
isEndDelimited = i === tokens.length - 1 && delimiters.indexOf(token[token.length - 1]) > -1
} else {
var prefix = escapeString(token.prefix)
var capture = token.repeat
? '(?:' + token.pattern + ')(?:' + prefix + '(?:' + token.pattern + '))*'
: token.pattern
if (keys) keys.push(token)
if (token.optional) {
if (token.partial) {
route += prefix + '(' + capture + ')?'
} else {
route += '(?:' + prefix + '(' + capture + '))?'
}
} else {
route += prefix + '(' + capture + ')'
}
}
}
if (end) {
if (!strict) route += '(?:' + delimiter + ')?'
route += endsWith === '$' ? '$' : '(?=' + endsWith + ')'
} else {
if (!strict) route += '(?:' + delimiter + '(?=' + endsWith + '))?'
if (!isEndDelimited) route += '(?=' + delimiter + '|' + endsWith + ')'
}
return new RegExp('^' + route, flags(options))
}
/**
* 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 }]`.
*
* @param {(string|RegExp|Array)} path
* @param {Array=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function pathToRegexp (path, keys, options) {
if (path instanceof RegExp) {
return regexpToRegexp(path, keys)
}
if (Array.isArray(path)) {
return arrayToRegexp(/** @type {!Array} */ (path), keys, options)
}
return stringToRegexp(/** @type {string} */ (path), keys, options)
}

View File

@@ -0,0 +1,45 @@
{
"name": "path-to-regexp",
"description": "Express style path to RegExp utility",
"version": "2.2.1",
"main": "index.js",
"typings": "index.d.ts",
"files": [
"index.js",
"index.d.ts",
"LICENSE"
],
"scripts": {
"lint": "standard",
"test-spec": "mocha --require ts-node/register -R spec --bail test.ts",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require ts-node/register -R spec test.ts",
"test": "npm run lint && npm run test-cov"
},
"keywords": [
"express",
"regexp",
"route",
"routing"
],
"component": {
"scripts": {
"path-to-regexp": "index.js"
}
},
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/pillarjs/path-to-regexp.git"
},
"devDependencies": {
"@types/chai": "^4.0.4",
"@types/mocha": "^2.2.42",
"@types/node": "^8.0.24",
"chai": "^4.1.1",
"istanbul": "^0.4.5",
"mocha": "^3.5.0",
"standard": "^10.0.3",
"ts-node": "^3.3.0",
"typescript": "^2.4.2"
}
}

74
node_modules/serve-handler/package.json generated vendored Normal file
View File

@@ -0,0 +1,74 @@
{
"name": "serve-handler",
"version": "6.1.5",
"description": "The routing foundation of `serve` and static deployments on Now",
"main": "src/index.js",
"scripts": {
"test": "yarn run test-lint && yarn run test-integration",
"test-lint": "zeit-eslint --ext .jsx,.js .",
"test-integration": "nyc --reporter=html --reporter=text ava test/integration.js",
"coverage": "nyc report --reporter=text-lcov > coverage.lcov",
"lint-staged": "git diff --diff-filter=ACMRT --cached --name-only '*.js' '*.jsx' | xargs zeit-eslint",
"build-views": "dottojs -s ./src -d ./src",
"prepublishOnly": "yarn run build-views"
},
"repository": "zeit/serve-handler",
"keywords": [
"static",
"deployment",
"server"
],
"author": "leo",
"license": "MIT",
"files": [
"src/index.js",
"src/glob-slash.js",
"src/directory.js",
"src/error.js"
],
"devDependencies": {
"@zeit/eslint-config-node": "0.2.13",
"@zeit/git-hooks": "0.1.4",
"ava": "2.2.0",
"commander": "2.15.1",
"dot": "1.1.3",
"eslint": "6.1.0",
"fs-extra": "6.0.1",
"micro": "9.3.2",
"node-fetch": "2.6.1",
"nyc": "14.1.1",
"request": "2.87.0",
"sleep-promise": "6.0.0",
"test-listen": "1.1.0"
},
"eslintConfig": {
"extends": [
"@zeit/eslint-config-node"
]
},
"nyc": {
"exclude": [
"src/directory.js",
"src/error.js",
"test/*"
]
},
"eslintIgnore": [
"error.js",
"directory.js",
"coverage"
],
"git": {
"pre-commit": "lint-staged"
},
"dependencies": {
"bytes": "3.0.0",
"content-disposition": "0.5.2",
"fast-url-parser": "1.1.3",
"mime-types": "2.1.18",
"minimatch": "3.1.2",
"path-is-inside": "1.0.2",
"path-to-regexp": "2.2.1",
"range-parser": "1.2.0"
}
}

16
node_modules/serve-handler/src/directory.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
(function(){function directory(it
) {
var encodeHTML = typeof _encodeHTML !== 'undefined' ? _encodeHTML : (function(doNotSkipEncoded) {
var encodeHTMLRules = { "&": "&#38;", "<": "&#60;", ">": "&#62;", '"': "&#34;", "'": "&#39;", "/": "&#47;" },
matchHTML = doNotSkipEncoded ? /[&<>"'\/]/g : /&(?!#?\w+;)|<|>|"|'|\//g;
return function(code) {
return code ? code.toString().replace(matchHTML, function(m) {return encodeHTMLRules[m] || m;}) : "";
};
}());var out='<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Files within '+encodeHTML(it.directory)+'</title> <style>body { margin: 0; padding: 30px; background: #fff; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif; -webkit-font-smoothing: antialiased;}main { max-width: 920px;}header { display: flex; justify-content: space-between; flex-wrap: wrap;}h1 { font-size: 18px; font-weight: 500; margin-top: 0; color: #000;}header h1 a { font-size: 18px; font-weight: 500; margin-top: 0; color: #000;}h1 i { font-style: normal;}ul { margin: 0 0 0 -2px; padding: 20px 0 0 0;}ul li { list-style: none; font-size: 14px; display: flex; justify-content: space-between;}a { text-decoration: none;}ul a { color: #000; padding: 10px 5px; margin: 0 -5px; white-space: nowrap; overflow: hidden; display: block; width: 100%; text-overflow: ellipsis;}header a { color: #0076FF; font-size: 11px; font-weight: 400; display: inline-block; line-height: 20px;}svg { height: 13px; vertical-align: text-bottom;}ul a::before { display: inline-block; vertical-align: middle; margin-right: 10px; width: 24px; text-align: center; line-height: 12px;}ul a.file::before { content: url("data:image/svg+xml;utf8,<svg width=\'15\' height=\'19\' fill=\'none\' xmlns=\'http://www.w3.org/2000/svg\'><path d=\'M10 8C8.34 8 7 6.66 7 5V1H3c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2h9c1.1 0 2-.9 2-2V8h-4zM8 5c0 1.1.9 2 2 2h3.59L8 1.41V5zM3 0h5l7 7v9c0 1.66-1.34 3-3 3H3c-1.66 0-3-1.34-3-3V3c0-1.66 1.34-3 3-3z\' fill=\'black\'/></svg>");}ul a:hover { text-decoration: underline;}ul a.folder::before { content: url("data:image/svg+xml;utf8,<svg width=\'20\' height=\'16\' fill=\'none\' xmlns=\'http://www.w3.org/2000/svg\'><path d=\'M18.784 3.87a1.565 1.565 0 0 0-.565-.356V2.426c0-.648-.523-1.171-1.15-1.171H8.996L7.908.25A.89.89 0 0 0 7.302 0H2.094C1.445 0 .944.523.944 1.171v2.3c-.21.085-.398.21-.565.356a1.348 1.348 0 0 0-.377 1.004l.398 9.83C.42 15.393 1.048 16 1.8 16h15.583c.753 0 1.36-.586 1.4-1.339l.398-9.83c.021-.313-.125-.69-.397-.962zM1.843 3.41V1.191c0-.146.104-.272.25-.272H7.26l1.234 1.088c.083.042.167.104.293.104h8.282c.125 0 .25.126.25.272V3.41H1.844zm15.54 11.712H1.78a.47.47 0 0 1-.481-.46l-.397-9.83c0-.147.041-.252.125-.356a.504.504 0 0 1 .377-.147H17.78c.125 0 .272.063.377.147.083.083.125.209.125.334l-.418 9.83c-.021.272-.23.482-.481.482z\' fill=\'black\'/></svg>");}ul a.lambda::before { content: url("data:image/svg+xml; utf8,<svg width=\'15\' height=\'19\' fill=\'none\' xmlns=\'http://www.w3.org/2000/svg\'><path d=\'M3.5 14.4354H5.31622L7.30541 9.81311H7.43514L8.65315 13.0797C9.05676 14.1643 9.55405 14.5 10.7 14.5C11.0171 14.5 11.291 14.4677 11.5 14.4032V13.1572C11.3847 13.1766 11.2622 13.2024 11.1541 13.2024C10.6351 13.2024 10.3829 13.0281 10.1595 12.4664L8.02613 7.07586C7.21171 5.01646 6.54865 4.5 5.11441 4.5C4.83333 4.5 4.62432 4.53228 4.37207 4.59038V5.83635C4.56667 5.81052 4.66036 5.79761 4.77568 5.79761C5.64775 5.79761 5.9 6.0042 6.4045 7.19852L6.64234 7.77954L3.5 14.4354Z\' fill=\'black\'/><rect x=\'0.5\' y=\'0.5\' width=\'14\' height=\'18\' rx=\'2.5\' stroke=\'black\'/></svg>");}ul a.file.gif::before,ul a.file.jpg::before,ul a.file.png::before,ul a.file.svg::before { content: url("data:image/svg+xml;utf8,<svg width=\'16\' height=\'16\' viewBox=\'0 0 80 80\' xmlns=\'http://www.w3.org/2000/svg\' fill=\'none\' stroke=\'black\' stroke-width=\'5\' stroke-linecap=\'round\' stroke-linejoin=\'round\'><rect x=\'6\' y=\'6\' width=\'68\' height=\'68\' rx=\'5\' ry=\'5\'/><circle cx=\'24\' cy=\'24\' r=\'8\'/><path d=\'M73 49L59 34 37 52m16 20L27 42 7 58\'/></svg>");}::selection { background-color: #79FFE1; color: #000;}::-moz-selection { background-color: #79FFE1; color: #000;}@media (min-width: 768px) { ul {display: flex;flex-wrap: wrap; } ul li {width: 230px;padding-right: 20px; }}@media (min-width: 992px) { body {padding: 45px; } h1, header h1 a {font-size: 15px; } ul li {font-size: 13px;box-sizing: border-box;justify-content: flex-start; }}</style> </head> <body> <main> <header> <h1> <i>Index of&nbsp;</i> ';var arr1=it.paths;if(arr1){var value,index=-1,l1=arr1.length-1;while(index<l1){value=arr1[index+=1];out+=' <a href="/'+encodeHTML(value.url)+'">'+encodeHTML(value.name)+'</a> ';} } out+=' </h1> </header> <ul id="files"> ';var arr2=it.files;if(arr2){var value,index=-1,l2=arr2.length-1;while(index<l2){value=arr2[index+=1];out+=' <li> <a href="'+encodeHTML(value.relative)+'" title="'+encodeHTML(value.title)+'" class="'+encodeHTML(value.type)+' '+encodeHTML(value.ext)+'">'+encodeHTML(value.base)+'</a> </li> ';} } out+=' </ul></main> </body></html>';return out;
}var itself=directory, _encodeHTML=(function(doNotSkipEncoded) {
var encodeHTMLRules = { "&": "&#38;", "<": "&#60;", ">": "&#62;", '"': "&#34;", "'": "&#39;", "/": "&#47;" },
matchHTML = doNotSkipEncoded ? /[&<>"'\/]/g : /&(?!#?\w+;)|<|>|"|'|\//g;
return function(code) {
return code ? code.toString().replace(matchHTML, function(m) {return encodeHTMLRules[m] || m;}) : "";
};
}());if(typeof module!=='undefined' && module.exports) module.exports=itself;else if(typeof define==='function')define(function(){return itself;});else {window.render=window.render||{};window.render['directory']=itself;}}());

10
node_modules/serve-handler/src/error.js generated vendored Normal file
View File

@@ -0,0 +1,10 @@
(function(){function error(it
) {
var out='<!DOCTYPE html><head> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/> <style> body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif; cursor: default; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; position: absolute; top: 0; left: 0; right: 0; bottom: 0; display: flex; flex-direction: column; } main, aside, section { display: flex; justify-content: center; align-items: center; flex-direction: column; } main { height: 100%; } aside { background: #000; flex-shrink: 1; padding: 30px 20px; } aside p { margin: 0; color: #999999; font-size: 14px; line-height: 24px; } aside a { color: #fff; text-decoration: none; } section span { font-size: 24px; font-weight: 500; display: block; border-bottom: 1px solid #EAEAEA; text-align: center; padding-bottom: 20px; width: 100px; } section p { font-size: 14px; font-weight: 400; } section span + p { margin: 20px 0 0 0; } @media (min-width: 768px) { section { height: 40px; flex-direction: row; } section span, section p { height: 100%; line-height: 40px; } section span { border-bottom: 0; border-right: 1px solid #EAEAEA; padding: 0 20px 0 0; width: auto; } section span + p { margin: 0; padding-left: 20px; } aside { padding: 50px 0; } aside p { max-width: 520px; text-align: center; } } </style></head><body> <main> <section> <span>'+(it.statusCode)+'</span> <p>'+(it.message)+'</p> </section> </main></body>';return out;
}var itself=error, _encodeHTML=(function(doNotSkipEncoded) {
var encodeHTMLRules = { "&": "&#38;", "<": "&#60;", ">": "&#62;", '"': "&#34;", "'": "&#39;", "/": "&#47;" },
matchHTML = doNotSkipEncoded ? /[&<>"'\/]/g : /&(?!#?\w+;)|<|>|"|'|\//g;
return function(code) {
return code ? code.toString().replace(matchHTML, function(m) {return encodeHTMLRules[m] || m;}) : "";
};
}());if(typeof module!=='undefined' && module.exports) module.exports=itself;else if(typeof define==='function')define(function(){return itself;});else {window.render=window.render||{};window.render['error']=itself;}}());

9
node_modules/serve-handler/src/glob-slash.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
/* ! The MIT License (MIT) Copyright (c) 2014 Scott Corgan */
// This is adopted from https://github.com/scottcorgan/glob-slash/
const path = require('path');
const normalize = value => path.posix.normalize(path.posix.join('/', value));
module.exports = value => (value.charAt(0) === '!' ? `!${normalize(value.substr(1))}` : normalize(value));
module.exports.normalize = normalize;

756
node_modules/serve-handler/src/index.js generated vendored Normal file
View File

@@ -0,0 +1,756 @@
// Native
const {promisify} = require('util');
const path = require('path');
const {createHash} = require('crypto');
const {realpath, lstat, createReadStream, readdir} = require('fs');
// Packages
const url = require('fast-url-parser');
const slasher = require('./glob-slash');
const minimatch = require('minimatch');
const pathToRegExp = require('path-to-regexp');
const mime = require('mime-types');
const bytes = require('bytes');
const contentDisposition = require('content-disposition');
const isPathInside = require('path-is-inside');
const parseRange = require('range-parser');
// Other
const directoryTemplate = require('./directory');
const errorTemplate = require('./error');
const etags = new Map();
const calculateSha = (handlers, absolutePath) =>
new Promise((resolve, reject) => {
const hash = createHash('sha1');
hash.update(path.extname(absolutePath));
hash.update('-');
const rs = handlers.createReadStream(absolutePath);
rs.on('error', reject);
rs.on('data', buf => hash.update(buf));
rs.on('end', () => {
const sha = hash.digest('hex');
resolve(sha);
});
});
const sourceMatches = (source, requestPath, allowSegments) => {
const keys = [];
const slashed = slasher(source);
const resolvedPath = path.posix.resolve(requestPath);
let results = null;
if (allowSegments) {
const normalized = slashed.replace('*', '(.*)');
const expression = pathToRegExp(normalized, keys);
results = expression.exec(resolvedPath);
if (!results) {
// clear keys so that they are not used
// later with empty results. this may
// happen if minimatch returns true
keys.length = 0;
}
}
if (results || minimatch(resolvedPath, slashed)) {
return {
keys,
results
};
}
return null;
};
const toTarget = (source, destination, previousPath) => {
const matches = sourceMatches(source, previousPath, true);
if (!matches) {
return null;
}
const {keys, results} = matches;
const props = {};
const {protocol} = url.parse(destination);
const normalizedDest = protocol ? destination : slasher(destination);
const toPath = pathToRegExp.compile(normalizedDest);
for (let index = 0; index < keys.length; index++) {
const {name} = keys[index];
props[name] = results[index + 1];
}
return toPath(props);
};
const applyRewrites = (requestPath, rewrites = [], repetitive) => {
// We need to copy the array, since we're going to modify it.
const rewritesCopy = rewrites.slice();
// If the method was called again, the path was already rewritten
// so we need to make sure to return it.
const fallback = repetitive ? requestPath : null;
if (rewritesCopy.length === 0) {
return fallback;
}
for (let index = 0; index < rewritesCopy.length; index++) {
const {source, destination} = rewrites[index];
const target = toTarget(source, destination, requestPath);
if (target) {
// Remove rules that were already applied
rewritesCopy.splice(index, 1);
// Check if there are remaining ones to be applied
return applyRewrites(slasher(target), rewritesCopy, true);
}
}
return fallback;
};
const ensureSlashStart = target => (target.startsWith('/') ? target : `/${target}`);
const shouldRedirect = (decodedPath, {redirects = [], trailingSlash}, cleanUrl) => {
const slashing = typeof trailingSlash === 'boolean';
const defaultType = 301;
const matchHTML = /(\.html|\/index)$/g;
if (redirects.length === 0 && !slashing && !cleanUrl) {
return null;
}
// By stripping the HTML parts from the decoded
// path *before* handling the trailing slash, we make
// sure that only *one* redirect occurs if both
// config options are used.
if (cleanUrl && matchHTML.test(decodedPath)) {
decodedPath = decodedPath.replace(matchHTML, '');
if (decodedPath.indexOf('//') > -1) {
decodedPath = decodedPath.replace(/\/+/g, '/');
}
return {
target: ensureSlashStart(decodedPath),
statusCode: defaultType
};
}
if (slashing) {
const {ext, name} = path.parse(decodedPath);
const isTrailed = decodedPath.endsWith('/');
const isDotfile = name.startsWith('.');
let target = null;
if (!trailingSlash && isTrailed) {
target = decodedPath.slice(0, -1);
} else if (trailingSlash && !isTrailed && !ext && !isDotfile) {
target = `${decodedPath}/`;
}
if (decodedPath.indexOf('//') > -1) {
target = decodedPath.replace(/\/+/g, '/');
}
if (target) {
return {
target: ensureSlashStart(target),
statusCode: defaultType
};
}
}
// This is currently the fastest way to
// iterate over an array
for (let index = 0; index < redirects.length; index++) {
const {source, destination, type} = redirects[index];
const target = toTarget(source, destination, decodedPath);
if (target) {
return {
target,
statusCode: type || defaultType
};
}
}
return null;
};
const appendHeaders = (target, source) => {
for (let index = 0; index < source.length; index++) {
const {key, value} = source[index];
target[key] = value;
}
};
const getHeaders = async (handlers, config, current, absolutePath, stats) => {
const {headers: customHeaders = [], etag = false} = config;
const related = {};
const {base} = path.parse(absolutePath);
const relativePath = path.relative(current, absolutePath);
if (customHeaders.length > 0) {
// By iterating over all headers and never stopping, developers
// can specify multiple header sources in the config that
// might match a single path.
for (let index = 0; index < customHeaders.length; index++) {
const {source, headers} = customHeaders[index];
if (sourceMatches(source, slasher(relativePath))) {
appendHeaders(related, headers);
}
}
}
let defaultHeaders = {};
if (stats) {
defaultHeaders = {
'Content-Length': stats.size,
// Default to "inline", which always tries to render in the browser,
// if that's not working, it will save the file. But to be clear: This
// only happens if it cannot find a appropiate value.
'Content-Disposition': contentDisposition(base, {
type: 'inline'
}),
'Accept-Ranges': 'bytes'
};
if (etag) {
let [mtime, sha] = etags.get(absolutePath) || [];
if (Number(mtime) !== Number(stats.mtime)) {
sha = await calculateSha(handlers, absolutePath);
etags.set(absolutePath, [stats.mtime, sha]);
}
defaultHeaders['ETag'] = `"${sha}"`;
} else {
defaultHeaders['Last-Modified'] = stats.mtime.toUTCString();
}
const contentType = mime.contentType(base);
if (contentType) {
defaultHeaders['Content-Type'] = contentType;
}
}
const headers = Object.assign(defaultHeaders, related);
for (const key in headers) {
if (headers.hasOwnProperty(key) && headers[key] === null) {
delete headers[key];
}
}
return headers;
};
const applicable = (decodedPath, configEntry) => {
if (typeof configEntry === 'boolean') {
return configEntry;
}
if (Array.isArray(configEntry)) {
for (let index = 0; index < configEntry.length; index++) {
const source = configEntry[index];
if (sourceMatches(source, decodedPath)) {
return true;
}
}
return false;
}
return true;
};
const getPossiblePaths = (relativePath, extension) => [
path.join(relativePath, `index${extension}`),
relativePath.endsWith('/') ? relativePath.replace(/\/$/g, extension) : (relativePath + extension)
].filter(item => path.basename(item) !== extension);
const findRelated = async (current, relativePath, rewrittenPath, originalStat) => {
const possible = rewrittenPath ? [rewrittenPath] : getPossiblePaths(relativePath, '.html');
let stats = null;
for (let index = 0; index < possible.length; index++) {
const related = possible[index];
const absolutePath = path.join(current, related);
try {
stats = await originalStat(absolutePath);
} catch (err) {
if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') {
throw err;
}
}
if (stats) {
return {
stats,
absolutePath
};
}
}
return null;
};
const canBeListed = (excluded, file) => {
const slashed = slasher(file);
let whether = true;
for (let mark = 0; mark < excluded.length; mark++) {
const source = excluded[mark];
if (sourceMatches(source, slashed)) {
whether = false;
break;
}
}
return whether;
};
const renderDirectory = async (current, acceptsJSON, handlers, methods, config, paths) => {
const {directoryListing, trailingSlash, unlisted = [], renderSingle} = config;
const slashSuffix = typeof trailingSlash === 'boolean' ? (trailingSlash ? '/' : '') : '/';
const {relativePath, absolutePath} = paths;
const excluded = [
'.DS_Store',
'.git',
...unlisted
];
if (!applicable(relativePath, directoryListing) && !renderSingle) {
return {};
}
let files = await handlers.readdir(absolutePath);
const canRenderSingle = renderSingle && (files.length === 1);
for (let index = 0; index < files.length; index++) {
const file = files[index];
const filePath = path.resolve(absolutePath, file);
const details = path.parse(filePath);
// It's important to indicate that the `stat` call was
// spawned by the directory listing, as Now is
// simulating those calls and needs to special-case this.
let stats = null;
if (methods.lstat) {
stats = await handlers.lstat(filePath, true);
} else {
stats = await handlers.lstat(filePath);
}
details.relative = path.join(relativePath, details.base);
if (stats.isDirectory()) {
details.base += slashSuffix;
details.relative += slashSuffix;
details.type = 'folder';
} else {
if (canRenderSingle) {
return {
singleFile: true,
absolutePath: filePath,
stats
};
}
details.ext = details.ext.split('.')[1] || 'txt';
details.type = 'file';
details.size = bytes(stats.size, {
unitSeparator: ' ',
decimalPlaces: 0
});
}
details.title = details.base;
if (canBeListed(excluded, file)) {
files[index] = details;
} else {
delete files[index];
}
}
const toRoot = path.relative(current, absolutePath);
const directory = path.join(path.basename(current), toRoot, slashSuffix);
const pathParts = directory.split(path.sep).filter(Boolean);
// Sort to list directories first, then sort alphabetically
files = files.sort((a, b) => {
const aIsDir = a.type === 'directory';
const bIsDir = b.type === 'directory';
/* istanbul ignore next */
if (aIsDir && !bIsDir) {
return -1;
}
if ((bIsDir && !aIsDir) || (a.base > b.base)) {
return 1;
}
/* istanbul ignore next */
if (a.base < b.base) {
return -1;
}
/* istanbul ignore next */
return 0;
}).filter(Boolean);
// Add parent directory to the head of the sorted files array
if (toRoot.length > 0) {
const directoryPath = [...pathParts].slice(1);
const relative = path.join('/', ...directoryPath, '..', slashSuffix);
files.unshift({
type: 'directory',
base: '..',
relative,
title: relative,
ext: ''
});
}
const subPaths = [];
for (let index = 0; index < pathParts.length; index++) {
const parents = [];
const isLast = index === (pathParts.length - 1);
let before = 0;
while (before <= index) {
parents.push(pathParts[before]);
before++;
}
parents.shift();
subPaths.push({
name: pathParts[index] + (isLast ? slashSuffix : '/'),
url: index === 0 ? '' : parents.join('/') + slashSuffix
});
}
const spec = {
files,
directory,
paths: subPaths
};
const output = acceptsJSON ? JSON.stringify(spec) : directoryTemplate(spec);
return {directory: output};
};
const sendError = async (absolutePath, response, acceptsJSON, current, handlers, config, spec) => {
const {err: original, message, code, statusCode} = spec;
/* istanbul ignore next */
if (original && process.env.NODE_ENV !== 'test') {
console.error(original);
}
response.statusCode = statusCode;
if (acceptsJSON) {
response.setHeader('Content-Type', 'application/json; charset=utf-8');
response.end(JSON.stringify({
error: {
code,
message
}
}));
return;
}
let stats = null;
const errorPage = path.join(current, `${statusCode}.html`);
try {
stats = await handlers.lstat(errorPage);
} catch (err) {
if (err.code !== 'ENOENT') {
console.error(err);
}
}
if (stats) {
let stream = null;
try {
stream = await handlers.createReadStream(errorPage);
const headers = await getHeaders(handlers, config, current, errorPage, stats);
response.writeHead(statusCode, headers);
stream.pipe(response);
return;
} catch (err) {
console.error(err);
}
}
const headers = await getHeaders(handlers, config, current, absolutePath, null);
headers['Content-Type'] = 'text/html; charset=utf-8';
response.writeHead(statusCode, headers);
response.end(errorTemplate({statusCode, message}));
};
const internalError = async (...args) => {
const lastIndex = args.length - 1;
const err = args[lastIndex];
args[lastIndex] = {
statusCode: 500,
code: 'internal_server_error',
message: 'A server error has occurred',
err
};
return sendError(...args);
};
const getHandlers = methods => Object.assign({
lstat: promisify(lstat),
realpath: promisify(realpath),
createReadStream,
readdir: promisify(readdir),
sendError
}, methods);
module.exports = async (request, response, config = {}, methods = {}) => {
const cwd = process.cwd();
const current = config.public ? path.resolve(cwd, config.public) : cwd;
const handlers = getHandlers(methods);
let relativePath = null;
let acceptsJSON = null;
if (request.headers.accept) {
acceptsJSON = request.headers.accept.includes('application/json');
}
try {
relativePath = decodeURIComponent(url.parse(request.url).pathname);
} catch (err) {
return sendError('/', response, acceptsJSON, current, handlers, config, {
statusCode: 400,
code: 'bad_request',
message: 'Bad Request'
});
}
let absolutePath = path.join(current, relativePath);
// Prevent path traversal vulnerabilities. We could do this
// by ourselves, but using the package covers all the edge cases.
if (!isPathInside(absolutePath, current)) {
return sendError(absolutePath, response, acceptsJSON, current, handlers, config, {
statusCode: 400,
code: 'bad_request',
message: 'Bad Request'
});
}
const cleanUrl = applicable(relativePath, config.cleanUrls);
const redirect = shouldRedirect(relativePath, config, cleanUrl);
if (redirect) {
response.writeHead(redirect.statusCode, {
Location: encodeURI(redirect.target)
});
response.end();
return;
}
let stats = null;
// It's extremely important that we're doing multiple stat calls. This one
// right here could technically be removed, but then the program
// would be slower. Because for directories, we always want to see if a related file
// exists and then (after that), fetch the directory itself if no
// related file was found. However (for files, of which most have extensions), we should
// always stat right away.
//
// When simulating a file system without directory indexes, calculating whether a
// directory exists requires loading all the file paths and then checking if
// one of them includes the path of the directory. As that's a very
// performance-expensive thing to do, we need to ensure it's not happening if not really necessary.
if (path.extname(relativePath) !== '') {
try {
stats = await handlers.lstat(absolutePath);
} catch (err) {
if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') {
return internalError(absolutePath, response, acceptsJSON, current, handlers, config, err);
}
}
}
const rewrittenPath = applyRewrites(relativePath, config.rewrites);
if (!stats && (cleanUrl || rewrittenPath)) {
try {
const related = await findRelated(current, relativePath, rewrittenPath, handlers.lstat);
if (related) {
({stats, absolutePath} = related);
}
} catch (err) {
if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') {
return internalError(absolutePath, response, acceptsJSON, current, handlers, config, err);
}
}
}
if (!stats) {
try {
stats = await handlers.lstat(absolutePath);
} catch (err) {
if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') {
return internalError(absolutePath, response, acceptsJSON, current, handlers, config, err);
}
}
}
if (stats && stats.isDirectory()) {
let directory = null;
let singleFile = null;
try {
const related = await renderDirectory(current, acceptsJSON, handlers, methods, config, {
relativePath,
absolutePath
});
if (related.singleFile) {
({stats, absolutePath, singleFile} = related);
} else {
({directory} = related);
}
} catch (err) {
if (err.code !== 'ENOENT') {
return internalError(absolutePath, response, acceptsJSON, current, handlers, config, err);
}
}
if (directory) {
const contentType = acceptsJSON ? 'application/json; charset=utf-8' : 'text/html; charset=utf-8';
response.statusCode = 200;
response.setHeader('Content-Type', contentType);
response.end(directory);
return;
}
if (!singleFile) {
// The directory listing is disabled, so we want to
// render a 404 error.
stats = null;
}
}
const isSymLink = stats && stats.isSymbolicLink();
// There are two scenarios in which we want to reply with
// a 404 error: Either the path does not exist, or it is a
// symlink while the `symlinks` option is disabled (which it is by default).
if (!stats || (!config.symlinks && isSymLink)) {
// allow for custom 404 handling
return handlers.sendError(absolutePath, response, acceptsJSON, current, handlers, config, {
statusCode: 404,
code: 'not_found',
message: 'The requested path could not be found'
});
}
// If we figured out that the target is a symlink, we need to
// resolve the symlink and run a new `stat` call just for the
// target of that symlink.
if (isSymLink) {
absolutePath = await handlers.realpath(absolutePath);
stats = await handlers.lstat(absolutePath);
}
const streamOpts = {};
// TODO ? if-range
if (request.headers.range && stats.size) {
const range = parseRange(stats.size, request.headers.range);
if (typeof range === 'object' && range.type === 'bytes') {
const {start, end} = range[0];
streamOpts.start = start;
streamOpts.end = end;
response.statusCode = 206;
} else {
response.statusCode = 416;
response.setHeader('Content-Range', `bytes */${stats.size}`);
}
}
// TODO ? multiple ranges
let stream = null;
try {
stream = await handlers.createReadStream(absolutePath, streamOpts);
} catch (err) {
return internalError(absolutePath, response, acceptsJSON, current, handlers, config, err);
}
const headers = await getHeaders(handlers, config, current, absolutePath, stats);
// eslint-disable-next-line no-undefined
if (streamOpts.start !== undefined && streamOpts.end !== undefined) {
headers['Content-Range'] = `bytes ${streamOpts.start}-${streamOpts.end}/${stats.size}`;
headers['Content-Length'] = streamOpts.end - streamOpts.start + 1;
}
// We need to check for `headers.ETag` being truthy first, otherwise it will
// match `undefined` being equal to `undefined`, which is true.
//
// Checking for `undefined` and `null` is also important, because `Range` can be `0`.
//
// eslint-disable-next-line no-eq-null
if (request.headers.range == null && headers.ETag && headers.ETag === request.headers['if-none-match']) {
response.statusCode = 304;
response.end();
return;
}
response.writeHead(response.statusCode || 200, headers);
stream.pipe(response);
};