initial commit (app returns google/startpage results)
This commit is contained in:
+1272
File diff suppressed because it is too large
Load Diff
+250
@@ -0,0 +1,250 @@
|
||||
2.0.0 / 2024-08-31
|
||||
==================
|
||||
|
||||
* Drop node <18 support
|
||||
* deps: mime-types@^3.0.0
|
||||
* deps: negotiator@^1.0.0
|
||||
|
||||
1.3.8 / 2022-02-02
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.34
|
||||
- deps: mime-db@~1.51.0
|
||||
* deps: negotiator@0.6.3
|
||||
|
||||
1.3.7 / 2019-04-29
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.6.2
|
||||
- Fix sorting charset, encoding, and language with extra parameters
|
||||
|
||||
1.3.6 / 2019-04-28
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.24
|
||||
- deps: mime-db@~1.40.0
|
||||
|
||||
1.3.5 / 2018-02-28
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.18
|
||||
- deps: mime-db@~1.33.0
|
||||
|
||||
1.3.4 / 2017-08-22
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.16
|
||||
- deps: mime-db@~1.29.0
|
||||
|
||||
1.3.3 / 2016-05-02
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.11
|
||||
- deps: mime-db@~1.23.0
|
||||
* deps: negotiator@0.6.1
|
||||
- perf: improve `Accept` parsing speed
|
||||
- perf: improve `Accept-Charset` parsing speed
|
||||
- perf: improve `Accept-Encoding` parsing speed
|
||||
- perf: improve `Accept-Language` parsing speed
|
||||
|
||||
1.3.2 / 2016-03-08
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.10
|
||||
- Fix extension of `application/dash+xml`
|
||||
- Update primary extension for `audio/mp4`
|
||||
- deps: mime-db@~1.22.0
|
||||
|
||||
1.3.1 / 2016-01-19
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.9
|
||||
- deps: mime-db@~1.21.0
|
||||
|
||||
1.3.0 / 2015-09-29
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.7
|
||||
- deps: mime-db@~1.19.0
|
||||
* deps: negotiator@0.6.0
|
||||
- Fix including type extensions in parameters in `Accept` parsing
|
||||
- Fix parsing `Accept` parameters with quoted equals
|
||||
- Fix parsing `Accept` parameters with quoted semicolons
|
||||
- Lazy-load modules from main entry point
|
||||
- perf: delay type concatenation until needed
|
||||
- perf: enable strict mode
|
||||
- perf: hoist regular expressions
|
||||
- perf: remove closures getting spec properties
|
||||
- perf: remove a closure from media type parsing
|
||||
- perf: remove property delete from media type parsing
|
||||
|
||||
1.2.13 / 2015-09-06
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.6
|
||||
- deps: mime-db@~1.18.0
|
||||
|
||||
1.2.12 / 2015-07-30
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.4
|
||||
- deps: mime-db@~1.16.0
|
||||
|
||||
1.2.11 / 2015-07-16
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.3
|
||||
- deps: mime-db@~1.15.0
|
||||
|
||||
1.2.10 / 2015-07-01
|
||||
===================
|
||||
|
||||
* deps: mime-types@~2.1.2
|
||||
- deps: mime-db@~1.14.0
|
||||
|
||||
1.2.9 / 2015-06-08
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.1
|
||||
- perf: fix deopt during mapping
|
||||
|
||||
1.2.8 / 2015-06-07
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.1.0
|
||||
- deps: mime-db@~1.13.0
|
||||
* perf: avoid argument reassignment & argument slice
|
||||
* perf: avoid negotiator recursive construction
|
||||
* perf: enable strict mode
|
||||
* perf: remove unnecessary bitwise operator
|
||||
|
||||
1.2.7 / 2015-05-10
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.5.3
|
||||
- Fix media type parameter matching to be case-insensitive
|
||||
|
||||
1.2.6 / 2015-05-07
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.11
|
||||
- deps: mime-db@~1.9.1
|
||||
* deps: negotiator@0.5.2
|
||||
- Fix comparing media types with quoted values
|
||||
- Fix splitting media types with quoted commas
|
||||
|
||||
1.2.5 / 2015-03-13
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.10
|
||||
- deps: mime-db@~1.8.0
|
||||
|
||||
1.2.4 / 2015-02-14
|
||||
==================
|
||||
|
||||
* Support Node.js 0.6
|
||||
* deps: mime-types@~2.0.9
|
||||
- deps: mime-db@~1.7.0
|
||||
* deps: negotiator@0.5.1
|
||||
- Fix preference sorting to be stable for long acceptable lists
|
||||
|
||||
1.2.3 / 2015-01-31
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.8
|
||||
- deps: mime-db@~1.6.0
|
||||
|
||||
1.2.2 / 2014-12-30
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.7
|
||||
- deps: mime-db@~1.5.0
|
||||
|
||||
1.2.1 / 2014-12-30
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.5
|
||||
- deps: mime-db@~1.3.1
|
||||
|
||||
1.2.0 / 2014-12-19
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.5.0
|
||||
- Fix list return order when large accepted list
|
||||
- Fix missing identity encoding when q=0 exists
|
||||
- Remove dynamic building of Negotiator class
|
||||
|
||||
1.1.4 / 2014-12-10
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.4
|
||||
- deps: mime-db@~1.3.0
|
||||
|
||||
1.1.3 / 2014-11-09
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.3
|
||||
- deps: mime-db@~1.2.0
|
||||
|
||||
1.1.2 / 2014-10-14
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.4.9
|
||||
- Fix error when media type has invalid parameter
|
||||
|
||||
1.1.1 / 2014-09-28
|
||||
==================
|
||||
|
||||
* deps: mime-types@~2.0.2
|
||||
- deps: mime-db@~1.1.0
|
||||
* deps: negotiator@0.4.8
|
||||
- Fix all negotiations to be case-insensitive
|
||||
- Stable sort preferences of same quality according to client order
|
||||
|
||||
1.1.0 / 2014-09-02
|
||||
==================
|
||||
|
||||
* update `mime-types`
|
||||
|
||||
1.0.7 / 2014-07-04
|
||||
==================
|
||||
|
||||
* Fix wrong type returned from `type` when match after unknown extension
|
||||
|
||||
1.0.6 / 2014-06-24
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.4.7
|
||||
|
||||
1.0.5 / 2014-06-20
|
||||
==================
|
||||
|
||||
* fix crash when unknown extension given
|
||||
|
||||
1.0.4 / 2014-06-19
|
||||
==================
|
||||
|
||||
* use `mime-types`
|
||||
|
||||
1.0.3 / 2014-06-11
|
||||
==================
|
||||
|
||||
* deps: negotiator@0.4.6
|
||||
- Order by specificity when quality is the same
|
||||
|
||||
1.0.2 / 2014-05-29
|
||||
==================
|
||||
|
||||
* Fix interpretation when header not in request
|
||||
* deps: pin negotiator@0.4.5
|
||||
|
||||
1.0.1 / 2014-01-18
|
||||
==================
|
||||
|
||||
* Identity encoding isn't always acceptable
|
||||
* deps: negotiator@~0.4.0
|
||||
|
||||
1.0.0 / 2013-12-27
|
||||
==================
|
||||
|
||||
* Genesis
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
|
||||
Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.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.
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
# accepts
|
||||
|
||||
[![NPM Version][npm-version-image]][npm-url]
|
||||
[![NPM Downloads][npm-downloads-image]][npm-url]
|
||||
[![Node.js Version][node-version-image]][node-version-url]
|
||||
[![Build Status][github-actions-ci-image]][github-actions-ci-url]
|
||||
[![Test Coverage][coveralls-image]][coveralls-url]
|
||||
|
||||
Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator).
|
||||
Extracted from [koa](https://www.npmjs.com/package/koa) for general use.
|
||||
|
||||
In addition to negotiator, it allows:
|
||||
|
||||
- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])`
|
||||
as well as `('text/html', 'application/json')`.
|
||||
- Allows type shorthands such as `json`.
|
||||
- Returns `false` when no types match
|
||||
- Treats non-existent headers as `*`
|
||||
|
||||
## Installation
|
||||
|
||||
This is a [Node.js](https://nodejs.org/en/) module available through the
|
||||
[npm registry](https://www.npmjs.com/). Installation is done using the
|
||||
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
|
||||
|
||||
```sh
|
||||
$ npm install accepts
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
```js
|
||||
var accepts = require('accepts')
|
||||
```
|
||||
|
||||
### accepts(req)
|
||||
|
||||
Create a new `Accepts` object for the given `req`.
|
||||
|
||||
#### .charset(charsets)
|
||||
|
||||
Return the first accepted charset. If nothing in `charsets` is accepted,
|
||||
then `false` is returned.
|
||||
|
||||
#### .charsets()
|
||||
|
||||
Return the charsets that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
#### .encoding(encodings)
|
||||
|
||||
Return the first accepted encoding. If nothing in `encodings` is accepted,
|
||||
then `false` is returned.
|
||||
|
||||
#### .encodings()
|
||||
|
||||
Return the encodings that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
#### .language(languages)
|
||||
|
||||
Return the first accepted language. If nothing in `languages` is accepted,
|
||||
then `false` is returned.
|
||||
|
||||
#### .languages()
|
||||
|
||||
Return the languages that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
#### .type(types)
|
||||
|
||||
Return the first accepted type (and it is returned as the same text as what
|
||||
appears in the `types` array). If nothing in `types` is accepted, then `false`
|
||||
is returned.
|
||||
|
||||
The `types` array can contain full MIME types or file extensions. Any value
|
||||
that is not a full MIME type is passed to `require('mime-types').lookup`.
|
||||
|
||||
#### .types()
|
||||
|
||||
Return the types that the request accepts, in the order of the client's
|
||||
preference (most preferred first).
|
||||
|
||||
## Examples
|
||||
|
||||
### Simple type negotiation
|
||||
|
||||
This simple example shows how to use `accepts` to return a different typed
|
||||
respond body based on what the client wants to accept. The server lists it's
|
||||
preferences in order and will get back the best match between the client and
|
||||
server.
|
||||
|
||||
```js
|
||||
var accepts = require('accepts')
|
||||
var http = require('http')
|
||||
|
||||
function app (req, res) {
|
||||
var accept = accepts(req)
|
||||
|
||||
// the order of this list is significant; should be server preferred order
|
||||
switch (accept.type(['json', 'html'])) {
|
||||
case 'json':
|
||||
res.setHeader('Content-Type', 'application/json')
|
||||
res.write('{"hello":"world!"}')
|
||||
break
|
||||
case 'html':
|
||||
res.setHeader('Content-Type', 'text/html')
|
||||
res.write('<b>hello, world!</b>')
|
||||
break
|
||||
default:
|
||||
// the fallback is text/plain, so no need to specify it above
|
||||
res.setHeader('Content-Type', 'text/plain')
|
||||
res.write('hello, world!')
|
||||
break
|
||||
}
|
||||
|
||||
res.end()
|
||||
}
|
||||
|
||||
http.createServer(app).listen(3000)
|
||||
```
|
||||
|
||||
You can test this out with the cURL program:
|
||||
```sh
|
||||
curl -I -H'Accept: text/html' http://localhost:3000/
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master
|
||||
[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master
|
||||
[github-actions-ci-image]: https://badgen.net/github/checks/jshttp/accepts/master?label=ci
|
||||
[github-actions-ci-url]: https://github.com/jshttp/accepts/actions/workflows/ci.yml
|
||||
[node-version-image]: https://badgen.net/npm/node/accepts
|
||||
[node-version-url]: https://nodejs.org/en/download
|
||||
[npm-downloads-image]: https://badgen.net/npm/dm/accepts
|
||||
[npm-url]: https://npmjs.org/package/accepts
|
||||
[npm-version-image]: https://badgen.net/npm/v/accepts
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
/*!
|
||||
* accepts
|
||||
* Copyright(c) 2014 Jonathan Ong
|
||||
* Copyright(c) 2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var Negotiator = require('negotiator')
|
||||
var mime = require('mime-types')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
* @public
|
||||
*/
|
||||
|
||||
module.exports = Accepts
|
||||
|
||||
/**
|
||||
* Create a new Accepts object for the given req.
|
||||
*
|
||||
* @param {object} req
|
||||
* @public
|
||||
*/
|
||||
|
||||
function Accepts (req) {
|
||||
if (!(this instanceof Accepts)) {
|
||||
return new Accepts(req)
|
||||
}
|
||||
|
||||
this.headers = req.headers
|
||||
this.negotiator = new Negotiator(req)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given `type(s)` is acceptable, returning
|
||||
* the best match when true, otherwise `undefined`, in which
|
||||
* case you should respond with 406 "Not Acceptable".
|
||||
*
|
||||
* The `type` value may be a single mime type string
|
||||
* such as "application/json", the extension name
|
||||
* such as "json" or an array `["json", "html", "text/plain"]`. When a list
|
||||
* or array is given the _best_ match, if any is returned.
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* // Accept: text/html
|
||||
* this.types('html');
|
||||
* // => "html"
|
||||
*
|
||||
* // Accept: text/*, application/json
|
||||
* this.types('html');
|
||||
* // => "html"
|
||||
* this.types('text/html');
|
||||
* // => "text/html"
|
||||
* this.types('json', 'text');
|
||||
* // => "json"
|
||||
* this.types('application/json');
|
||||
* // => "application/json"
|
||||
*
|
||||
* // Accept: text/*, application/json
|
||||
* this.types('image/png');
|
||||
* this.types('png');
|
||||
* // => undefined
|
||||
*
|
||||
* // Accept: text/*;q=.5, application/json
|
||||
* this.types(['html', 'json']);
|
||||
* this.types('html', 'json');
|
||||
* // => "json"
|
||||
*
|
||||
* @param {String|Array} types...
|
||||
* @return {String|Array|Boolean}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.type =
|
||||
Accepts.prototype.types = function (types_) {
|
||||
var types = types_
|
||||
|
||||
// support flattened arguments
|
||||
if (types && !Array.isArray(types)) {
|
||||
types = new Array(arguments.length)
|
||||
for (var i = 0; i < types.length; i++) {
|
||||
types[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no types, return all requested types
|
||||
if (!types || types.length === 0) {
|
||||
return this.negotiator.mediaTypes()
|
||||
}
|
||||
|
||||
// no accept header, return first given type
|
||||
if (!this.headers.accept) {
|
||||
return types[0]
|
||||
}
|
||||
|
||||
var mimes = types.map(extToMime)
|
||||
var accepts = this.negotiator.mediaTypes(mimes.filter(validMime))
|
||||
var first = accepts[0]
|
||||
|
||||
return first
|
||||
? types[mimes.indexOf(first)]
|
||||
: false
|
||||
}
|
||||
|
||||
/**
|
||||
* Return accepted encodings or best fit based on `encodings`.
|
||||
*
|
||||
* Given `Accept-Encoding: gzip, deflate`
|
||||
* an array sorted by quality is returned:
|
||||
*
|
||||
* ['gzip', 'deflate']
|
||||
*
|
||||
* @param {String|Array} encodings...
|
||||
* @return {String|Array}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.encoding =
|
||||
Accepts.prototype.encodings = function (encodings_) {
|
||||
var encodings = encodings_
|
||||
|
||||
// support flattened arguments
|
||||
if (encodings && !Array.isArray(encodings)) {
|
||||
encodings = new Array(arguments.length)
|
||||
for (var i = 0; i < encodings.length; i++) {
|
||||
encodings[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no encodings, return all requested encodings
|
||||
if (!encodings || encodings.length === 0) {
|
||||
return this.negotiator.encodings()
|
||||
}
|
||||
|
||||
return this.negotiator.encodings(encodings)[0] || false
|
||||
}
|
||||
|
||||
/**
|
||||
* Return accepted charsets or best fit based on `charsets`.
|
||||
*
|
||||
* Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
|
||||
* an array sorted by quality is returned:
|
||||
*
|
||||
* ['utf-8', 'utf-7', 'iso-8859-1']
|
||||
*
|
||||
* @param {String|Array} charsets...
|
||||
* @return {String|Array}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.charset =
|
||||
Accepts.prototype.charsets = function (charsets_) {
|
||||
var charsets = charsets_
|
||||
|
||||
// support flattened arguments
|
||||
if (charsets && !Array.isArray(charsets)) {
|
||||
charsets = new Array(arguments.length)
|
||||
for (var i = 0; i < charsets.length; i++) {
|
||||
charsets[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no charsets, return all requested charsets
|
||||
if (!charsets || charsets.length === 0) {
|
||||
return this.negotiator.charsets()
|
||||
}
|
||||
|
||||
return this.negotiator.charsets(charsets)[0] || false
|
||||
}
|
||||
|
||||
/**
|
||||
* Return accepted languages or best fit based on `langs`.
|
||||
*
|
||||
* Given `Accept-Language: en;q=0.8, es, pt`
|
||||
* an array sorted by quality is returned:
|
||||
*
|
||||
* ['es', 'pt', 'en']
|
||||
*
|
||||
* @param {String|Array} langs...
|
||||
* @return {Array|String}
|
||||
* @public
|
||||
*/
|
||||
|
||||
Accepts.prototype.lang =
|
||||
Accepts.prototype.langs =
|
||||
Accepts.prototype.language =
|
||||
Accepts.prototype.languages = function (languages_) {
|
||||
var languages = languages_
|
||||
|
||||
// support flattened arguments
|
||||
if (languages && !Array.isArray(languages)) {
|
||||
languages = new Array(arguments.length)
|
||||
for (var i = 0; i < languages.length; i++) {
|
||||
languages[i] = arguments[i]
|
||||
}
|
||||
}
|
||||
|
||||
// no languages, return all requested languages
|
||||
if (!languages || languages.length === 0) {
|
||||
return this.negotiator.languages()
|
||||
}
|
||||
|
||||
return this.negotiator.languages(languages)[0] || false
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert extnames to mime.
|
||||
*
|
||||
* @param {String} type
|
||||
* @return {String}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function extToMime (type) {
|
||||
return type.indexOf('/') === -1
|
||||
? mime.lookup(type)
|
||||
: type
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if mime is valid.
|
||||
*
|
||||
* @param {String} type
|
||||
* @return {Boolean}
|
||||
* @private
|
||||
*/
|
||||
|
||||
function validMime (type) {
|
||||
return typeof type === 'string'
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "accepts",
|
||||
"description": "Higher-level content negotiation",
|
||||
"version": "2.0.0",
|
||||
"contributors": [
|
||||
"Douglas Christopher Wilson <doug@somethingdoug.com>",
|
||||
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": "jshttp/accepts",
|
||||
"dependencies": {
|
||||
"mime-types": "^3.0.0",
|
||||
"negotiator": "^1.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"deep-equal": "1.0.1",
|
||||
"eslint": "7.32.0",
|
||||
"eslint-config-standard": "14.1.1",
|
||||
"eslint-plugin-import": "2.25.4",
|
||||
"eslint-plugin-markdown": "2.2.1",
|
||||
"eslint-plugin-node": "11.1.0",
|
||||
"eslint-plugin-promise": "4.3.1",
|
||||
"eslint-plugin-standard": "4.1.0",
|
||||
"mocha": "9.2.0",
|
||||
"nyc": "15.1.0"
|
||||
},
|
||||
"files": [
|
||||
"LICENSE",
|
||||
"HISTORY.md",
|
||||
"index.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"test": "mocha --reporter spec --check-leaks --bail test/",
|
||||
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
|
||||
"test-cov": "nyc --reporter=html --reporter=text npm test"
|
||||
},
|
||||
"keywords": [
|
||||
"content",
|
||||
"negotiation",
|
||||
"accept",
|
||||
"accepts"
|
||||
]
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com>
|
||||
Copyright (c) 2014-2015 Douglas Christopher Wilson <doug@somethingdoug.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.
|
||||
+509
@@ -0,0 +1,509 @@
|
||||
# body-parser
|
||||
|
||||
[![NPM Version][npm-version-image]][npm-url]
|
||||
[![NPM Downloads][npm-downloads-image]][npm-url]
|
||||
[![Build Status][ci-image]][ci-url]
|
||||
[![Test Coverage][coveralls-image]][coveralls-url]
|
||||
[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]
|
||||
|
||||
Node.js body parsing middleware.
|
||||
|
||||
Parse incoming request bodies in a middleware before your handlers, available
|
||||
under the `req.body` property.
|
||||
|
||||
**Note** As `req.body`'s shape is based on user-controlled input, all
|
||||
properties and values in this object are untrusted and should be validated
|
||||
before trusting. For example, `req.body.foo.toString()` may fail in multiple
|
||||
ways, for example the `foo` property may not be there or may not be a string,
|
||||
and `toString` may not be a function and instead a string or other user input.
|
||||
|
||||
[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/learn/http/anatomy-of-an-http-transaction).
|
||||
|
||||
_This does not handle multipart bodies_, due to their complex and typically
|
||||
large nature. For multipart bodies, you may be interested in the following
|
||||
modules:
|
||||
|
||||
* [busboy](https://www.npmjs.com/package/busboy#readme) and
|
||||
[connect-busboy](https://www.npmjs.com/package/connect-busboy#readme)
|
||||
* [multiparty](https://www.npmjs.com/package/multiparty#readme) and
|
||||
[connect-multiparty](https://www.npmjs.com/package/connect-multiparty#readme)
|
||||
* [formidable](https://www.npmjs.com/package/formidable#readme)
|
||||
* [multer](https://www.npmjs.com/package/multer#readme)
|
||||
|
||||
This module provides the following parsers:
|
||||
|
||||
* [JSON body parser](#bodyparserjsonoptions)
|
||||
* [Raw body parser](#bodyparserrawoptions)
|
||||
* [Text body parser](#bodyparsertextoptions)
|
||||
* [URL-encoded form body parser](#bodyparserurlencodedoptions)
|
||||
|
||||
Other body parsers you might be interested in:
|
||||
|
||||
- [body](https://www.npmjs.com/package/body#readme)
|
||||
- [co-body](https://www.npmjs.com/package/co-body#readme)
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
$ npm install body-parser
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
```js
|
||||
// Import all parsers
|
||||
const bodyParser = require('body-parser')
|
||||
|
||||
// Or import individual parsers directly
|
||||
const json = require('body-parser/json')
|
||||
const urlencoded = require('body-parser/urlencoded')
|
||||
const raw = require('body-parser/raw')
|
||||
const text = require('body-parser/text')
|
||||
```
|
||||
|
||||
The `bodyParser` object exposes various factories to create middlewares. All
|
||||
middlewares will populate the `req.body` property with the parsed body when
|
||||
the `Content-Type` request header matches the `type` option.
|
||||
|
||||
The various errors returned by this module are described in the
|
||||
[errors section](#errors).
|
||||
|
||||
### bodyParser.json([options])
|
||||
|
||||
Returns middleware that only parses `json` and only looks at requests where
|
||||
the `Content-Type` header matches the `type` option. This parser accepts any
|
||||
Unicode encoding of the body and supports automatic inflation of `gzip`,
|
||||
`br` (brotli) and `deflate` encodings.
|
||||
|
||||
A new `body` object containing the parsed data is populated on the `request`
|
||||
object after the middleware (i.e. `req.body`).
|
||||
|
||||
#### Options
|
||||
|
||||
The `json` function takes an optional `options` object that may contain any of
|
||||
the following keys:
|
||||
|
||||
##### defaultCharset
|
||||
|
||||
Specify the default character set for the json content if the charset is not
|
||||
specified in the `Content-Type` header of the request. Defaults to `utf-8`.
|
||||
|
||||
##### inflate
|
||||
|
||||
When set to `true`, then deflated (compressed) bodies will be inflated; when
|
||||
`false`, deflated bodies are rejected. Defaults to `true`.
|
||||
|
||||
##### limit
|
||||
|
||||
Controls the maximum request body size. If this is a number, then the value
|
||||
specifies the number of bytes; if it is a string, the value is passed to the
|
||||
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
|
||||
to `'100kb'`.
|
||||
|
||||
> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur.
|
||||
|
||||
##### reviver
|
||||
|
||||
The `reviver` option is passed directly to `JSON.parse` as the second
|
||||
argument. You can find more information on this argument
|
||||
[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
|
||||
|
||||
##### strict
|
||||
|
||||
When set to `true`, will only accept arrays and objects; when `false` will
|
||||
accept anything `JSON.parse` accepts. Defaults to `true`.
|
||||
|
||||
##### type
|
||||
|
||||
The `type` option is used to determine what media type the middleware will
|
||||
parse. This option can be a string, array of strings, or a function. If not a
|
||||
function, `type` option is passed directly to the
|
||||
[type-is](https://www.npmjs.com/package/type-is#readme) library and this can
|
||||
be an extension name (like `json`), a mime type (like `application/json`), or
|
||||
a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type`
|
||||
option is called as `fn(req)` and the request is parsed if it returns a truthy
|
||||
value. Defaults to `application/json`.
|
||||
|
||||
##### verify
|
||||
|
||||
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
|
||||
where `buf` is a `Buffer` of the raw request body and `encoding` is the
|
||||
encoding of the request. The parsing can be aborted by throwing an error.
|
||||
|
||||
### bodyParser.raw([options])
|
||||
|
||||
Returns middleware that parses all bodies as a `Buffer` and only looks at
|
||||
requests where the `Content-Type` header matches the `type` option. This
|
||||
parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate`
|
||||
encodings.
|
||||
|
||||
A new `body` object containing the parsed data is populated on the `request`
|
||||
object after the middleware (i.e. `req.body`). This will be a `Buffer` object
|
||||
of the body.
|
||||
|
||||
#### Options
|
||||
|
||||
The `raw` function takes an optional `options` object that may contain any of
|
||||
the following keys:
|
||||
|
||||
##### inflate
|
||||
|
||||
When set to `true`, then deflated (compressed) bodies will be inflated; when
|
||||
`false`, deflated bodies are rejected. Defaults to `true`.
|
||||
|
||||
##### limit
|
||||
|
||||
Controls the maximum request body size. If this is a number, then the value
|
||||
specifies the number of bytes; if it is a string, the value is passed to the
|
||||
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
|
||||
to `'100kb'`.
|
||||
|
||||
> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur.
|
||||
|
||||
##### type
|
||||
|
||||
The `type` option is used to determine what media type the middleware will
|
||||
parse. This option can be a string, array of strings, or a function.
|
||||
If not a function, `type` option is passed directly to the
|
||||
[type-is](https://www.npmjs.com/package/type-is#readme) library and this
|
||||
can be an extension name (like `bin`), a mime type (like
|
||||
`application/octet-stream`), or a mime type with a wildcard (like `*/*` or
|
||||
`application/*`). If a function, the `type` option is called as `fn(req)`
|
||||
and the request is parsed if it returns a truthy value. Defaults to
|
||||
`application/octet-stream`.
|
||||
|
||||
##### verify
|
||||
|
||||
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
|
||||
where `buf` is a `Buffer` of the raw request body and `encoding` is the
|
||||
encoding of the request. The parsing can be aborted by throwing an error.
|
||||
|
||||
### bodyParser.text([options])
|
||||
|
||||
Returns middleware that parses all bodies as a string and only looks at
|
||||
requests where the `Content-Type` header matches the `type` option. This
|
||||
parser supports automatic inflation of `gzip`, `br` (brotli) and `deflate`
|
||||
encodings.
|
||||
|
||||
A new `body` string containing the parsed data is populated on the `request`
|
||||
object after the middleware (i.e. `req.body`). This will be a string of the
|
||||
body.
|
||||
|
||||
#### Options
|
||||
|
||||
The `text` function takes an optional `options` object that may contain any of
|
||||
the following keys:
|
||||
|
||||
##### defaultCharset
|
||||
|
||||
Specify the default character set for the text content if the charset is not
|
||||
specified in the `Content-Type` header of the request. Defaults to `utf-8`.
|
||||
|
||||
##### inflate
|
||||
|
||||
When set to `true`, then deflated (compressed) bodies will be inflated; when
|
||||
`false`, deflated bodies are rejected. Defaults to `true`.
|
||||
|
||||
##### limit
|
||||
|
||||
Controls the maximum request body size. If this is a number, then the value
|
||||
specifies the number of bytes; if it is a string, the value is passed to the
|
||||
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
|
||||
to `'100kb'`.
|
||||
|
||||
> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur.
|
||||
|
||||
##### type
|
||||
|
||||
The `type` option is used to determine what media type the middleware will
|
||||
parse. This option can be a string, array of strings, or a function. If not
|
||||
a function, `type` option is passed directly to the
|
||||
[type-is](https://www.npmjs.com/package/type-is#readme) library and this can
|
||||
be an extension name (like `txt`), a mime type (like `text/plain`), or a mime
|
||||
type with a wildcard (like `*/*` or `text/*`). If a function, the `type`
|
||||
option is called as `fn(req)` and the request is parsed if it returns a
|
||||
truthy value. Defaults to `text/plain`.
|
||||
|
||||
##### verify
|
||||
|
||||
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
|
||||
where `buf` is a `Buffer` of the raw request body and `encoding` is the
|
||||
encoding of the request. The parsing can be aborted by throwing an error.
|
||||
|
||||
### bodyParser.urlencoded([options])
|
||||
|
||||
Returns middleware that only parses `urlencoded` bodies and only looks at
|
||||
requests where the `Content-Type` header matches the `type` option. This
|
||||
parser accepts only UTF-8 and ISO-8859-1 encodings of the body and supports
|
||||
automatic inflation of `gzip`, `br` (brotli) and `deflate` encodings.
|
||||
|
||||
A new `body` object containing the parsed data is populated on the `request`
|
||||
object after the middleware (i.e. `req.body`). This object will contain
|
||||
key-value pairs, where the value can be a string or array (when `extended` is
|
||||
`false`), or any type (when `extended` is `true`).
|
||||
|
||||
#### Options
|
||||
|
||||
The `urlencoded` function takes an optional `options` object that may contain
|
||||
any of the following keys:
|
||||
|
||||
##### extended
|
||||
|
||||
The "extended" syntax allows for rich objects and arrays to be encoded into the
|
||||
URL-encoded format, allowing for a JSON-like experience with URL-encoded. For
|
||||
more information, please [see the qs
|
||||
library](https://www.npmjs.com/package/qs#readme).
|
||||
|
||||
Defaults to `false`.
|
||||
|
||||
##### inflate
|
||||
|
||||
When set to `true`, then deflated (compressed) bodies will be inflated; when
|
||||
`false`, deflated bodies are rejected. Defaults to `true`.
|
||||
|
||||
##### limit
|
||||
|
||||
Controls the maximum request body size. If this is a number, then the value
|
||||
specifies the number of bytes; if it is a string, the value is passed to the
|
||||
[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
|
||||
to `'100kb'`.
|
||||
|
||||
> It’s recommended not to configure a very high limit and to use the default value whenever possible. Allowing larger payloads increases memory usage because of the resources required for decoding and transformations, and it can also lead to longer response times as more data is processed. By ‘very high’, we mean values above the default, for example payloads of 5 MB or more can already start to introduce these risks. With the default limits, these issues do not occur.
|
||||
|
||||
##### parameterLimit
|
||||
|
||||
The `parameterLimit` option controls the maximum number of parameters that
|
||||
are allowed in the URL-encoded data. If a request contains more parameters
|
||||
than this value, a 413 will be returned to the client. Defaults to `1000`.
|
||||
|
||||
##### type
|
||||
|
||||
The `type` option is used to determine what media type the middleware will
|
||||
parse. This option can be a string, array of strings, or a function. If not
|
||||
a function, `type` option is passed directly to the
|
||||
[type-is](https://www.npmjs.com/package/type-is#readme) library and this can
|
||||
be an extension name (like `urlencoded`), a mime type (like
|
||||
`application/x-www-form-urlencoded`), or a mime type with a wildcard (like
|
||||
`*/x-www-form-urlencoded`). If a function, the `type` option is called as
|
||||
`fn(req)` and the request is parsed if it returns a truthy value. Defaults
|
||||
to `application/x-www-form-urlencoded`.
|
||||
|
||||
##### verify
|
||||
|
||||
The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
|
||||
where `buf` is a `Buffer` of the raw request body and `encoding` is the
|
||||
encoding of the request. The parsing can be aborted by throwing an error.
|
||||
|
||||
##### defaultCharset
|
||||
|
||||
The default charset to parse as, if not specified in content-type. Must be
|
||||
either `utf-8` or `iso-8859-1`. Defaults to `utf-8`.
|
||||
|
||||
##### charsetSentinel
|
||||
|
||||
Whether to let the value of the `utf8` parameter take precedence as the charset
|
||||
selector. It requires the form to contain a parameter named `utf8` with a value
|
||||
of `✓`. Defaults to `false`.
|
||||
|
||||
##### interpretNumericEntities
|
||||
|
||||
Whether to decode numeric entities such as `☺` when parsing an iso-8859-1
|
||||
form. Defaults to `false`.
|
||||
|
||||
|
||||
##### depth
|
||||
|
||||
The `depth` option is used to configure the maximum depth of the `qs` library when `extended` is `true`. This allows you to limit the amount of keys that are parsed and can be useful to prevent certain types of abuse. Defaults to `32`. It is recommended to keep this value as low as possible.
|
||||
|
||||
## Errors
|
||||
|
||||
The middlewares provided by this module create errors using the
|
||||
[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors
|
||||
will typically have a `status`/`statusCode` property that contains the suggested
|
||||
HTTP response code, an `expose` property to determine if the `message` property
|
||||
should be displayed to the client, a `type` property to determine the type of
|
||||
error without matching against the `message`, and a `body` property containing
|
||||
the read body, if available.
|
||||
|
||||
The following are the common errors created, though any error can come through
|
||||
for various reasons.
|
||||
|
||||
### content encoding unsupported
|
||||
|
||||
This error will occur when the request had a `Content-Encoding` header that
|
||||
contained an encoding but the "inflation" option was set to `false`. The
|
||||
`status` property is set to `415`, the `type` property is set to
|
||||
`'encoding.unsupported'`, and the `charset` property will be set to the
|
||||
encoding that is unsupported.
|
||||
|
||||
### entity parse failed
|
||||
|
||||
This error will occur when the request contained an entity that could not be
|
||||
parsed by the middleware. The `status` property is set to `400`, the `type`
|
||||
property is set to `'entity.parse.failed'`, and the `body` property is set to
|
||||
the entity value that failed parsing.
|
||||
|
||||
### entity verify failed
|
||||
|
||||
This error will occur when the request contained an entity that could not be
|
||||
failed verification by the defined `verify` option. The `status` property is
|
||||
set to `403`, the `type` property is set to `'entity.verify.failed'`, and the
|
||||
`body` property is set to the entity value that failed verification.
|
||||
|
||||
### request aborted
|
||||
|
||||
This error will occur when the request is aborted by the client before reading
|
||||
the body has finished. The `received` property will be set to the number of
|
||||
bytes received before the request was aborted and the `expected` property is
|
||||
set to the number of expected bytes. The `status` property is set to `400`
|
||||
and `type` property is set to `'request.aborted'`.
|
||||
|
||||
### request entity too large
|
||||
|
||||
This error will occur when the request body's size is larger than the "limit"
|
||||
option. The `limit` property will be set to the byte limit and the `length`
|
||||
property will be set to the request body's length. The `status` property is
|
||||
set to `413` and the `type` property is set to `'entity.too.large'`.
|
||||
|
||||
### request size did not match content length
|
||||
|
||||
This error will occur when the request's length did not match the length from
|
||||
the `Content-Length` header. This typically occurs when the request is malformed,
|
||||
typically when the `Content-Length` header was calculated based on characters
|
||||
instead of bytes. The `status` property is set to `400` and the `type` property
|
||||
is set to `'request.size.invalid'`.
|
||||
|
||||
### stream encoding should not be set
|
||||
|
||||
This error will occur when something called the `req.setEncoding` method prior
|
||||
to this middleware. This module operates directly on bytes only and you cannot
|
||||
call `req.setEncoding` when using this module. The `status` property is set to
|
||||
`500` and the `type` property is set to `'stream.encoding.set'`.
|
||||
|
||||
### stream is not readable
|
||||
|
||||
This error will occur when the request is no longer readable when this middleware
|
||||
attempts to read it. This typically means something other than a middleware from
|
||||
this module read the request body already and the middleware was also configured to
|
||||
read the same request. The `status` property is set to `500` and the `type`
|
||||
property is set to `'stream.not.readable'`.
|
||||
|
||||
### too many parameters
|
||||
|
||||
This error will occur when the content of the request exceeds the configured
|
||||
`parameterLimit` for the `urlencoded` parser. The `status` property is set to
|
||||
`413` and the `type` property is set to `'parameters.too.many'`.
|
||||
|
||||
### unsupported charset "BOGUS"
|
||||
|
||||
This error will occur when the request had a charset parameter in the
|
||||
`Content-Type` header, but the `iconv-lite` module does not support it OR the
|
||||
parser does not support it. The charset is contained in the message as well
|
||||
as in the `charset` property. The `status` property is set to `415`, the
|
||||
`type` property is set to `'charset.unsupported'`, and the `charset` property
|
||||
is set to the charset that is unsupported.
|
||||
|
||||
### unsupported content encoding "bogus"
|
||||
|
||||
This error will occur when the request had a `Content-Encoding` header that
|
||||
contained an unsupported encoding. The encoding is contained in the message
|
||||
as well as in the `encoding` property. The `status` property is set to `415`,
|
||||
the `type` property is set to `'encoding.unsupported'`, and the `encoding`
|
||||
property is set to the encoding that is unsupported.
|
||||
|
||||
### The input exceeded the depth
|
||||
|
||||
This error occurs when using `bodyParser.urlencoded` with the `extended` property set to `true` and the input exceeds the configured `depth` option. The `status` property is set to `400`. It is recommended to review the `depth` option and evaluate if it requires a higher value. When the `depth` option is set to `32` (default value), the error will not be thrown.
|
||||
|
||||
## Examples
|
||||
|
||||
### Express/Connect top-level generic
|
||||
|
||||
This example demonstrates adding a generic JSON and URL-encoded parser as a
|
||||
top-level middleware, which will parse the bodies of all incoming requests.
|
||||
This is the simplest setup.
|
||||
|
||||
```js
|
||||
const express = require('express')
|
||||
const bodyParser = require('body-parser')
|
||||
|
||||
const app = express()
|
||||
|
||||
// parse application/x-www-form-urlencoded
|
||||
app.use(bodyParser.urlencoded())
|
||||
|
||||
// parse application/json
|
||||
app.use(bodyParser.json())
|
||||
|
||||
app.use(function (req, res) {
|
||||
res.setHeader('Content-Type', 'text/plain')
|
||||
res.write('you posted:\n')
|
||||
res.end(String(JSON.stringify(req.body, null, 2)))
|
||||
})
|
||||
```
|
||||
|
||||
### Express route-specific
|
||||
|
||||
This example demonstrates adding body parsers specifically to the routes that
|
||||
need them. In general, this is the most recommended way to use body-parser with
|
||||
Express.
|
||||
|
||||
```js
|
||||
const express = require('express')
|
||||
const bodyParser = require('body-parser')
|
||||
|
||||
const app = express()
|
||||
|
||||
// create application/json parser
|
||||
const jsonParser = bodyParser.json()
|
||||
|
||||
// create application/x-www-form-urlencoded parser
|
||||
const urlencodedParser = bodyParser.urlencoded()
|
||||
|
||||
// POST /login gets urlencoded bodies
|
||||
app.post('/login', urlencodedParser, function (req, res) {
|
||||
if (!req.body || !req.body.username) res.sendStatus(400)
|
||||
res.send('welcome, ' + req.body.username)
|
||||
})
|
||||
|
||||
// POST /api/users gets JSON bodies
|
||||
app.post('/api/users', jsonParser, function (req, res) {
|
||||
if (!req.body) res.sendStatus(400)
|
||||
// create user in req.body
|
||||
})
|
||||
```
|
||||
|
||||
### Change accepted type for parsers
|
||||
|
||||
All the parsers accept a `type` option which allows you to change the
|
||||
`Content-Type` that the middleware will parse.
|
||||
|
||||
```js
|
||||
const express = require('express')
|
||||
const bodyParser = require('body-parser')
|
||||
|
||||
const app = express()
|
||||
|
||||
// parse various different custom JSON types as JSON
|
||||
app.use(bodyParser.json({ type: 'application/*+json' }))
|
||||
|
||||
// parse some custom thing into a Buffer
|
||||
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
|
||||
|
||||
// parse an HTML body into a string
|
||||
app.use(bodyParser.text({ type: 'text/html' }))
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[ci-image]: https://img.shields.io/github/actions/workflow/status/expressjs/body-parser/ci.yml?branch=master&label=ci
|
||||
[ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml
|
||||
[coveralls-image]: https://img.shields.io/coverallsCoverage/github/expressjs/body-parser?branch=master
|
||||
[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
|
||||
[npm-downloads-image]: https://img.shields.io/npm/dm/body-parser
|
||||
[npm-url]: https://npmjs.com/package/body-parser
|
||||
[npm-version-image]: https://img.shields.io/npm/v/body-parser
|
||||
[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/body-parser/badge
|
||||
[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/body-parser
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* @typedef {Object} Parsers
|
||||
* @property {Function} json JSON parser
|
||||
* @property {Function} raw Raw parser
|
||||
* @property {Function} text Text parser
|
||||
* @property {Function} urlencoded URL-encoded parser
|
||||
*/
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
* @type {Function & Parsers}
|
||||
*/
|
||||
exports = module.exports = bodyParser
|
||||
|
||||
/**
|
||||
* JSON parser.
|
||||
* @public
|
||||
*/
|
||||
exports.json = require('./lib/types/json')
|
||||
|
||||
/**
|
||||
* Raw parser.
|
||||
* @public
|
||||
*/
|
||||
exports.raw = require('./lib/types/raw')
|
||||
|
||||
/**
|
||||
* Text parser.
|
||||
* @public
|
||||
*/
|
||||
exports.text = require('./lib/types/text')
|
||||
|
||||
/**
|
||||
* URL-encoded parser.
|
||||
* @public
|
||||
*/
|
||||
exports.urlencoded = require('./lib/types/urlencoded')
|
||||
|
||||
/**
|
||||
* Create a middleware to parse json and urlencoded bodies.
|
||||
*
|
||||
* @deprecated
|
||||
* @public
|
||||
*/
|
||||
function bodyParser () {
|
||||
throw new Error('The bodyParser() generic has been split into individual middleware to use instead.')
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
const createError = require('http-errors')
|
||||
const getBody = require('raw-body')
|
||||
const iconv = require('iconv-lite')
|
||||
const onFinished = require('on-finished')
|
||||
const zlib = require('node:zlib')
|
||||
const hasBody = require('type-is').hasBody
|
||||
const { getCharset } = require('./utils')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = read
|
||||
|
||||
/**
|
||||
* Read a request into a buffer and parse.
|
||||
*
|
||||
* @param {Object} req
|
||||
* @param {Object} res
|
||||
* @param {Function} next
|
||||
* @param {Function} parse
|
||||
* @param {Function} debug
|
||||
* @param {Object} options
|
||||
* @private
|
||||
*/
|
||||
function read (req, res, next, parse, debug, options) {
|
||||
if (onFinished.isFinished(req)) {
|
||||
debug('body already parsed')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
if (!('body' in req)) {
|
||||
req.body = undefined
|
||||
}
|
||||
|
||||
// skip requests without bodies
|
||||
if (!hasBody(req)) {
|
||||
debug('skip empty body')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
debug('content-type %j', req.headers['content-type'])
|
||||
|
||||
// determine if request should be parsed
|
||||
if (!options.shouldParse(req)) {
|
||||
debug('skip parsing')
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
let encoding = null
|
||||
if (options?.skipCharset !== true) {
|
||||
encoding = getCharset(req) || options.defaultCharset
|
||||
|
||||
// validate charset
|
||||
if (!!options?.isValidCharset && !options.isValidCharset(encoding)) {
|
||||
debug('invalid charset')
|
||||
next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
|
||||
charset: encoding,
|
||||
type: 'charset.unsupported'
|
||||
}))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
let length
|
||||
const opts = options
|
||||
let stream
|
||||
|
||||
// read options
|
||||
const verify = opts.verify
|
||||
|
||||
try {
|
||||
// get the content stream
|
||||
stream = contentstream(req, debug, opts.inflate)
|
||||
length = stream.length
|
||||
stream.length = undefined
|
||||
} catch (err) {
|
||||
return next(err)
|
||||
}
|
||||
|
||||
// set raw-body options
|
||||
opts.length = length
|
||||
opts.encoding = verify
|
||||
? null
|
||||
: encoding
|
||||
|
||||
// assert charset is supported
|
||||
if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) {
|
||||
return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
|
||||
charset: encoding.toLowerCase(),
|
||||
type: 'charset.unsupported'
|
||||
}))
|
||||
}
|
||||
|
||||
// read body
|
||||
debug('read body')
|
||||
getBody(stream, opts, function (error, body) {
|
||||
if (error) {
|
||||
let _error
|
||||
|
||||
if (error.type === 'encoding.unsupported') {
|
||||
// echo back charset
|
||||
_error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
|
||||
charset: encoding.toLowerCase(),
|
||||
type: 'charset.unsupported'
|
||||
})
|
||||
} else {
|
||||
// set status code on error
|
||||
_error = createError(400, error)
|
||||
}
|
||||
|
||||
// unpipe from stream and destroy
|
||||
if (stream !== req) {
|
||||
req.unpipe()
|
||||
stream.destroy()
|
||||
}
|
||||
|
||||
// read off entire request
|
||||
dump(req, function onfinished () {
|
||||
next(createError(400, _error))
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// verify
|
||||
if (verify) {
|
||||
try {
|
||||
debug('verify body')
|
||||
verify(req, res, body, encoding)
|
||||
} catch (err) {
|
||||
next(createError(403, err, {
|
||||
body: body,
|
||||
type: err.type || 'entity.verify.failed'
|
||||
}))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// parse
|
||||
let str = body
|
||||
try {
|
||||
debug('parse body')
|
||||
str = typeof body !== 'string' && encoding !== null
|
||||
? iconv.decode(body, encoding)
|
||||
: body
|
||||
req.body = parse(str, encoding)
|
||||
} catch (err) {
|
||||
next(createError(400, err, {
|
||||
body: str,
|
||||
type: err.type || 'entity.parse.failed'
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
next()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the content stream of the request.
|
||||
*
|
||||
* @param {Object} req
|
||||
* @param {Function} debug
|
||||
* @param {boolean} inflate
|
||||
* @returns {Object}
|
||||
* @private
|
||||
*/
|
||||
function contentstream (req, debug, inflate) {
|
||||
const encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
|
||||
const length = req.headers['content-length']
|
||||
|
||||
debug('content-encoding "%s"', encoding)
|
||||
|
||||
if (inflate === false && encoding !== 'identity') {
|
||||
throw createError(415, 'content encoding unsupported', {
|
||||
encoding: encoding,
|
||||
type: 'encoding.unsupported'
|
||||
})
|
||||
}
|
||||
|
||||
if (encoding === 'identity') {
|
||||
req.length = length
|
||||
return req
|
||||
}
|
||||
|
||||
const stream = createDecompressionStream(encoding, debug)
|
||||
req.pipe(stream)
|
||||
return stream
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a decompression stream for the given encoding.
|
||||
* @param {string} encoding
|
||||
* @param {Function} debug
|
||||
* @returns {Object}
|
||||
* @private
|
||||
*/
|
||||
function createDecompressionStream (encoding, debug) {
|
||||
switch (encoding) {
|
||||
case 'deflate':
|
||||
debug('inflate body')
|
||||
return zlib.createInflate()
|
||||
case 'gzip':
|
||||
debug('gunzip body')
|
||||
return zlib.createGunzip()
|
||||
case 'br':
|
||||
debug('brotli decompress body')
|
||||
return zlib.createBrotliDecompress()
|
||||
default:
|
||||
throw createError(415, 'unsupported content encoding "' + encoding + '"', {
|
||||
encoding: encoding,
|
||||
type: 'encoding.unsupported'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dump the contents of a request.
|
||||
*
|
||||
* @param {Object} req
|
||||
* @param {Function} callback
|
||||
* @private
|
||||
*/
|
||||
function dump (req, callback) {
|
||||
if (onFinished.isFinished(req)) {
|
||||
callback(null)
|
||||
} else {
|
||||
onFinished(req, callback)
|
||||
req.resume()
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014 Jonathan Ong
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
const debug = require('debug')('body-parser:json')
|
||||
const read = require('../read')
|
||||
const { normalizeOptions } = require('../utils')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = json
|
||||
|
||||
/**
|
||||
* RegExp to match the first non-space in a string.
|
||||
*
|
||||
* Allowed whitespace is defined in RFC 7159:
|
||||
*
|
||||
* ws = *(
|
||||
* %x20 / ; Space
|
||||
* %x09 / ; Horizontal tab
|
||||
* %x0A / ; Line feed or New line
|
||||
* %x0D ) ; Carriage return
|
||||
*/
|
||||
const FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex
|
||||
|
||||
const JSON_SYNTAX_CHAR = '#'
|
||||
const JSON_SYNTAX_REGEXP = /#+/g
|
||||
|
||||
/**
|
||||
* Create a middleware to parse JSON bodies.
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @returns {Function}
|
||||
* @public
|
||||
*/
|
||||
function json (options) {
|
||||
const normalizedOptions = normalizeOptions(options, 'application/json')
|
||||
|
||||
const parse = createJsonParser(options)
|
||||
|
||||
const readOptions = {
|
||||
...normalizedOptions,
|
||||
// assert charset per RFC 7159 sec 8.1
|
||||
isValidCharset: (charset) => charset.slice(0, 4) === 'utf-'
|
||||
}
|
||||
|
||||
return function jsonParser (req, res, next) {
|
||||
read(req, res, next, parse, debug, readOptions)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a JSON parse function
|
||||
*
|
||||
* @param {object} [options]
|
||||
* @return {function}
|
||||
* @private
|
||||
*/
|
||||
function createJsonParser (options) {
|
||||
const reviver = options?.reviver
|
||||
const strict = options?.strict !== false
|
||||
|
||||
if (strict) {
|
||||
return function parse (body) {
|
||||
if (body.length === 0) {
|
||||
// special-case empty json body, as it's a common client-side mistake
|
||||
// TODO: maybe make this configurable or part of "strict" option
|
||||
return {}
|
||||
}
|
||||
|
||||
const first = firstchar(body)
|
||||
if (first !== '{' && first !== '[') {
|
||||
debug('strict violation')
|
||||
throw createStrictSyntaxError(body, first)
|
||||
}
|
||||
|
||||
try {
|
||||
debug('parse json')
|
||||
return JSON.parse(body, reviver)
|
||||
} catch (e) {
|
||||
throw normalizeJsonSyntaxError(e, {
|
||||
message: e.message,
|
||||
stack: e.stack
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return function parse (body) {
|
||||
if (body.length === 0) {
|
||||
// special-case empty json body, as it's a common client-side mistake
|
||||
// TODO: maybe make this configurable or part of "strict" option
|
||||
return {}
|
||||
}
|
||||
|
||||
try {
|
||||
debug('parse json')
|
||||
return JSON.parse(body, reviver)
|
||||
} catch (e) {
|
||||
throw normalizeJsonSyntaxError(e, {
|
||||
message: e.message,
|
||||
stack: e.stack
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create strict violation syntax error matching native error.
|
||||
*
|
||||
* @param {string} str
|
||||
* @param {string} char
|
||||
* @returns {Error}
|
||||
* @private
|
||||
*/
|
||||
function createStrictSyntaxError (str, char) {
|
||||
const index = str.indexOf(char)
|
||||
let partial = ''
|
||||
|
||||
if (index !== -1) {
|
||||
partial = str.substring(0, index) + JSON_SYNTAX_CHAR.repeat(str.length - index)
|
||||
}
|
||||
|
||||
try {
|
||||
JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation')
|
||||
} catch (e) {
|
||||
return normalizeJsonSyntaxError(e, {
|
||||
message: e.message.replace(JSON_SYNTAX_REGEXP, function (placeholder) {
|
||||
return str.substring(index, index + placeholder.length)
|
||||
}),
|
||||
stack: e.stack
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first non-whitespace character in a string.
|
||||
*
|
||||
* @param {string} str
|
||||
* @returns {string|undefined}
|
||||
* @private
|
||||
*/
|
||||
function firstchar (str) {
|
||||
const match = FIRST_CHAR_REGEXP.exec(str)
|
||||
|
||||
return match
|
||||
? match[1]
|
||||
: undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a SyntaxError for JSON.parse.
|
||||
*
|
||||
* @param {SyntaxError} error
|
||||
* @param {Object} obj
|
||||
* @returns {SyntaxError}
|
||||
* @private
|
||||
*/
|
||||
function normalizeJsonSyntaxError (error, obj) {
|
||||
const keys = Object.getOwnPropertyNames(error)
|
||||
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i]
|
||||
if (key !== 'stack' && key !== 'message') {
|
||||
delete error[key]
|
||||
}
|
||||
}
|
||||
|
||||
// replace stack before message for Node.js 0.10 and below
|
||||
error.stack = obj.stack.replace(error.message, obj.message)
|
||||
error.message = obj.message
|
||||
|
||||
return error
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
const debug = require('debug')('body-parser:raw')
|
||||
const read = require('../read')
|
||||
const { normalizeOptions, passthrough } = require('../utils')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = raw
|
||||
|
||||
/**
|
||||
* Create a middleware to parse raw bodies.
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @returns {Function}
|
||||
* @public
|
||||
*/
|
||||
function raw (options) {
|
||||
const normalizedOptions = normalizeOptions(options, 'application/octet-stream')
|
||||
|
||||
const readOptions = {
|
||||
...normalizedOptions,
|
||||
// Skip charset validation and parse the body as is
|
||||
skipCharset: true
|
||||
}
|
||||
|
||||
return function rawParser (req, res, next) {
|
||||
read(req, res, next, passthrough, debug, readOptions)
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
const debug = require('debug')('body-parser:text')
|
||||
const read = require('../read')
|
||||
const { normalizeOptions, passthrough } = require('../utils')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = text
|
||||
|
||||
/**
|
||||
* Create a middleware to parse text bodies.
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @returns {Function}
|
||||
* @public
|
||||
*/
|
||||
function text (options) {
|
||||
const normalizedOptions = normalizeOptions(options, 'text/plain')
|
||||
|
||||
return function textParser (req, res, next) {
|
||||
read(req, res, next, passthrough, debug, normalizedOptions)
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
/*!
|
||||
* body-parser
|
||||
* Copyright(c) 2014 Jonathan Ong
|
||||
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
* @private
|
||||
*/
|
||||
|
||||
const createError = require('http-errors')
|
||||
const debug = require('debug')('body-parser:urlencoded')
|
||||
const read = require('../read')
|
||||
const qs = require('qs')
|
||||
const { normalizeOptions } = require('../utils')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
|
||||
module.exports = urlencoded
|
||||
|
||||
/**
|
||||
* Create a middleware to parse urlencoded bodies.
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @returns {Function}
|
||||
* @public
|
||||
*/
|
||||
function urlencoded (options) {
|
||||
const normalizedOptions = normalizeOptions(options, 'application/x-www-form-urlencoded')
|
||||
|
||||
if (normalizedOptions.defaultCharset !== 'utf-8' && normalizedOptions.defaultCharset !== 'iso-8859-1') {
|
||||
throw new TypeError('option defaultCharset must be either utf-8 or iso-8859-1')
|
||||
}
|
||||
|
||||
// create the appropriate query parser
|
||||
const parse = createQueryParser(options)
|
||||
|
||||
const readOptions = {
|
||||
...normalizedOptions,
|
||||
// assert charset
|
||||
isValidCharset: (charset) => charset === 'utf-8' || charset === 'iso-8859-1'
|
||||
}
|
||||
|
||||
return function urlencodedParser (req, res, next) {
|
||||
read(req, res, next, parse, debug, readOptions)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the extended query parser.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @returns {Function}
|
||||
* @private
|
||||
*/
|
||||
function createQueryParser (options) {
|
||||
const extended = Boolean(options?.extended)
|
||||
let parameterLimit = options?.parameterLimit !== undefined
|
||||
? options?.parameterLimit
|
||||
: 1000
|
||||
const charsetSentinel = options?.charsetSentinel
|
||||
const interpretNumericEntities = options?.interpretNumericEntities
|
||||
const depth = extended ? (options?.depth !== undefined ? options?.depth : 32) : 0
|
||||
|
||||
if (isNaN(parameterLimit) || parameterLimit < 1) {
|
||||
throw new TypeError('option parameterLimit must be a positive number')
|
||||
}
|
||||
|
||||
if (isNaN(depth) || depth < 0) {
|
||||
throw new TypeError('option depth must be a zero or a positive number')
|
||||
}
|
||||
|
||||
if (isFinite(parameterLimit)) {
|
||||
parameterLimit = parameterLimit | 0
|
||||
}
|
||||
|
||||
return function parse (body, encoding) {
|
||||
if (!body.length) return {}
|
||||
|
||||
const paramCount = parameterCount(body, parameterLimit)
|
||||
|
||||
if (paramCount === undefined) {
|
||||
debug('too many parameters')
|
||||
throw createError(413, 'too many parameters', {
|
||||
type: 'parameters.too.many'
|
||||
})
|
||||
}
|
||||
|
||||
const arrayLimit = extended ? Math.max(100, paramCount) : paramCount
|
||||
|
||||
debug('parse ' + (extended ? 'extended ' : '') + 'urlencoding')
|
||||
try {
|
||||
return qs.parse(body, {
|
||||
allowPrototypes: true,
|
||||
arrayLimit: arrayLimit,
|
||||
depth: depth,
|
||||
charsetSentinel: charsetSentinel,
|
||||
interpretNumericEntities: interpretNumericEntities,
|
||||
charset: encoding,
|
||||
parameterLimit: parameterLimit,
|
||||
strictDepth: true
|
||||
})
|
||||
} catch (err) {
|
||||
if (err instanceof RangeError) {
|
||||
throw createError(400, 'The input exceeded the depth', {
|
||||
type: 'querystring.parse.rangeError'
|
||||
})
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the number of parameters, stopping once limit reached
|
||||
*
|
||||
* @param {string} body
|
||||
* @param {number} limit
|
||||
* @returns {number|undefined} Returns undefined if limit exceeded
|
||||
* @private
|
||||
*/
|
||||
function parameterCount (body, limit) {
|
||||
let count = 0
|
||||
let index = -1
|
||||
do {
|
||||
count++
|
||||
if (count > limit) return undefined // Early exit if limit exceeded
|
||||
index = body.indexOf('&', index + 1)
|
||||
} while (index !== -1)
|
||||
return count
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
'use strict'
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
const bytes = require('bytes')
|
||||
const contentType = require('content-type')
|
||||
const typeis = require('type-is')
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
*/
|
||||
module.exports = {
|
||||
getCharset,
|
||||
normalizeOptions,
|
||||
passthrough
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the charset of a request.
|
||||
*
|
||||
* @param {Object} req
|
||||
* @returns {string | undefined}
|
||||
* @private
|
||||
*/
|
||||
function getCharset (req) {
|
||||
const header = req.headers['content-type']
|
||||
if (!header) return undefined
|
||||
return contentType.parse(header).parameters.charset?.toLowerCase()
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the simple type checker.
|
||||
*
|
||||
* @param {string | string[]} type
|
||||
* @returns {Function}
|
||||
* @private
|
||||
*/
|
||||
function typeChecker (type) {
|
||||
return function checkType (req) {
|
||||
return Boolean(typeis(req, type))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes the common options for all parsers.
|
||||
*
|
||||
* @param {Object} options options to normalize
|
||||
* @param {string | string[] | Function} defaultType default content type(s) or a function to determine it
|
||||
* @returns {Object}
|
||||
* @private
|
||||
*/
|
||||
function normalizeOptions (options, defaultType) {
|
||||
if (!defaultType) {
|
||||
// Parsers must define a default content type
|
||||
throw new TypeError('defaultType must be provided')
|
||||
}
|
||||
|
||||
const inflate = options?.inflate !== false
|
||||
const limit = typeof options?.limit === 'undefined' || options?.limit === null
|
||||
? 102400 // 100kb default
|
||||
: bytes.parse(options.limit)
|
||||
const type = options?.type || defaultType
|
||||
const verify = options?.verify || false
|
||||
const defaultCharset = options?.defaultCharset || 'utf-8'
|
||||
|
||||
if (limit === null) {
|
||||
throw new TypeError(`option limit "${String(options.limit)}" is invalid`)
|
||||
}
|
||||
|
||||
if (verify !== false && typeof verify !== 'function') {
|
||||
throw new TypeError('option verify must be function')
|
||||
}
|
||||
|
||||
// create the appropriate type checking function
|
||||
const shouldParse = typeof type !== 'function'
|
||||
? typeChecker(type)
|
||||
: type
|
||||
|
||||
return {
|
||||
inflate,
|
||||
limit,
|
||||
verify,
|
||||
defaultCharset,
|
||||
shouldParse
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Passthrough function that returns input unchanged.
|
||||
* Used by parsers that don't need to transform the data.
|
||||
*
|
||||
* @param {*} value
|
||||
* @returns {*}
|
||||
* @private
|
||||
*/
|
||||
function passthrough (value) {
|
||||
return value
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2015 Douglas Christopher Wilson
|
||||
|
||||
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.
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
# content-type
|
||||
|
||||
[![NPM version][npm-image]][npm-url]
|
||||
[![NPM downloads][downloads-image]][downloads-url]
|
||||
[![Build status][build-image]][build-url]
|
||||
[![Build coverage][coverage-image]][coverage-url]
|
||||
[![License][license-image]][license-url]
|
||||
|
||||
Create and parse HTTP `Content-Type` header.
|
||||
|
||||
## Installation
|
||||
|
||||
```sh
|
||||
npm install content-type
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
```js
|
||||
const contentType = require("content-type");
|
||||
```
|
||||
|
||||
### contentType.parse(string, options?)
|
||||
|
||||
```js
|
||||
const obj = contentType.parse("image/svg+xml; charset=utf-8");
|
||||
```
|
||||
|
||||
Parse a `Content-Type` header. This will return an object with the following properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`):
|
||||
|
||||
- `type`: The media type. Example: `'image/svg+xml'`.
|
||||
- `parameters`: An object of the parameters in the media type (parameter name is always lower case). Example: `{charset: 'utf-8'}`.
|
||||
|
||||
The parser is lenient and does not error. You should validate `type` and `parameters` before trusting them.
|
||||
|
||||
#### Options
|
||||
|
||||
- `parameters` (default: `true`): Set to `false` to skip parameters.
|
||||
- `comma` (default: `false`): Set to `true` to stop on a comma. This can be used to parse the media range in an `Accept` header.
|
||||
- `start` (default: `0`): Set index to start parsing from.
|
||||
|
||||
### contentType.format(obj)
|
||||
|
||||
```js
|
||||
const str = contentType.format({
|
||||
type: "image/svg+xml",
|
||||
parameters: { charset: "utf-8" },
|
||||
});
|
||||
```
|
||||
|
||||
Format an object into a `Content-Type` header. This will return a string of the content type for the given object with the following properties (examples are shown that produce the string `'image/svg+xml; charset=utf-8'`):
|
||||
|
||||
- `type`: The media type. Example: `'image/svg+xml'`.
|
||||
- `parameters`: An optional object of the parameters in the media type. Example: `{charset: 'utf-8'}`.
|
||||
|
||||
Throws a `TypeError` if the object contains an invalid type or parameter names.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[npm-image]: https://img.shields.io/npm/v/content-type
|
||||
[npm-url]: https://npmjs.org/package/content-type
|
||||
[downloads-image]: https://img.shields.io/npm/dm/content-type
|
||||
[downloads-url]: https://npmjs.org/package/content-type
|
||||
[build-image]: https://img.shields.io/github/actions/workflow/status/jshttp/content-type/ci.yml?branch=master
|
||||
[build-url]: https://github.com/jshttp/content-type/actions/workflows/ci.yml?query=branch%3Amaster
|
||||
[coverage-image]: https://img.shields.io/codecov/c/gh/jshttp/content-type
|
||||
[coverage-url]: https://codecov.io/gh/jshttp/content-type
|
||||
[license-image]: http://img.shields.io/npm/l/content-type.svg?style=flat
|
||||
[license-url]: LICENSE
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/*!
|
||||
* content-type
|
||||
* Copyright(c) 2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
/**
|
||||
* The content type object contains a type string and optional parameters.
|
||||
*/
|
||||
export interface ContentType {
|
||||
type: string;
|
||||
index: number;
|
||||
parameters: Record<string, string>;
|
||||
}
|
||||
/**
|
||||
* Format an object into a `Content-Type` header.
|
||||
*/
|
||||
export declare function format(obj: Partial<ContentType>): string;
|
||||
/**
|
||||
* Options for parsing a `Content-Type` header.
|
||||
*/
|
||||
export interface ParseOptions {
|
||||
/**
|
||||
* Exit early on the first semicolon, returning only the type.
|
||||
* This is useful for parsing the MIME from `Content-Type` headers.
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
parameters?: boolean;
|
||||
/**
|
||||
* Exits early on a comma, returning the first value and parameters.
|
||||
* This is useful for parsing `Accept` headers.
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
comma?: boolean;
|
||||
/**
|
||||
* The index to start parsing from.
|
||||
*
|
||||
* @default 0
|
||||
*/
|
||||
start?: number;
|
||||
}
|
||||
/**
|
||||
* Parse a `Content-Type` header.
|
||||
*/
|
||||
export declare function parse(header: string, options?: ParseOptions): ContentType;
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
"use strict";
|
||||
/*!
|
||||
* content-type
|
||||
* Copyright(c) 2015 Douglas Christopher Wilson
|
||||
* MIT Licensed
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.format = format;
|
||||
exports.parse = parse;
|
||||
const TEXT_REGEXP = /^[\u0009\u0020-\u007e\u0080-\u00ff]*$/;
|
||||
const TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
||||
/**
|
||||
* RegExp to match chars that must be quoted-pair in RFC 9110 sec 5.6.4
|
||||
*/
|
||||
const QUOTE_REGEXP = /[\\"]/g;
|
||||
/**
|
||||
* RegExp to match type in RFC 9110 sec 8.3.1
|
||||
*
|
||||
* media-type = type "/" subtype
|
||||
* type = token
|
||||
* subtype = token
|
||||
*/
|
||||
const TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
||||
/**
|
||||
* Null object perf optimization. Faster than `Object.create(null)` and `{ __proto__: null }`.
|
||||
*/
|
||||
const NullObject = /* @__PURE__ */ (() => {
|
||||
const C = function () { };
|
||||
C.prototype = Object.create(null);
|
||||
return C;
|
||||
})();
|
||||
/**
|
||||
* Format an object into a `Content-Type` header.
|
||||
*/
|
||||
function format(obj) {
|
||||
const { type, parameters } = obj;
|
||||
if (!type || !TYPE_REGEXP.test(type)) {
|
||||
throw new TypeError(`Invalid type: ${type}`);
|
||||
}
|
||||
let result = type;
|
||||
if (parameters) {
|
||||
for (const param of Object.keys(parameters)) {
|
||||
if (!TOKEN_REGEXP.test(param)) {
|
||||
throw new TypeError(`Invalid parameter name: ${param}`);
|
||||
}
|
||||
result += `; ${param}=${qstring(parameters[param])}`;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Parse a `Content-Type` header.
|
||||
*/
|
||||
function parse(header, options) {
|
||||
const stopChar = options?.comma === true ? COMMA : 65536; // Sentinel for "no stop char".
|
||||
const len = header.length;
|
||||
let index = skipOWS(header, options?.start ?? 0, len);
|
||||
const valueStart = index;
|
||||
index = skipValue(header, index, len, stopChar);
|
||||
const valueEnd = trailingOWS(header, valueStart, index);
|
||||
const type = header.slice(valueStart, valueEnd).toLowerCase();
|
||||
if (options?.parameters === false) {
|
||||
return { type, index, parameters: new NullObject() };
|
||||
}
|
||||
return parseParameters(header, type, index, len, stopChar);
|
||||
}
|
||||
const SP = 32; // " "
|
||||
const HTAB = 9; // "\t"
|
||||
const SEMI = 59; // ";"
|
||||
const EQ = 61; // "="
|
||||
const DQUOTE = 34; // '"'
|
||||
const BSLASH = 92; // "\\"
|
||||
const COMMA = 44; // ","
|
||||
/**
|
||||
* Parses the parameters of a `Content-Type` header starting at the given index.
|
||||
*/
|
||||
function parseParameters(header, type, index, len, stopChar) {
|
||||
const parameters = new NullObject();
|
||||
parameter: while (index < len) {
|
||||
if (header.charCodeAt(index) === stopChar)
|
||||
break;
|
||||
index = skipOWS(header, index + 1 /* Skip over ; */, len);
|
||||
const keyStart = index;
|
||||
while (index < len) {
|
||||
const code = header.charCodeAt(index);
|
||||
if (code === stopChar)
|
||||
break parameter;
|
||||
if (code === SEMI)
|
||||
continue parameter;
|
||||
if (code === EQ) {
|
||||
const keyEnd = trailingOWS(header, keyStart, index);
|
||||
const key = header.slice(keyStart, keyEnd).toLowerCase();
|
||||
index = skipOWS(header, index + 1, len);
|
||||
if (index < len && header.charCodeAt(index) === DQUOTE) {
|
||||
index++;
|
||||
let value = "";
|
||||
while (index < len) {
|
||||
const code = header.charCodeAt(index++);
|
||||
if (code === DQUOTE) {
|
||||
index = skipValue(header, index, len, stopChar);
|
||||
if (parameters[key] === undefined)
|
||||
parameters[key] = value;
|
||||
break;
|
||||
}
|
||||
if (code === BSLASH && index < len) {
|
||||
value += header[index++];
|
||||
continue;
|
||||
}
|
||||
value += String.fromCharCode(code);
|
||||
}
|
||||
continue parameter;
|
||||
}
|
||||
const valueStart = index;
|
||||
index = skipValue(header, index, len, stopChar);
|
||||
if (parameters[key] === undefined) {
|
||||
const valueEnd = trailingOWS(header, valueStart, index);
|
||||
parameters[key] = header.slice(valueStart, valueEnd);
|
||||
}
|
||||
continue parameter;
|
||||
}
|
||||
index++;
|
||||
}
|
||||
}
|
||||
return { type, index, parameters };
|
||||
}
|
||||
/**
|
||||
* Skip over characters until a semicolon or other exit character.
|
||||
*/
|
||||
function skipValue(str, index, len, stopChar) {
|
||||
while (index < len) {
|
||||
const code = str.charCodeAt(index);
|
||||
if (code === SEMI || code === stopChar)
|
||||
break;
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
/**
|
||||
* Skip optional whitespace (OWS) in an HTTP header value.
|
||||
*
|
||||
* OWS is defined in RFC 9110 sec 5.6.3 as SP (" ") or HTAB ("\t").
|
||||
*/
|
||||
function skipOWS(header, index, len) {
|
||||
while (index < len) {
|
||||
const char = header.charCodeAt(index);
|
||||
if (char !== SP && char !== HTAB)
|
||||
break;
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
/**
|
||||
* Trim optional whitespace (OWS) from the end of a substring.
|
||||
*
|
||||
* OWS is defined in RFC 9110 sec 5.6.3 as SP (" ") or HTAB ("\t").
|
||||
*/
|
||||
function trailingOWS(header, start, end) {
|
||||
while (end > start) {
|
||||
const char = header.charCodeAt(end - 1);
|
||||
if (char !== SP && char !== HTAB)
|
||||
break;
|
||||
end--;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
/**
|
||||
* Serialize a parameter value.
|
||||
*/
|
||||
function qstring(str) {
|
||||
if (TOKEN_REGEXP.test(str))
|
||||
return str;
|
||||
if (TEXT_REGEXP.test(str))
|
||||
return `"${str.replace(QUOTE_REGEXP, "\\$&")}"`;
|
||||
throw new TypeError(`Invalid parameter value: ${str}`);
|
||||
}
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+52
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "content-type",
|
||||
"version": "2.1.0",
|
||||
"description": "Create and parse HTTP Content-Type header",
|
||||
"keywords": [
|
||||
"content-type",
|
||||
"http",
|
||||
"req",
|
||||
"res",
|
||||
"rfc7231",
|
||||
"rfc9110"
|
||||
],
|
||||
"repository": "jshttp/content-type",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Douglas Christopher Wilson <doug@somethingdoug.com>",
|
||||
"type": "commonjs",
|
||||
"exports": "./dist/index.js",
|
||||
"main": "./dist/index.js",
|
||||
"typings": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist/"
|
||||
],
|
||||
"scripts": {
|
||||
"bench": "vitest bench",
|
||||
"build": "ts-scripts build",
|
||||
"format": "ts-scripts format",
|
||||
"prepare": "ts-scripts install && npm run build",
|
||||
"specs": "ts-scripts specs",
|
||||
"test": "ts-scripts test"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@borderless/ts-scripts": "^0.15.0",
|
||||
"@vitest/coverage-v8": "^3.0.5",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^3.2.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"ts-scripts": {
|
||||
"dist": [
|
||||
"dist"
|
||||
],
|
||||
"project": [
|
||||
"tsconfig.build.json"
|
||||
]
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"name": "body-parser",
|
||||
"description": "Node.js body parsing middleware",
|
||||
"version": "2.3.0",
|
||||
"contributors": [
|
||||
"Douglas Christopher Wilson <doug@somethingdoug.com>",
|
||||
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": "expressjs/body-parser",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
},
|
||||
"type": "commonjs",
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./package.json": "./package.json",
|
||||
"./json": "./lib/types/json.js",
|
||||
"./raw": "./lib/types/raw.js",
|
||||
"./text": "./lib/types/text.js",
|
||||
"./urlencoded": "./lib/types/urlencoded.js",
|
||||
"./lib/*": "./lib/*.js",
|
||||
"./lib/*.js": "./lib/*.js",
|
||||
"./lib/types/*": "./lib/types/*.js",
|
||||
"./lib/types/*.js": "./lib/types/*.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"bytes": "^3.1.2",
|
||||
"content-type": "^2.0.0",
|
||||
"debug": "^4.4.3",
|
||||
"http-errors": "^2.0.1",
|
||||
"iconv-lite": "^0.7.2",
|
||||
"on-finished": "^2.4.1",
|
||||
"qs": "^6.15.2",
|
||||
"raw-body": "^3.0.2",
|
||||
"type-is": "^2.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-config-standard": "^14.1.1",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-markdown": "^3.0.1",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-promise": "^6.6.0",
|
||||
"eslint-plugin-standard": "^4.1.0",
|
||||
"mocha": "^11.7.6",
|
||||
"nyc": "^17.1.0",
|
||||
"supertest": "^7.2.2"
|
||||
},
|
||||
"files": [
|
||||
"lib/",
|
||||
"LICENSE",
|
||||
"index.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"test": "mocha --reporter spec --check-leaks test/",
|
||||
"test-ci": "nyc --reporter=lcovonly --reporter=text npm test",
|
||||
"test-cov": "nyc --reporter=html --reporter=text npm test"
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
#boolbase
|
||||
This very simple module provides two basic functions, one that always returns true (`trueFunc`) and one that always returns false (`falseFunc`).
|
||||
|
||||
###WTF?
|
||||
|
||||
By having only a single instance of these functions around, it's possible to do some nice optimizations. Eg. [`CSSselect`](https://github.com/fb55/CSSselect) uses these functions to determine whether a selector won't match any elements. If that's the case, the DOM doesn't even have to be touched.
|
||||
|
||||
###And why is this a separate module?
|
||||
|
||||
I'm trying to modularize `CSSselect` and most modules depend on these functions. IMHO, having a separate module is the easiest solution to this problem.
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
module.exports = {
|
||||
trueFunc: function trueFunc(){
|
||||
return true;
|
||||
},
|
||||
falseFunc: function falseFunc(){
|
||||
return false;
|
||||
}
|
||||
};
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "boolbase",
|
||||
"version": "1.0.0",
|
||||
"description": "two functions: One that returns true, one that returns false",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/fb55/boolbase"
|
||||
},
|
||||
"keywords": [
|
||||
"boolean",
|
||||
"function"
|
||||
],
|
||||
"author": "Felix Boehm <me@feedic.com>",
|
||||
"license": "ISC",
|
||||
"bugs": {
|
||||
"url": "https://github.com/fb55/boolbase/issues"
|
||||
},
|
||||
"homepage": "https://github.com/fb55/boolbase"
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
3.1.2 / 2022-01-27
|
||||
==================
|
||||
|
||||
* Fix return value for un-parsable strings
|
||||
|
||||
3.1.1 / 2021-11-15
|
||||
==================
|
||||
|
||||
* Fix "thousandsSeparator" incorrecting formatting fractional part
|
||||
|
||||
3.1.0 / 2019-01-22
|
||||
==================
|
||||
|
||||
* Add petabyte (`pb`) support
|
||||
|
||||
3.0.0 / 2017-08-31
|
||||
==================
|
||||
|
||||
* Change "kB" to "KB" in format output
|
||||
* Remove support for Node.js 0.6
|
||||
* Remove support for ComponentJS
|
||||
|
||||
2.5.0 / 2017-03-24
|
||||
==================
|
||||
|
||||
* Add option "unit"
|
||||
|
||||
2.4.0 / 2016-06-01
|
||||
==================
|
||||
|
||||
* Add option "unitSeparator"
|
||||
|
||||
2.3.0 / 2016-02-15
|
||||
==================
|
||||
|
||||
* Drop partial bytes on all parsed units
|
||||
* Fix non-finite numbers to `.format` to return `null`
|
||||
* Fix parsing byte string that looks like hex
|
||||
* perf: hoist regular expressions
|
||||
|
||||
2.2.0 / 2015-11-13
|
||||
==================
|
||||
|
||||
* add option "decimalPlaces"
|
||||
* add option "fixedDecimals"
|
||||
|
||||
2.1.0 / 2015-05-21
|
||||
==================
|
||||
|
||||
* add `.format` export
|
||||
* add `.parse` export
|
||||
|
||||
2.0.2 / 2015-05-20
|
||||
==================
|
||||
|
||||
* remove map recreation
|
||||
* remove unnecessary object construction
|
||||
|
||||
2.0.1 / 2015-05-07
|
||||
==================
|
||||
|
||||
* fix browserify require
|
||||
* remove node.extend dependency
|
||||
|
||||
2.0.0 / 2015-04-12
|
||||
==================
|
||||
|
||||
* add option "case"
|
||||
* add option "thousandsSeparator"
|
||||
* return "null" on invalid parse input
|
||||
* support proper round-trip: bytes(bytes(num)) === num
|
||||
* units no longer case sensitive when parsing
|
||||
|
||||
1.0.0 / 2014-05-05
|
||||
==================
|
||||
|
||||
* add negative support. fixes #6
|
||||
|
||||
0.3.0 / 2014-03-19
|
||||
==================
|
||||
|
||||
* added terabyte support
|
||||
|
||||
0.2.1 / 2013-04-01
|
||||
==================
|
||||
|
||||
* add .component
|
||||
|
||||
0.2.0 / 2012-10-28
|
||||
==================
|
||||
|
||||
* bytes(200).should.eql('200b')
|
||||
|
||||
0.1.0 / 2012-07-04
|
||||
==================
|
||||
|
||||
* add bytes to string conversion [yields]
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2012-2014 TJ Holowaychuk <tj@vision-media.ca>
|
||||
Copyright (c) 2015 Jed Watson <jed.watson@me.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.
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
# Bytes utility
|
||||
|
||||
[![NPM Version][npm-image]][npm-url]
|
||||
[![NPM Downloads][downloads-image]][downloads-url]
|
||||
[![Build Status][ci-image]][ci-url]
|
||||
[![Test Coverage][coveralls-image]][coveralls-url]
|
||||
|
||||
Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa.
|
||||
|
||||
## Installation
|
||||
|
||||
This is a [Node.js](https://nodejs.org/en/) module available through the
|
||||
[npm registry](https://www.npmjs.com/). Installation is done using the
|
||||
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
|
||||
|
||||
```bash
|
||||
$ npm install bytes
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
var bytes = require('bytes');
|
||||
```
|
||||
|
||||
#### bytes(number|string value, [options]): number|string|null
|
||||
|
||||
Default export function. Delegates to either `bytes.format` or `bytes.parse` based on the type of `value`.
|
||||
|
||||
**Arguments**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|----------|--------------------|
|
||||
| value | `number`|`string` | Number value to format or string value to parse |
|
||||
| options | `Object` | Conversion options for `format` |
|
||||
|
||||
**Returns**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|------------------|-------------------------------------------------|
|
||||
| results | `string`|`number`|`null` | Return null upon error. Numeric value in bytes, or string value otherwise. |
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
bytes(1024);
|
||||
// output: '1KB'
|
||||
|
||||
bytes('1KB');
|
||||
// output: 1024
|
||||
```
|
||||
|
||||
#### bytes.format(number value, [options]): string|null
|
||||
|
||||
Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is
|
||||
rounded.
|
||||
|
||||
**Arguments**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|----------|--------------------|
|
||||
| value | `number` | Value in bytes |
|
||||
| options | `Object` | Conversion options |
|
||||
|
||||
**Options**
|
||||
|
||||
| Property | Type | Description |
|
||||
|-------------------|--------|-----------------------------------------------------------------------------------------|
|
||||
| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. |
|
||||
| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` |
|
||||
| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `'.'`... Default value to `''`. |
|
||||
| unit | `string`|`null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). |
|
||||
| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. |
|
||||
|
||||
**Returns**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|------------------|-------------------------------------------------|
|
||||
| results | `string`|`null` | Return null upon error. String value otherwise. |
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
bytes.format(1024);
|
||||
// output: '1KB'
|
||||
|
||||
bytes.format(1000);
|
||||
// output: '1000B'
|
||||
|
||||
bytes.format(1000, {thousandsSeparator: ' '});
|
||||
// output: '1 000B'
|
||||
|
||||
bytes.format(1024 * 1.7, {decimalPlaces: 0});
|
||||
// output: '2KB'
|
||||
|
||||
bytes.format(1024, {unitSeparator: ' '});
|
||||
// output: '1 KB'
|
||||
```
|
||||
|
||||
#### bytes.parse(string|number value): number|null
|
||||
|
||||
Parse the string value into an integer in bytes. If no unit is given, or `value`
|
||||
is a number, it is assumed the value is in bytes.
|
||||
|
||||
Supported units and abbreviations are as follows and are case-insensitive:
|
||||
|
||||
* `b` for bytes
|
||||
* `kb` for kilobytes
|
||||
* `mb` for megabytes
|
||||
* `gb` for gigabytes
|
||||
* `tb` for terabytes
|
||||
* `pb` for petabytes
|
||||
|
||||
The units are in powers of two, not ten. This means 1kb = 1024b according to this parser.
|
||||
|
||||
**Arguments**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------------|--------|--------------------|
|
||||
| value | `string`|`number` | String to parse, or number in bytes. |
|
||||
|
||||
**Returns**
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|-------------|-------------------------|
|
||||
| results | `number`|`null` | Return null upon error. Value in bytes otherwise. |
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
bytes.parse('1KB');
|
||||
// output: 1024
|
||||
|
||||
bytes.parse('1024');
|
||||
// output: 1024
|
||||
|
||||
bytes.parse(1024);
|
||||
// output: 1024
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
[ci-image]: https://badgen.net/github/checks/visionmedia/bytes.js/master?label=ci
|
||||
[ci-url]: https://github.com/visionmedia/bytes.js/actions?query=workflow%3Aci
|
||||
[coveralls-image]: https://badgen.net/coveralls/c/github/visionmedia/bytes.js/master
|
||||
[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master
|
||||
[downloads-image]: https://badgen.net/npm/dm/bytes
|
||||
[downloads-url]: https://npmjs.org/package/bytes
|
||||
[npm-image]: https://badgen.net/npm/v/bytes
|
||||
[npm-url]: https://npmjs.org/package/bytes
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
/*!
|
||||
* bytes
|
||||
* Copyright(c) 2012-2014 TJ Holowaychuk
|
||||
* Copyright(c) 2015 Jed Watson
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Module exports.
|
||||
* @public
|
||||
*/
|
||||
|
||||
module.exports = bytes;
|
||||
module.exports.format = format;
|
||||
module.exports.parse = parse;
|
||||
|
||||
/**
|
||||
* Module variables.
|
||||
* @private
|
||||
*/
|
||||
|
||||
var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g;
|
||||
|
||||
var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/;
|
||||
|
||||
var map = {
|
||||
b: 1,
|
||||
kb: 1 << 10,
|
||||
mb: 1 << 20,
|
||||
gb: 1 << 30,
|
||||
tb: Math.pow(1024, 4),
|
||||
pb: Math.pow(1024, 5),
|
||||
};
|
||||
|
||||
var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;
|
||||
|
||||
/**
|
||||
* Convert the given value in bytes into a string or parse to string to an integer in bytes.
|
||||
*
|
||||
* @param {string|number} value
|
||||
* @param {{
|
||||
* case: [string],
|
||||
* decimalPlaces: [number]
|
||||
* fixedDecimals: [boolean]
|
||||
* thousandsSeparator: [string]
|
||||
* unitSeparator: [string]
|
||||
* }} [options] bytes options.
|
||||
*
|
||||
* @returns {string|number|null}
|
||||
*/
|
||||
|
||||
function bytes(value, options) {
|
||||
if (typeof value === 'string') {
|
||||
return parse(value);
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
return format(value, options);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the given value in bytes into a string.
|
||||
*
|
||||
* If the value is negative, it is kept as such. If it is a float,
|
||||
* it is rounded.
|
||||
*
|
||||
* @param {number} value
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.decimalPlaces=2]
|
||||
* @param {number} [options.fixedDecimals=false]
|
||||
* @param {string} [options.thousandsSeparator=]
|
||||
* @param {string} [options.unit=]
|
||||
* @param {string} [options.unitSeparator=]
|
||||
*
|
||||
* @returns {string|null}
|
||||
* @public
|
||||
*/
|
||||
|
||||
function format(value, options) {
|
||||
if (!Number.isFinite(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var mag = Math.abs(value);
|
||||
var thousandsSeparator = (options && options.thousandsSeparator) || '';
|
||||
var unitSeparator = (options && options.unitSeparator) || '';
|
||||
var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
|
||||
var fixedDecimals = Boolean(options && options.fixedDecimals);
|
||||
var unit = (options && options.unit) || '';
|
||||
|
||||
if (!unit || !map[unit.toLowerCase()]) {
|
||||
if (mag >= map.pb) {
|
||||
unit = 'PB';
|
||||
} else if (mag >= map.tb) {
|
||||
unit = 'TB';
|
||||
} else if (mag >= map.gb) {
|
||||
unit = 'GB';
|
||||
} else if (mag >= map.mb) {
|
||||
unit = 'MB';
|
||||
} else if (mag >= map.kb) {
|
||||
unit = 'KB';
|
||||
} else {
|
||||
unit = 'B';
|
||||
}
|
||||
}
|
||||
|
||||
var val = value / map[unit.toLowerCase()];
|
||||
var str = val.toFixed(decimalPlaces);
|
||||
|
||||
if (!fixedDecimals) {
|
||||
str = str.replace(formatDecimalsRegExp, '$1');
|
||||
}
|
||||
|
||||
if (thousandsSeparator) {
|
||||
str = str.split('.').map(function (s, i) {
|
||||
return i === 0
|
||||
? s.replace(formatThousandsRegExp, thousandsSeparator)
|
||||
: s
|
||||
}).join('.');
|
||||
}
|
||||
|
||||
return str + unitSeparator + unit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the string value into an integer in bytes.
|
||||
*
|
||||
* If no unit is given, it is assumed the value is in bytes.
|
||||
*
|
||||
* @param {number|string} val
|
||||
*
|
||||
* @returns {number|null}
|
||||
* @public
|
||||
*/
|
||||
|
||||
function parse(val) {
|
||||
if (typeof val === 'number' && !isNaN(val)) {
|
||||
return val;
|
||||
}
|
||||
|
||||
if (typeof val !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Test if the string passed is valid
|
||||
var results = parseRegExp.exec(val);
|
||||
var floatValue;
|
||||
var unit = 'b';
|
||||
|
||||
if (!results) {
|
||||
// Nothing could be extracted from the given string
|
||||
floatValue = parseInt(val, 10);
|
||||
unit = 'b'
|
||||
} else {
|
||||
// Retrieve the value and the unit
|
||||
floatValue = parseFloat(results[1]);
|
||||
unit = results[4].toLowerCase();
|
||||
}
|
||||
|
||||
if (isNaN(floatValue)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Math.floor(map[unit] * floatValue);
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "bytes",
|
||||
"description": "Utility to parse a string bytes to bytes and vice-versa",
|
||||
"version": "3.1.2",
|
||||
"author": "TJ Holowaychuk <tj@vision-media.ca> (http://tjholowaychuk.com)",
|
||||
"contributors": [
|
||||
"Jed Watson <jed.watson@me.com>",
|
||||
"Théo FIDRY <theo.fidry@gmail.com>"
|
||||
],
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"byte",
|
||||
"bytes",
|
||||
"utility",
|
||||
"parse",
|
||||
"parser",
|
||||
"convert",
|
||||
"converter"
|
||||
],
|
||||
"repository": "visionmedia/bytes.js",
|
||||
"devDependencies": {
|
||||
"eslint": "7.32.0",
|
||||
"eslint-plugin-markdown": "2.2.1",
|
||||
"mocha": "9.2.0",
|
||||
"nyc": "15.1.0"
|
||||
},
|
||||
"files": [
|
||||
"History.md",
|
||||
"LICENSE",
|
||||
"Readme.md",
|
||||
"index.js"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"test": "mocha --check-leaks --reporter spec",
|
||||
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
|
||||
"test-cov": "nyc --reporter=html --reporter=text npm test"
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"root": true,
|
||||
|
||||
"extends": "@ljharb",
|
||||
|
||||
"rules": {
|
||||
"func-name-matching": 0,
|
||||
"id-length": 0,
|
||||
"new-cap": [2, {
|
||||
"capIsNewExceptions": [
|
||||
"GetIntrinsic",
|
||||
],
|
||||
}],
|
||||
"no-extra-parens": 0,
|
||||
"no-magic-numbers": 0,
|
||||
},
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: [ljharb]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: npm/call-bind-apply-helpers
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"all": true,
|
||||
"check-coverage": false,
|
||||
"reporter": ["text-summary", "text", "html", "json"],
|
||||
"exclude": [
|
||||
"coverage",
|
||||
"test"
|
||||
]
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [v1.0.2](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.1...v1.0.2) - 2025-02-12
|
||||
|
||||
### Commits
|
||||
|
||||
- [types] improve inferred types [`e6f9586`](https://github.com/ljharb/call-bind-apply-helpers/commit/e6f95860a3c72879cb861a858cdfb8138fbedec1)
|
||||
- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `@types/tape`, `es-value-fixtures`, `for-each`, `has-strict-mode`, `object-inspect` [`e43d540`](https://github.com/ljharb/call-bind-apply-helpers/commit/e43d5409f97543bfbb11f345d47d8ce4e066d8c1)
|
||||
|
||||
## [v1.0.1](https://github.com/ljharb/call-bind-apply-helpers/compare/v1.0.0...v1.0.1) - 2024-12-08
|
||||
|
||||
### Commits
|
||||
|
||||
- [types] `reflectApply`: fix types [`4efc396`](https://github.com/ljharb/call-bind-apply-helpers/commit/4efc3965351a4f02cc55e836fa391d3d11ef2ef8)
|
||||
- [Fix] `reflectApply`: oops, Reflect is not a function [`83cc739`](https://github.com/ljharb/call-bind-apply-helpers/commit/83cc7395de6b79b7730bdf092f1436f0b1263c75)
|
||||
- [Dev Deps] update `@arethetypeswrong/cli` [`80bd5d3`](https://github.com/ljharb/call-bind-apply-helpers/commit/80bd5d3ae58b4f6b6995ce439dd5a1bcb178a940)
|
||||
|
||||
## v1.0.0 - 2024-12-05
|
||||
|
||||
### Commits
|
||||
|
||||
- Initial implementation, tests, readme [`7879629`](https://github.com/ljharb/call-bind-apply-helpers/commit/78796290f9b7430c9934d6f33d94ae9bc89fce04)
|
||||
- Initial commit [`3f1dc16`](https://github.com/ljharb/call-bind-apply-helpers/commit/3f1dc164afc43285631b114a5f9dd9137b2b952f)
|
||||
- npm init [`081df04`](https://github.com/ljharb/call-bind-apply-helpers/commit/081df048c312fcee400922026f6e97281200a603)
|
||||
- Only apps should have lockfiles [`5b9ca0f`](https://github.com/ljharb/call-bind-apply-helpers/commit/5b9ca0fe8101ebfaf309c549caac4e0a017ed930)
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Jordan Harband
|
||||
|
||||
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.
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
# call-bind-apply-helpers <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
|
||||
|
||||
[![github actions][actions-image]][actions-url]
|
||||
[![coverage][codecov-image]][codecov-url]
|
||||
[![dependency status][deps-svg]][deps-url]
|
||||
[![dev dependency status][dev-deps-svg]][dev-deps-url]
|
||||
[![License][license-image]][license-url]
|
||||
[![Downloads][downloads-image]][downloads-url]
|
||||
|
||||
[![npm badge][npm-badge-png]][package-url]
|
||||
|
||||
Helper functions around Function call/apply/bind, for use in `call-bind`.
|
||||
|
||||
The only packages that should likely ever use this package directly are `call-bind` and `get-intrinsic`.
|
||||
Please use `call-bind` unless you have a very good reason not to.
|
||||
|
||||
## Getting started
|
||||
|
||||
```sh
|
||||
npm install --save call-bind-apply-helpers
|
||||
```
|
||||
|
||||
## Usage/Examples
|
||||
|
||||
```js
|
||||
const assert = require('assert');
|
||||
const callBindBasic = require('call-bind-apply-helpers');
|
||||
|
||||
function f(a, b) {
|
||||
assert.equal(this, 1);
|
||||
assert.equal(a, 2);
|
||||
assert.equal(b, 3);
|
||||
assert.equal(arguments.length, 2);
|
||||
}
|
||||
|
||||
const fBound = callBindBasic([f, 1]);
|
||||
|
||||
delete Function.prototype.call;
|
||||
delete Function.prototype.bind;
|
||||
|
||||
fBound(2, 3);
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
Clone the repo, `npm install`, and run `npm test`
|
||||
|
||||
[package-url]: https://npmjs.org/package/call-bind-apply-helpers
|
||||
[npm-version-svg]: https://versionbadg.es/ljharb/call-bind-apply-helpers.svg
|
||||
[deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers.svg
|
||||
[deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers
|
||||
[dev-deps-svg]: https://david-dm.org/ljharb/call-bind-apply-helpers/dev-status.svg
|
||||
[dev-deps-url]: https://david-dm.org/ljharb/call-bind-apply-helpers#info=devDependencies
|
||||
[npm-badge-png]: https://nodei.co/npm/call-bind-apply-helpers.png?downloads=true&stars=true
|
||||
[license-image]: https://img.shields.io/npm/l/call-bind-apply-helpers.svg
|
||||
[license-url]: LICENSE
|
||||
[downloads-image]: https://img.shields.io/npm/dm/call-bind-apply-helpers.svg
|
||||
[downloads-url]: https://npm-stat.com/charts.html?package=call-bind-apply-helpers
|
||||
[codecov-image]: https://codecov.io/gh/ljharb/call-bind-apply-helpers/branch/main/graphs/badge.svg
|
||||
[codecov-url]: https://app.codecov.io/gh/ljharb/call-bind-apply-helpers/
|
||||
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bind-apply-helpers
|
||||
[actions-url]: https://github.com/ljharb/call-bind-apply-helpers/actions
|
||||
+1
@@ -0,0 +1 @@
|
||||
export = Reflect.apply;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
var bind = require('function-bind');
|
||||
|
||||
var $apply = require('./functionApply');
|
||||
var $call = require('./functionCall');
|
||||
var $reflectApply = require('./reflectApply');
|
||||
|
||||
/** @type {import('./actualApply')} */
|
||||
module.exports = $reflectApply || bind.call($call, $apply);
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import actualApply from './actualApply';
|
||||
|
||||
type TupleSplitHead<T extends any[], N extends number> = T['length'] extends N
|
||||
? T
|
||||
: T extends [...infer R, any]
|
||||
? TupleSplitHead<R, N>
|
||||
: never
|
||||
|
||||
type TupleSplitTail<T, N extends number, O extends any[] = []> = O['length'] extends N
|
||||
? T
|
||||
: T extends [infer F, ...infer R]
|
||||
? TupleSplitTail<[...R], N, [...O, F]>
|
||||
: never
|
||||
|
||||
type TupleSplit<T extends any[], N extends number> = [TupleSplitHead<T, N>, TupleSplitTail<T, N>]
|
||||
|
||||
declare function applyBind(...args: TupleSplit<Parameters<typeof actualApply>, 2>[1]): ReturnType<typeof actualApply>;
|
||||
|
||||
export = applyBind;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
|
||||
var bind = require('function-bind');
|
||||
var $apply = require('./functionApply');
|
||||
var actualApply = require('./actualApply');
|
||||
|
||||
/** @type {import('./applyBind')} */
|
||||
module.exports = function applyBind() {
|
||||
return actualApply(bind, $apply, arguments);
|
||||
};
|
||||
+1
@@ -0,0 +1 @@
|
||||
export = Function.prototype.apply;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
'use strict';
|
||||
|
||||
/** @type {import('./functionApply')} */
|
||||
module.exports = Function.prototype.apply;
|
||||
+1
@@ -0,0 +1 @@
|
||||
export = Function.prototype.call;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
'use strict';
|
||||
|
||||
/** @type {import('./functionCall')} */
|
||||
module.exports = Function.prototype.call;
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
type RemoveFromTuple<
|
||||
Tuple extends readonly unknown[],
|
||||
RemoveCount extends number,
|
||||
Index extends 1[] = []
|
||||
> = Index["length"] extends RemoveCount
|
||||
? Tuple
|
||||
: Tuple extends [infer First, ...infer Rest]
|
||||
? RemoveFromTuple<Rest, RemoveCount, [...Index, 1]>
|
||||
: Tuple;
|
||||
|
||||
type ConcatTuples<
|
||||
Prefix extends readonly unknown[],
|
||||
Suffix extends readonly unknown[]
|
||||
> = [...Prefix, ...Suffix];
|
||||
|
||||
type ExtractFunctionParams<T> = T extends (this: infer TThis, ...args: infer P extends readonly unknown[]) => infer R
|
||||
? { thisArg: TThis; params: P; returnType: R }
|
||||
: never;
|
||||
|
||||
type BindFunction<
|
||||
T extends (this: any, ...args: any[]) => any,
|
||||
TThis,
|
||||
TBoundArgs extends readonly unknown[],
|
||||
ReceiverBound extends boolean
|
||||
> = ExtractFunctionParams<T> extends {
|
||||
thisArg: infer OrigThis;
|
||||
params: infer P extends readonly unknown[];
|
||||
returnType: infer R;
|
||||
}
|
||||
? ReceiverBound extends true
|
||||
? (...args: RemoveFromTuple<P, Extract<TBoundArgs["length"], number>>) => R extends [OrigThis, ...infer Rest]
|
||||
? [TThis, ...Rest] // Replace `this` with `thisArg`
|
||||
: R
|
||||
: <U, RemainingArgs extends RemoveFromTuple<P, Extract<TBoundArgs["length"], number>>>(
|
||||
thisArg: U,
|
||||
...args: RemainingArgs
|
||||
) => R extends [OrigThis, ...infer Rest]
|
||||
? [U, ...ConcatTuples<TBoundArgs, Rest>] // Preserve bound args in return type
|
||||
: R
|
||||
: never;
|
||||
|
||||
declare function callBind<
|
||||
const T extends (this: any, ...args: any[]) => any,
|
||||
Extracted extends ExtractFunctionParams<T>,
|
||||
const TBoundArgs extends Partial<Extracted["params"]> & readonly unknown[],
|
||||
const TThis extends Extracted["thisArg"]
|
||||
>(
|
||||
args: [fn: T, thisArg: TThis, ...boundArgs: TBoundArgs]
|
||||
): BindFunction<T, TThis, TBoundArgs, true>;
|
||||
|
||||
declare function callBind<
|
||||
const T extends (this: any, ...args: any[]) => any,
|
||||
Extracted extends ExtractFunctionParams<T>,
|
||||
const TBoundArgs extends Partial<Extracted["params"]> & readonly unknown[]
|
||||
>(
|
||||
args: [fn: T, ...boundArgs: TBoundArgs]
|
||||
): BindFunction<T, Extracted["thisArg"], TBoundArgs, false>;
|
||||
|
||||
declare function callBind<const TArgs extends readonly unknown[]>(
|
||||
args: [fn: Exclude<TArgs[0], Function>, ...rest: TArgs]
|
||||
): never;
|
||||
|
||||
// export as namespace callBind;
|
||||
export = callBind;
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
'use strict';
|
||||
|
||||
var bind = require('function-bind');
|
||||
var $TypeError = require('es-errors/type');
|
||||
|
||||
var $call = require('./functionCall');
|
||||
var $actualApply = require('./actualApply');
|
||||
|
||||
/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */
|
||||
module.exports = function callBindBasic(args) {
|
||||
if (args.length < 1 || typeof args[0] !== 'function') {
|
||||
throw new $TypeError('a function is required');
|
||||
}
|
||||
return $actualApply(bind, $call, args);
|
||||
};
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"name": "call-bind-apply-helpers",
|
||||
"version": "1.0.2",
|
||||
"description": "Helper functions around Function call/apply/bind, for use in `call-bind`",
|
||||
"main": "index.js",
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./actualApply": "./actualApply.js",
|
||||
"./applyBind": "./applyBind.js",
|
||||
"./functionApply": "./functionApply.js",
|
||||
"./functionCall": "./functionCall.js",
|
||||
"./reflectApply": "./reflectApply.js",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"scripts": {
|
||||
"prepack": "npmignore --auto --commentLines=auto",
|
||||
"prepublish": "not-in-publish || npm run prepublishOnly",
|
||||
"prepublishOnly": "safe-publish-latest",
|
||||
"prelint": "evalmd README.md",
|
||||
"lint": "eslint --ext=.js,.mjs .",
|
||||
"postlint": "tsc -p . && attw -P",
|
||||
"pretest": "npm run lint",
|
||||
"tests-only": "nyc tape 'test/**/*.js'",
|
||||
"test": "npm run tests-only",
|
||||
"posttest": "npx npm@'>=10.2' audit --production",
|
||||
"version": "auto-changelog && git add CHANGELOG.md",
|
||||
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/ljharb/call-bind-apply-helpers.git"
|
||||
},
|
||||
"author": "Jordan Harband <ljharb@gmail.com>",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/ljharb/call-bind-apply-helpers/issues"
|
||||
},
|
||||
"homepage": "https://github.com/ljharb/call-bind-apply-helpers#readme",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"function-bind": "^1.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@arethetypeswrong/cli": "^0.17.3",
|
||||
"@ljharb/eslint-config": "^21.1.1",
|
||||
"@ljharb/tsconfig": "^0.2.3",
|
||||
"@types/for-each": "^0.3.3",
|
||||
"@types/function-bind": "^1.1.10",
|
||||
"@types/object-inspect": "^1.13.0",
|
||||
"@types/tape": "^5.8.1",
|
||||
"auto-changelog": "^2.5.0",
|
||||
"encoding": "^0.1.13",
|
||||
"es-value-fixtures": "^1.7.1",
|
||||
"eslint": "=8.8.0",
|
||||
"evalmd": "^0.0.19",
|
||||
"for-each": "^0.3.5",
|
||||
"has-strict-mode": "^1.1.0",
|
||||
"in-publish": "^2.0.1",
|
||||
"npmignore": "^0.3.1",
|
||||
"nyc": "^10.3.2",
|
||||
"object-inspect": "^1.13.4",
|
||||
"safe-publish-latest": "^2.0.0",
|
||||
"tape": "^5.9.0",
|
||||
"typescript": "next"
|
||||
},
|
||||
"testling": {
|
||||
"files": "test/index.js"
|
||||
},
|
||||
"auto-changelog": {
|
||||
"output": "CHANGELOG.md",
|
||||
"template": "keepachangelog",
|
||||
"unreleased": false,
|
||||
"commitLimit": false,
|
||||
"backfillLimit": false,
|
||||
"hideCredit": true
|
||||
},
|
||||
"publishConfig": {
|
||||
"ignore": [
|
||||
".github/workflows"
|
||||
]
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
declare const reflectApply: false | typeof Reflect.apply;
|
||||
|
||||
export = reflectApply;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
'use strict';
|
||||
|
||||
/** @type {import('./reflectApply')} */
|
||||
module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply;
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
'use strict';
|
||||
|
||||
var callBind = require('../');
|
||||
var hasStrictMode = require('has-strict-mode')();
|
||||
var forEach = require('for-each');
|
||||
var inspect = require('object-inspect');
|
||||
var v = require('es-value-fixtures');
|
||||
|
||||
var test = require('tape');
|
||||
|
||||
test('callBindBasic', function (t) {
|
||||
forEach(v.nonFunctions, function (nonFunction) {
|
||||
t['throws'](
|
||||
// @ts-expect-error
|
||||
function () { callBind([nonFunction]); },
|
||||
TypeError,
|
||||
inspect(nonFunction) + ' is not a function'
|
||||
);
|
||||
});
|
||||
|
||||
var sentinel = { sentinel: true };
|
||||
/** @type {<T, A extends number, B extends number>(this: T, a: A, b: B) => [T | undefined, A, B]} */
|
||||
var func = function (a, b) {
|
||||
// eslint-disable-next-line no-invalid-this
|
||||
return [!hasStrictMode && this === global ? undefined : this, a, b];
|
||||
};
|
||||
t.equal(func.length, 2, 'original function length is 2');
|
||||
|
||||
/** type {(thisArg: unknown, a: number, b: number) => [unknown, number, number]} */
|
||||
var bound = callBind([func]);
|
||||
/** type {((a: number, b: number) => [typeof sentinel, typeof a, typeof b])} */
|
||||
var boundR = callBind([func, sentinel]);
|
||||
/** type {((b: number) => [typeof sentinel, number, typeof b])} */
|
||||
var boundArg = callBind([func, sentinel, /** @type {const} */ (1)]);
|
||||
|
||||
// @ts-expect-error
|
||||
t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with no args');
|
||||
|
||||
// @ts-expect-error
|
||||
t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args');
|
||||
// @ts-expect-error
|
||||
t.deepEqual(bound(1, 2), [hasStrictMode ? 1 : Object(1), 2, undefined], 'bound func too few args');
|
||||
// @ts-expect-error
|
||||
t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args');
|
||||
// @ts-expect-error
|
||||
t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args');
|
||||
|
||||
t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args');
|
||||
t.deepEqual(bound(1, 2, 3), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with right args');
|
||||
t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args');
|
||||
t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg');
|
||||
|
||||
// @ts-expect-error
|
||||
t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args');
|
||||
// @ts-expect-error
|
||||
t.deepEqual(bound(1, 2, 3, 4), [hasStrictMode ? 1 : Object(1), 2, 3], 'bound func with too many args');
|
||||
// @ts-expect-error
|
||||
t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args');
|
||||
// @ts-expect-error
|
||||
t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args');
|
||||
|
||||
t.end();
|
||||
});
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "@ljharb/tsconfig",
|
||||
"compilerOptions": {
|
||||
"target": "es2021",
|
||||
},
|
||||
"exclude": [
|
||||
"coverage",
|
||||
],
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"root": true,
|
||||
|
||||
"extends": "@ljharb",
|
||||
|
||||
"rules": {
|
||||
"new-cap": [2, {
|
||||
"capIsNewExceptions": [
|
||||
"GetIntrinsic",
|
||||
],
|
||||
}],
|
||||
},
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: [ljharb]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: npm/call-bound
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"all": true,
|
||||
"check-coverage": false,
|
||||
"reporter": ["text-summary", "text", "html", "json"],
|
||||
"exclude": [
|
||||
"coverage",
|
||||
"test"
|
||||
]
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [v1.0.4](https://github.com/ljharb/call-bound/compare/v1.0.3...v1.0.4) - 2025-03-03
|
||||
|
||||
### Commits
|
||||
|
||||
- [types] improve types [`e648922`](https://github.com/ljharb/call-bound/commit/e6489222a9e54f350fbf952ceabe51fd8b6027ff)
|
||||
- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `@types/tape`, `es-value-fixtures`, `for-each`, `has-strict-mode`, `object-inspect` [`a42a5eb`](https://github.com/ljharb/call-bound/commit/a42a5ebe6c1b54fcdc7997c7dc64fdca9e936719)
|
||||
- [Deps] update `call-bind-apply-helpers`, `get-intrinsic` [`f529eac`](https://github.com/ljharb/call-bound/commit/f529eac132404c17156bbc23ab2297a25d0f20b8)
|
||||
|
||||
## [v1.0.3](https://github.com/ljharb/call-bound/compare/v1.0.2...v1.0.3) - 2024-12-15
|
||||
|
||||
### Commits
|
||||
|
||||
- [Refactor] use `call-bind-apply-helpers` instead of `call-bind` [`5e0b134`](https://github.com/ljharb/call-bound/commit/5e0b13496df14fb7d05dae9412f088da8d3f75be)
|
||||
- [Deps] update `get-intrinsic` [`41fc967`](https://github.com/ljharb/call-bound/commit/41fc96732a22c7b7e8f381f93ccc54bb6293be2e)
|
||||
- [readme] fix example [`79a0137`](https://github.com/ljharb/call-bound/commit/79a0137723f7c6d09c9c05452bbf8d5efb5d6e49)
|
||||
- [meta] add `sideEffects` flag [`08b07be`](https://github.com/ljharb/call-bound/commit/08b07be7f1c03f67dc6f3cdaf0906259771859f7)
|
||||
|
||||
## [v1.0.2](https://github.com/ljharb/call-bound/compare/v1.0.1...v1.0.2) - 2024-12-10
|
||||
|
||||
### Commits
|
||||
|
||||
- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/tsconfig`, `gopd` [`e6a5ffe`](https://github.com/ljharb/call-bound/commit/e6a5ffe849368fe4f74dfd6cdeca1b9baa39e8d5)
|
||||
- [Deps] update `call-bind`, `get-intrinsic` [`2aeb5b5`](https://github.com/ljharb/call-bound/commit/2aeb5b521dc2b2683d1345c753ea1161de2d1c14)
|
||||
- [types] improve return type [`1a0c9fe`](https://github.com/ljharb/call-bound/commit/1a0c9fe3114471e7ca1f57d104e2efe713bb4871)
|
||||
|
||||
## v1.0.1 - 2024-12-05
|
||||
|
||||
### Commits
|
||||
|
||||
- Initial implementation, tests, readme, types [`6d94121`](https://github.com/ljharb/call-bound/commit/6d94121a9243602e506334069f7a03189fe3363d)
|
||||
- Initial commit [`0eae867`](https://github.com/ljharb/call-bound/commit/0eae867334ea025c33e6e91cdecfc9df96680cf9)
|
||||
- npm init [`71b2479`](https://github.com/ljharb/call-bound/commit/71b2479c6723e0b7d91a6b663613067e98b7b275)
|
||||
- Only apps should have lockfiles [`c3754a9`](https://github.com/ljharb/call-bound/commit/c3754a949b7f9132b47e2d18c1729889736741eb)
|
||||
- [actions] skip `npm ls` in node < 10 [`74275a5`](https://github.com/ljharb/call-bound/commit/74275a5186b8caf6309b6b97472bdcb0df4683a8)
|
||||
- [Dev Deps] add missing peer dep [`1354de8`](https://github.com/ljharb/call-bound/commit/1354de8679413e4ae9c523d85f76fa7a5e032d97)
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Jordan Harband
|
||||
|
||||
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.
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
# call-bound <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
|
||||
|
||||
[![github actions][actions-image]][actions-url]
|
||||
[![coverage][codecov-image]][codecov-url]
|
||||
[![dependency status][deps-svg]][deps-url]
|
||||
[![dev dependency status][dev-deps-svg]][dev-deps-url]
|
||||
[![License][license-image]][license-url]
|
||||
[![Downloads][downloads-image]][downloads-url]
|
||||
|
||||
[![npm badge][npm-badge-png]][package-url]
|
||||
|
||||
Robust call-bound JavaScript intrinsics, using `call-bind` and `get-intrinsic`.
|
||||
|
||||
## Getting started
|
||||
|
||||
```sh
|
||||
npm install --save call-bound
|
||||
```
|
||||
|
||||
## Usage/Examples
|
||||
|
||||
```js
|
||||
const assert = require('assert');
|
||||
const callBound = require('call-bound');
|
||||
|
||||
const slice = callBound('Array.prototype.slice');
|
||||
|
||||
delete Function.prototype.call;
|
||||
delete Function.prototype.bind;
|
||||
delete Array.prototype.slice;
|
||||
|
||||
assert.deepEqual(slice([1, 2, 3, 4], 1, -1), [2, 3]);
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
Clone the repo, `npm install`, and run `npm test`
|
||||
|
||||
[package-url]: https://npmjs.org/package/call-bound
|
||||
[npm-version-svg]: https://versionbadg.es/ljharb/call-bound.svg
|
||||
[deps-svg]: https://david-dm.org/ljharb/call-bound.svg
|
||||
[deps-url]: https://david-dm.org/ljharb/call-bound
|
||||
[dev-deps-svg]: https://david-dm.org/ljharb/call-bound/dev-status.svg
|
||||
[dev-deps-url]: https://david-dm.org/ljharb/call-bound#info=devDependencies
|
||||
[npm-badge-png]: https://nodei.co/npm/call-bound.png?downloads=true&stars=true
|
||||
[license-image]: https://img.shields.io/npm/l/call-bound.svg
|
||||
[license-url]: LICENSE
|
||||
[downloads-image]: https://img.shields.io/npm/dm/call-bound.svg
|
||||
[downloads-url]: https://npm-stat.com/charts.html?package=call-bound
|
||||
[codecov-image]: https://codecov.io/gh/ljharb/call-bound/branch/main/graphs/badge.svg
|
||||
[codecov-url]: https://app.codecov.io/gh/ljharb/call-bound/
|
||||
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/call-bound
|
||||
[actions-url]: https://github.com/ljharb/call-bound/actions
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
type Intrinsic = typeof globalThis;
|
||||
|
||||
type IntrinsicName = keyof Intrinsic | `%${keyof Intrinsic}%`;
|
||||
|
||||
type IntrinsicPath = IntrinsicName | `${StripPercents<IntrinsicName>}.${string}` | `%${StripPercents<IntrinsicName>}.${string}%`;
|
||||
|
||||
type AllowMissing = boolean;
|
||||
|
||||
type StripPercents<T extends string> = T extends `%${infer U}%` ? U : T;
|
||||
|
||||
type BindMethodPrecise<F> =
|
||||
F extends (this: infer This, ...args: infer Args) => infer R
|
||||
? (obj: This, ...args: Args) => R
|
||||
: F extends {
|
||||
(this: infer This1, ...args: infer Args1): infer R1;
|
||||
(this: infer This2, ...args: infer Args2): infer R2
|
||||
}
|
||||
? {
|
||||
(obj: This1, ...args: Args1): R1;
|
||||
(obj: This2, ...args: Args2): R2
|
||||
}
|
||||
: never
|
||||
|
||||
// Extract method type from a prototype
|
||||
type GetPrototypeMethod<T extends keyof typeof globalThis, M extends string> =
|
||||
(typeof globalThis)[T] extends { prototype: any }
|
||||
? M extends keyof (typeof globalThis)[T]['prototype']
|
||||
? (typeof globalThis)[T]['prototype'][M]
|
||||
: never
|
||||
: never
|
||||
|
||||
// Get static property/method
|
||||
type GetStaticMember<T extends keyof typeof globalThis, P extends string> =
|
||||
P extends keyof (typeof globalThis)[T] ? (typeof globalThis)[T][P] : never
|
||||
|
||||
// Type that maps string path to actual bound function or value with better precision
|
||||
type BoundIntrinsic<S extends string> =
|
||||
S extends `${infer Obj}.prototype.${infer Method}`
|
||||
? Obj extends keyof typeof globalThis
|
||||
? BindMethodPrecise<GetPrototypeMethod<Obj, Method & string>>
|
||||
: unknown
|
||||
: S extends `${infer Obj}.${infer Prop}`
|
||||
? Obj extends keyof typeof globalThis
|
||||
? GetStaticMember<Obj, Prop & string>
|
||||
: unknown
|
||||
: unknown
|
||||
|
||||
declare function arraySlice<T>(array: readonly T[], start?: number, end?: number): T[];
|
||||
declare function arraySlice<T>(array: ArrayLike<T>, start?: number, end?: number): T[];
|
||||
declare function arraySlice<T>(array: IArguments, start?: number, end?: number): T[];
|
||||
|
||||
// Special cases for methods that need explicit typing
|
||||
interface SpecialCases {
|
||||
'%Object.prototype.isPrototypeOf%': (thisArg: {}, obj: unknown) => boolean;
|
||||
'%String.prototype.replace%': {
|
||||
(str: string, searchValue: string | RegExp, replaceValue: string): string;
|
||||
(str: string, searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string
|
||||
};
|
||||
'%Object.prototype.toString%': (obj: {}) => string;
|
||||
'%Object.prototype.hasOwnProperty%': (obj: {}, v: PropertyKey) => boolean;
|
||||
'%Array.prototype.slice%': typeof arraySlice;
|
||||
'%Array.prototype.map%': <T, U>(array: readonly T[], callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any) => U[];
|
||||
'%Array.prototype.filter%': <T>(array: readonly T[], predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any) => T[];
|
||||
'%Array.prototype.indexOf%': <T>(array: readonly T[], searchElement: T, fromIndex?: number) => number;
|
||||
'%Function.prototype.apply%': <T, A extends any[], R>(fn: (...args: A) => R, thisArg: any, args: A) => R;
|
||||
'%Function.prototype.call%': <T, A extends any[], R>(fn: (...args: A) => R, thisArg: any, ...args: A) => R;
|
||||
'%Function.prototype.bind%': <T, A extends any[], R>(fn: (...args: A) => R, thisArg: any, ...args: A) => (...remainingArgs: A) => R;
|
||||
'%Promise.prototype.then%': {
|
||||
<T, R>(promise: Promise<T>, onfulfilled: (value: T) => R | PromiseLike<R>): Promise<R>;
|
||||
<T, R>(promise: Promise<T>, onfulfilled: ((value: T) => R | PromiseLike<R>) | undefined | null, onrejected: (reason: any) => R | PromiseLike<R>): Promise<R>;
|
||||
};
|
||||
'%RegExp.prototype.test%': (regexp: RegExp, str: string) => boolean;
|
||||
'%RegExp.prototype.exec%': (regexp: RegExp, str: string) => RegExpExecArray | null;
|
||||
'%Error.prototype.toString%': (error: Error) => string;
|
||||
'%TypeError.prototype.toString%': (error: TypeError) => string;
|
||||
'%String.prototype.split%': (
|
||||
obj: unknown,
|
||||
splitter: string | RegExp | {
|
||||
[Symbol.split](string: string, limit?: number): string[];
|
||||
},
|
||||
limit?: number | undefined
|
||||
) => string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a bound function for a prototype method, or a value for a static property.
|
||||
*
|
||||
* @param name - The name of the intrinsic (e.g. 'Array.prototype.slice')
|
||||
* @param {AllowMissing} [allowMissing] - Whether to allow missing intrinsics (default: false)
|
||||
*/
|
||||
declare function callBound<K extends keyof SpecialCases | StripPercents<keyof SpecialCases>, S extends IntrinsicPath>(name: K, allowMissing?: AllowMissing): SpecialCases[`%${StripPercents<K>}%`];
|
||||
declare function callBound<K extends keyof SpecialCases | StripPercents<keyof SpecialCases>, S extends IntrinsicPath>(name: S, allowMissing?: AllowMissing): BoundIntrinsic<S>;
|
||||
|
||||
export = callBound;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
var GetIntrinsic = require('get-intrinsic');
|
||||
|
||||
var callBindBasic = require('call-bind-apply-helpers');
|
||||
|
||||
/** @type {(thisArg: string, searchString: string, position?: number) => number} */
|
||||
var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]);
|
||||
|
||||
/** @type {import('.')} */
|
||||
module.exports = function callBoundIntrinsic(name, allowMissing) {
|
||||
/* eslint no-extra-parens: 0 */
|
||||
|
||||
var intrinsic = /** @type {(this: unknown, ...args: unknown[]) => unknown} */ (GetIntrinsic(name, !!allowMissing));
|
||||
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
|
||||
return callBindBasic(/** @type {const} */ ([intrinsic]));
|
||||
}
|
||||
return intrinsic;
|
||||
};
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"name": "call-bound",
|
||||
"version": "1.0.4",
|
||||
"description": "Robust call-bound JavaScript intrinsics, using `call-bind` and `get-intrinsic`.",
|
||||
"main": "index.js",
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"scripts": {
|
||||
"prepack": "npmignore --auto --commentLines=auto",
|
||||
"prepublish": "not-in-publish || npm run prepublishOnly",
|
||||
"prepublishOnly": "safe-publish-latest",
|
||||
"prelint": "evalmd README.md",
|
||||
"lint": "eslint --ext=.js,.mjs .",
|
||||
"postlint": "tsc -p . && attw -P",
|
||||
"pretest": "npm run lint",
|
||||
"tests-only": "nyc tape 'test/**/*.js'",
|
||||
"test": "npm run tests-only",
|
||||
"posttest": "npx npm@'>=10.2' audit --production",
|
||||
"version": "auto-changelog && git add CHANGELOG.md",
|
||||
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/ljharb/call-bound.git"
|
||||
},
|
||||
"keywords": [
|
||||
"javascript",
|
||||
"ecmascript",
|
||||
"es",
|
||||
"js",
|
||||
"callbind",
|
||||
"callbound",
|
||||
"call",
|
||||
"bind",
|
||||
"bound",
|
||||
"call-bind",
|
||||
"call-bound",
|
||||
"function",
|
||||
"es-abstract"
|
||||
],
|
||||
"author": "Jordan Harband <ljharb@gmail.com>",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
},
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/ljharb/call-bound/issues"
|
||||
},
|
||||
"homepage": "https://github.com/ljharb/call-bound#readme",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"get-intrinsic": "^1.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@arethetypeswrong/cli": "^0.17.4",
|
||||
"@ljharb/eslint-config": "^21.1.1",
|
||||
"@ljharb/tsconfig": "^0.3.0",
|
||||
"@types/call-bind": "^1.0.5",
|
||||
"@types/get-intrinsic": "^1.2.3",
|
||||
"@types/tape": "^5.8.1",
|
||||
"auto-changelog": "^2.5.0",
|
||||
"encoding": "^0.1.13",
|
||||
"es-value-fixtures": "^1.7.1",
|
||||
"eslint": "=8.8.0",
|
||||
"evalmd": "^0.0.19",
|
||||
"for-each": "^0.3.5",
|
||||
"gopd": "^1.2.0",
|
||||
"has-strict-mode": "^1.1.0",
|
||||
"in-publish": "^2.0.1",
|
||||
"npmignore": "^0.3.1",
|
||||
"nyc": "^10.3.2",
|
||||
"object-inspect": "^1.13.4",
|
||||
"safe-publish-latest": "^2.0.0",
|
||||
"tape": "^5.9.0",
|
||||
"typescript": "next"
|
||||
},
|
||||
"testling": {
|
||||
"files": "test/index.js"
|
||||
},
|
||||
"auto-changelog": {
|
||||
"output": "CHANGELOG.md",
|
||||
"template": "keepachangelog",
|
||||
"unreleased": false,
|
||||
"commitLimit": false,
|
||||
"backfillLimit": false,
|
||||
"hideCredit": true
|
||||
},
|
||||
"publishConfig": {
|
||||
"ignore": [
|
||||
".github/workflows"
|
||||
]
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
'use strict';
|
||||
|
||||
var test = require('tape');
|
||||
|
||||
var callBound = require('../');
|
||||
|
||||
/** @template {true} T @template U @typedef {T extends U ? T : never} AssertType */
|
||||
|
||||
test('callBound', function (t) {
|
||||
// static primitive
|
||||
t.equal(callBound('Array.length'), Array.length, 'Array.length yields itself');
|
||||
t.equal(callBound('%Array.length%'), Array.length, '%Array.length% yields itself');
|
||||
|
||||
// static non-function object
|
||||
t.equal(callBound('Array.prototype'), Array.prototype, 'Array.prototype yields itself');
|
||||
t.equal(callBound('%Array.prototype%'), Array.prototype, '%Array.prototype% yields itself');
|
||||
t.equal(callBound('Array.constructor'), Array.constructor, 'Array.constructor yields itself');
|
||||
t.equal(callBound('%Array.constructor%'), Array.constructor, '%Array.constructor% yields itself');
|
||||
|
||||
// static function
|
||||
t.equal(callBound('Date.parse'), Date.parse, 'Date.parse yields itself');
|
||||
t.equal(callBound('%Date.parse%'), Date.parse, '%Date.parse% yields itself');
|
||||
|
||||
// prototype primitive
|
||||
t.equal(callBound('Error.prototype.message'), Error.prototype.message, 'Error.prototype.message yields itself');
|
||||
t.equal(callBound('%Error.prototype.message%'), Error.prototype.message, '%Error.prototype.message% yields itself');
|
||||
|
||||
var x = callBound('Object.prototype.toString');
|
||||
var y = callBound('%Object.prototype.toString%');
|
||||
|
||||
// prototype function
|
||||
t.notEqual(x, Object.prototype.toString, 'Object.prototype.toString does not yield itself');
|
||||
t.notEqual(y, Object.prototype.toString, '%Object.prototype.toString% does not yield itself');
|
||||
t.equal(x(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original');
|
||||
t.equal(y(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original');
|
||||
|
||||
t['throws'](
|
||||
// @ts-expect-error
|
||||
function () { callBound('does not exist'); },
|
||||
SyntaxError,
|
||||
'nonexistent intrinsic throws'
|
||||
);
|
||||
t['throws'](
|
||||
// @ts-expect-error
|
||||
function () { callBound('does not exist', true); },
|
||||
SyntaxError,
|
||||
'allowMissing arg still throws for unknown intrinsic'
|
||||
);
|
||||
|
||||
t.test('real but absent intrinsic', { skip: typeof WeakRef !== 'undefined' }, function (st) {
|
||||
st['throws'](
|
||||
function () { callBound('WeakRef'); },
|
||||
TypeError,
|
||||
'real but absent intrinsic throws'
|
||||
);
|
||||
st.equal(callBound('WeakRef', true), undefined, 'allowMissing arg avoids exception');
|
||||
st.end();
|
||||
});
|
||||
|
||||
t.end();
|
||||
});
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "@ljharb/tsconfig",
|
||||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"lib": ["es2024"],
|
||||
},
|
||||
"exclude": [
|
||||
"coverage",
|
||||
],
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
Copyright (c) Felix Böhm
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
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.
|
||||
|
||||
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER 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,
|
||||
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
# cheerio-select [](https://npmjs.org/package/cheerio-select) [](http://travis-ci.org/cheeriojs/cheerio-select) [](https://npmjs.org/package/cheerio-select) [](https://coveralls.io/r/cheeriojs/cheerio-select)
|
||||
|
||||
CSS selector engine supporting jQuery selectors, based on [`css-select`](https://github.com/fb55/css-select).
|
||||
|
||||
Supports all jQuery positional pseudo-selectors:
|
||||
|
||||
- `:first`
|
||||
- `:last`
|
||||
- `:eq`
|
||||
- `:nth`
|
||||
- `:gt`
|
||||
- `:lt`
|
||||
- `:even`
|
||||
- `:odd`
|
||||
- `:not(:positional)`, where `:positional` is any of the above.
|
||||
|
||||
This library is a thin wrapper around [`css-select`](https://github.com/fb55/css-select).
|
||||
Only use this module if you will actually use jQuery positional selectors.
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import type { AnyNode } from "domhandler";
|
||||
import type { Selector } from "css-what";
|
||||
export declare function getDocumentRoot(node: AnyNode): AnyNode;
|
||||
export declare function groupSelectors(selectors: Selector[][]): [plain: Selector[][], filtered: Selector[][]];
|
||||
//# sourceMappingURL=helpers.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"helpers.d.ts","sourceRoot":"https://raw.githubusercontent.com/cheeriojs/cheerio-select/ef063a6ca4c3f0d02d2fc3505e750b6fb81c448d/src/","sources":["helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAGzC,wBAAgB,eAAe,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAGtD;AAED,wBAAgB,cAAc,CAC1B,SAAS,EAAE,QAAQ,EAAE,EAAE,GACxB,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,CAAC,CAa/C"}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { isFilter } from "./positionals.js";
|
||||
export function getDocumentRoot(node) {
|
||||
while (node.parent)
|
||||
node = node.parent;
|
||||
return node;
|
||||
}
|
||||
export function groupSelectors(selectors) {
|
||||
const filteredSelectors = [];
|
||||
const plainSelectors = [];
|
||||
for (const selector of selectors) {
|
||||
if (selector.some(isFilter)) {
|
||||
filteredSelectors.push(selector);
|
||||
}
|
||||
else {
|
||||
plainSelectors.push(selector);
|
||||
}
|
||||
}
|
||||
return [plainSelectors, filteredSelectors];
|
||||
}
|
||||
//# sourceMappingURL=helpers.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"helpers.js","sourceRoot":"https://raw.githubusercontent.com/cheeriojs/cheerio-select/ef063a6ca4c3f0d02d2fc3505e750b6fb81c448d/src/","sources":["helpers.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE5C,MAAM,UAAU,eAAe,CAAC,IAAa;IACzC,OAAO,IAAI,CAAC,MAAM;QAAE,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC;IACvC,OAAO,IAAI,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,cAAc,CAC1B,SAAuB;IAEvB,MAAM,iBAAiB,GAAiB,EAAE,CAAC;IAC3C,MAAM,cAAc,GAAiB,EAAE,CAAC;IAExC,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE;QAC9B,IAAI,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE;YACzB,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;SACpC;aAAM;YACH,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;SACjC;KACJ;IAED,OAAO,CAAC,cAAc,EAAE,iBAAiB,CAAC,CAAC;AAC/C,CAAC"}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { type Options as CSSSelectOptions } from "css-select";
|
||||
import type { Element, AnyNode, Document } from "domhandler";
|
||||
export { filters, pseudos, aliases } from "css-select";
|
||||
export interface Options extends CSSSelectOptions<AnyNode, Element> {
|
||||
/** Optional reference to the root of the document. If not set, this will be computed when needed. */
|
||||
root?: Document;
|
||||
}
|
||||
export declare function is(element: Element, selector: string | ((el: Element) => boolean), options?: Options): boolean;
|
||||
export declare function some(elements: Element[], selector: string | ((el: Element) => boolean), options?: Options): boolean;
|
||||
export declare function filter(selector: string, elements: AnyNode[], options?: Options): Element[];
|
||||
export declare function select(selector: string | ((el: Element) => boolean), root: AnyNode | AnyNode[], options?: Options, limit?: number): Element[];
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"https://raw.githubusercontent.com/cheeriojs/cheerio-select/ef063a6ca4c3f0d02d2fc3505e750b6fb81c448d/src/","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAEH,KAAK,OAAO,IAAI,gBAAgB,EAEnC,MAAM,YAAY,CAAC;AAGpB,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAU7D,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAYvD,MAAM,WAAW,OAAQ,SAAQ,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC;IAC/D,qGAAqG;IACrG,IAAI,CAAC,EAAE,QAAQ,CAAC;CACnB;AAED,wBAAgB,EAAE,CACd,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,OAAO,KAAK,OAAO,CAAC,EAC7C,OAAO,GAAE,OAAY,GACtB,OAAO,CAET;AAED,wBAAgB,IAAI,CAChB,QAAQ,EAAE,OAAO,EAAE,EACnB,QAAQ,EAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,OAAO,KAAK,OAAO,CAAC,EAC7C,OAAO,GAAE,OAAY,GACtB,OAAO,CAWT;AAsCD,wBAAgB,MAAM,CAClB,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,OAAO,EAAE,EACnB,OAAO,GAAE,OAAY,GACtB,OAAO,EAAE,CAEX;AAoGD,wBAAgB,MAAM,CAClB,QAAQ,EAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,OAAO,KAAK,OAAO,CAAC,EAC7C,IAAI,EAAE,OAAO,GAAG,OAAO,EAAE,EACzB,OAAO,GAAE,OAAY,EACrB,KAAK,SAAW,GACjB,OAAO,EAAE,CA2BX"}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
import { parse, SelectorType, isTraversal } from "css-what";
|
||||
import { _compileToken as compileToken, prepareContext, } from "css-select";
|
||||
import * as DomUtils from "domutils";
|
||||
import * as boolbase from "boolbase";
|
||||
import { getDocumentRoot, groupSelectors } from "./helpers.js";
|
||||
import { isFilter, getLimit, } from "./positionals.js";
|
||||
// Re-export pseudo extension points
|
||||
export { filters, pseudos, aliases } from "css-select";
|
||||
const UNIVERSAL_SELECTOR = {
|
||||
type: SelectorType.Universal,
|
||||
namespace: null,
|
||||
};
|
||||
const SCOPE_PSEUDO = {
|
||||
type: SelectorType.Pseudo,
|
||||
name: "scope",
|
||||
data: null,
|
||||
};
|
||||
export function is(element, selector, options = {}) {
|
||||
return some([element], selector, options);
|
||||
}
|
||||
export function some(elements, selector, options = {}) {
|
||||
if (typeof selector === "function")
|
||||
return elements.some(selector);
|
||||
const [plain, filtered] = groupSelectors(parse(selector));
|
||||
return ((plain.length > 0 && elements.some(compileToken(plain, options))) ||
|
||||
filtered.some((sel) => filterBySelector(sel, elements, options).length > 0));
|
||||
}
|
||||
function filterByPosition(filter, elems, data, options) {
|
||||
const num = typeof data === "string" ? parseInt(data, 10) : NaN;
|
||||
switch (filter) {
|
||||
case "first":
|
||||
case "lt":
|
||||
// Already done in `getLimit`
|
||||
return elems;
|
||||
case "last":
|
||||
return elems.length > 0 ? [elems[elems.length - 1]] : elems;
|
||||
case "nth":
|
||||
case "eq":
|
||||
return isFinite(num) && Math.abs(num) < elems.length
|
||||
? [num < 0 ? elems[elems.length + num] : elems[num]]
|
||||
: [];
|
||||
case "gt":
|
||||
return isFinite(num) ? elems.slice(num + 1) : [];
|
||||
case "even":
|
||||
return elems.filter((_, i) => i % 2 === 0);
|
||||
case "odd":
|
||||
return elems.filter((_, i) => i % 2 === 1);
|
||||
case "not": {
|
||||
const filtered = new Set(filterParsed(data, elems, options));
|
||||
return elems.filter((e) => !filtered.has(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
export function filter(selector, elements, options = {}) {
|
||||
return filterParsed(parse(selector), elements, options);
|
||||
}
|
||||
/**
|
||||
* Filter a set of elements by a selector.
|
||||
*
|
||||
* Will return elements in the original order.
|
||||
*
|
||||
* @param selector Selector to filter by.
|
||||
* @param elements Elements to filter.
|
||||
* @param options Options for selector.
|
||||
*/
|
||||
function filterParsed(selector, elements, options) {
|
||||
if (elements.length === 0)
|
||||
return [];
|
||||
const [plainSelectors, filteredSelectors] = groupSelectors(selector);
|
||||
let found;
|
||||
if (plainSelectors.length) {
|
||||
const filtered = filterElements(elements, plainSelectors, options);
|
||||
// If there are no filters, just return
|
||||
if (filteredSelectors.length === 0) {
|
||||
return filtered;
|
||||
}
|
||||
// Otherwise, we have to do some filtering
|
||||
if (filtered.length) {
|
||||
found = new Set(filtered);
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < filteredSelectors.length && (found === null || found === void 0 ? void 0 : found.size) !== elements.length; i++) {
|
||||
const filteredSelector = filteredSelectors[i];
|
||||
const missing = found
|
||||
? elements.filter((e) => DomUtils.isTag(e) && !found.has(e))
|
||||
: elements;
|
||||
if (missing.length === 0)
|
||||
break;
|
||||
const filtered = filterBySelector(filteredSelector, elements, options);
|
||||
if (filtered.length) {
|
||||
if (!found) {
|
||||
/*
|
||||
* If we haven't found anything before the last selector,
|
||||
* just return what we found now.
|
||||
*/
|
||||
if (i === filteredSelectors.length - 1) {
|
||||
return filtered;
|
||||
}
|
||||
found = new Set(filtered);
|
||||
}
|
||||
else {
|
||||
filtered.forEach((el) => found.add(el));
|
||||
}
|
||||
}
|
||||
}
|
||||
return typeof found !== "undefined"
|
||||
? (found.size === elements.length
|
||||
? elements
|
||||
: // Filter elements to preserve order
|
||||
elements.filter((el) => found.has(el)))
|
||||
: [];
|
||||
}
|
||||
function filterBySelector(selector, elements, options) {
|
||||
var _a;
|
||||
if (selector.some(isTraversal)) {
|
||||
/*
|
||||
* Get root node, run selector with the scope
|
||||
* set to all of our nodes.
|
||||
*/
|
||||
const root = (_a = options.root) !== null && _a !== void 0 ? _a : getDocumentRoot(elements[0]);
|
||||
const opts = { ...options, context: elements, relativeSelector: false };
|
||||
selector.push(SCOPE_PSEUDO);
|
||||
return findFilterElements(root, selector, opts, true, elements.length);
|
||||
}
|
||||
// Performance optimization: If we don't have to traverse, just filter set.
|
||||
return findFilterElements(elements, selector, options, false, elements.length);
|
||||
}
|
||||
export function select(selector, root, options = {}, limit = Infinity) {
|
||||
if (typeof selector === "function") {
|
||||
return find(root, selector);
|
||||
}
|
||||
const [plain, filtered] = groupSelectors(parse(selector));
|
||||
const results = filtered.map((sel) => findFilterElements(root, sel, options, true, limit));
|
||||
// Plain selectors can be queried in a single go
|
||||
if (plain.length) {
|
||||
results.push(findElements(root, plain, options, limit));
|
||||
}
|
||||
if (results.length === 0) {
|
||||
return [];
|
||||
}
|
||||
// If there was only a single selector, just return the result
|
||||
if (results.length === 1) {
|
||||
return results[0];
|
||||
}
|
||||
// Sort results, filtering for duplicates
|
||||
return DomUtils.uniqueSort(results.reduce((a, b) => [...a, ...b]));
|
||||
}
|
||||
/**
|
||||
*
|
||||
* @param root Element(s) to search from.
|
||||
* @param selector Selector to look for.
|
||||
* @param options Options for querying.
|
||||
* @param queryForSelector Query multiple levels deep for the initial selector, even if it doesn't contain a traversal.
|
||||
*/
|
||||
function findFilterElements(root, selector, options, queryForSelector, totalLimit) {
|
||||
const filterIndex = selector.findIndex(isFilter);
|
||||
const sub = selector.slice(0, filterIndex);
|
||||
const filter = selector[filterIndex];
|
||||
// If we are at the end of the selector, we can limit the number of elements to retrieve.
|
||||
const partLimit = selector.length - 1 === filterIndex ? totalLimit : Infinity;
|
||||
/*
|
||||
* Set the number of elements to retrieve.
|
||||
* Eg. for :first, we only have to get a single element.
|
||||
*/
|
||||
const limit = getLimit(filter.name, filter.data, partLimit);
|
||||
if (limit === 0)
|
||||
return [];
|
||||
/*
|
||||
* Skip `findElements` call if our selector starts with a positional
|
||||
* pseudo.
|
||||
*/
|
||||
const elemsNoLimit = sub.length === 0 && !Array.isArray(root)
|
||||
? DomUtils.getChildren(root).filter(DomUtils.isTag)
|
||||
: sub.length === 0
|
||||
? (Array.isArray(root) ? root : [root]).filter(DomUtils.isTag)
|
||||
: queryForSelector || sub.some(isTraversal)
|
||||
? findElements(root, [sub], options, limit)
|
||||
: filterElements(root, [sub], options);
|
||||
const elems = elemsNoLimit.slice(0, limit);
|
||||
let result = filterByPosition(filter.name, elems, filter.data, options);
|
||||
if (result.length === 0 || selector.length === filterIndex + 1) {
|
||||
return result;
|
||||
}
|
||||
const remainingSelector = selector.slice(filterIndex + 1);
|
||||
const remainingHasTraversal = remainingSelector.some(isTraversal);
|
||||
if (remainingHasTraversal) {
|
||||
if (isTraversal(remainingSelector[0])) {
|
||||
const { type } = remainingSelector[0];
|
||||
if (type === SelectorType.Sibling ||
|
||||
type === SelectorType.Adjacent) {
|
||||
// If we have a sibling traversal, we need to also look at the siblings.
|
||||
result = prepareContext(result, DomUtils, true);
|
||||
}
|
||||
// Avoid a traversal-first selector error.
|
||||
remainingSelector.unshift(UNIVERSAL_SELECTOR);
|
||||
}
|
||||
options = {
|
||||
...options,
|
||||
// Avoid absolutizing the selector
|
||||
relativeSelector: false,
|
||||
/*
|
||||
* Add a custom root func, to make sure traversals don't match elements
|
||||
* that aren't a part of the considered tree.
|
||||
*/
|
||||
rootFunc: (el) => result.includes(el),
|
||||
};
|
||||
}
|
||||
else if (options.rootFunc && options.rootFunc !== boolbase.trueFunc) {
|
||||
options = { ...options, rootFunc: boolbase.trueFunc };
|
||||
}
|
||||
/*
|
||||
* If we have another filter, recursively call `findFilterElements`,
|
||||
* with the `recursive` flag disabled. We only have to look for more
|
||||
* elements when we see a traversal.
|
||||
*
|
||||
* Otherwise,
|
||||
*/
|
||||
return remainingSelector.some(isFilter)
|
||||
? findFilterElements(result, remainingSelector, options, false, totalLimit)
|
||||
: remainingHasTraversal
|
||||
? // Query existing elements to resolve traversal.
|
||||
findElements(result, [remainingSelector], options, totalLimit)
|
||||
: // If we don't have any more traversals, simply filter elements.
|
||||
filterElements(result, [remainingSelector], options);
|
||||
}
|
||||
function findElements(root, sel, options, limit) {
|
||||
const query = compileToken(sel, options, root);
|
||||
return find(root, query, limit);
|
||||
}
|
||||
function find(root, query, limit = Infinity) {
|
||||
const elems = prepareContext(root, DomUtils, query.shouldTestNextSiblings);
|
||||
return DomUtils.find((node) => DomUtils.isTag(node) && query(node), elems, true, limit);
|
||||
}
|
||||
function filterElements(elements, sel, options) {
|
||||
const els = (Array.isArray(elements) ? elements : [elements]).filter(DomUtils.isTag);
|
||||
if (els.length === 0)
|
||||
return els;
|
||||
const query = compileToken(sel, options);
|
||||
return query === boolbase.trueFunc ? els : els.filter(query);
|
||||
}
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
{"type":"module"}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import type { Selector, PseudoSelector } from "css-what";
|
||||
export declare type Filter = "first" | "last" | "eq" | "nth" | "gt" | "lt" | "even" | "odd" | "not";
|
||||
export declare const filterNames: Set<string>;
|
||||
export interface CheerioSelector extends PseudoSelector {
|
||||
name: Filter;
|
||||
data: string | null;
|
||||
}
|
||||
export declare function isFilter(s: Selector): s is CheerioSelector;
|
||||
export declare function getLimit(filter: Filter, data: string | null, partLimit: number): number;
|
||||
//# sourceMappingURL=positionals.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"positionals.d.ts","sourceRoot":"https://raw.githubusercontent.com/cheeriojs/cheerio-select/ef063a6ca4c3f0d02d2fc3505e750b6fb81c448d/src/","sources":["positionals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAEzD,oBAAY,MAAM,GACZ,OAAO,GACP,MAAM,GACN,IAAI,GACJ,KAAK,GACL,IAAI,GACJ,IAAI,GACJ,MAAM,GACN,KAAK,GACL,KAAK,CAAC;AACZ,eAAO,MAAM,WAAW,EAAE,GAAG,CAAC,MAAM,CASlC,CAAC;AAEH,MAAM,WAAW,eAAgB,SAAQ,cAAc;IACnD,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AAED,wBAAgB,QAAQ,CAAC,CAAC,EAAE,QAAQ,GAAG,CAAC,IAAI,eAAe,CAS1D;AAED,wBAAgB,QAAQ,CACpB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,SAAS,EAAE,MAAM,GAClB,MAAM,CAyBR"}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
export const filterNames = new Set([
|
||||
"first",
|
||||
"last",
|
||||
"eq",
|
||||
"gt",
|
||||
"nth",
|
||||
"lt",
|
||||
"even",
|
||||
"odd",
|
||||
]);
|
||||
export function isFilter(s) {
|
||||
if (s.type !== "pseudo")
|
||||
return false;
|
||||
if (filterNames.has(s.name))
|
||||
return true;
|
||||
if (s.name === "not" && Array.isArray(s.data)) {
|
||||
// Only consider `:not` with embedded filters
|
||||
return s.data.some((s) => s.some(isFilter));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
export function getLimit(filter, data, partLimit) {
|
||||
const num = data != null ? parseInt(data, 10) : NaN;
|
||||
switch (filter) {
|
||||
case "first":
|
||||
return 1;
|
||||
case "nth":
|
||||
case "eq":
|
||||
return isFinite(num) ? (num >= 0 ? num + 1 : Infinity) : 0;
|
||||
case "lt":
|
||||
return isFinite(num)
|
||||
? num >= 0
|
||||
? Math.min(num, partLimit)
|
||||
: Infinity
|
||||
: 0;
|
||||
case "gt":
|
||||
return isFinite(num) ? Infinity : 0;
|
||||
case "odd":
|
||||
return 2 * partLimit;
|
||||
case "even":
|
||||
return 2 * partLimit - 1;
|
||||
case "last":
|
||||
case "not":
|
||||
return Infinity;
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=positionals.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"positionals.js","sourceRoot":"https://raw.githubusercontent.com/cheeriojs/cheerio-select/ef063a6ca4c3f0d02d2fc3505e750b6fb81c448d/src/","sources":["positionals.ts"],"names":[],"mappings":"AAYA,MAAM,CAAC,MAAM,WAAW,GAAgB,IAAI,GAAG,CAAS;IACpD,OAAO;IACP,MAAM;IACN,IAAI;IACJ,IAAI;IACJ,KAAK;IACL,IAAI;IACJ,MAAM;IACN,KAAK;CACR,CAAC,CAAC;AAOH,MAAM,UAAU,QAAQ,CAAC,CAAW;IAChC,IAAI,CAAC,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtC,IAAI,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IACzC,IAAI,CAAC,CAAC,IAAI,KAAK,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE;QAC3C,6CAA6C;QAC7C,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;KAC/C;IAED,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,MAAM,UAAU,QAAQ,CACpB,MAAc,EACd,IAAmB,EACnB,SAAiB;IAEjB,MAAM,GAAG,GAAG,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IAEpD,QAAQ,MAAM,EAAE;QACZ,KAAK,OAAO;YACR,OAAO,CAAC,CAAC;QACb,KAAK,KAAK,CAAC;QACX,KAAK,IAAI;YACL,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC/D,KAAK,IAAI;YACL,OAAO,QAAQ,CAAC,GAAG,CAAC;gBAChB,CAAC,CAAC,GAAG,IAAI,CAAC;oBACN,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,SAAS,CAAC;oBAC1B,CAAC,CAAC,QAAQ;gBACd,CAAC,CAAC,CAAC,CAAC;QACZ,KAAK,IAAI;YACL,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;QACxC,KAAK,KAAK;YACN,OAAO,CAAC,GAAG,SAAS,CAAC;QACzB,KAAK,MAAM;YACP,OAAO,CAAC,GAAG,SAAS,GAAG,CAAC,CAAC;QAC7B,KAAK,MAAM,CAAC;QACZ,KAAK,KAAK;YACN,OAAO,QAAQ,CAAC;KACvB;AACL,CAAC"}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import type { AnyNode } from "domhandler";
|
||||
import type { Selector } from "css-what";
|
||||
export declare function getDocumentRoot(node: AnyNode): AnyNode;
|
||||
export declare function groupSelectors(selectors: Selector[][]): [plain: Selector[][], filtered: Selector[][]];
|
||||
//# sourceMappingURL=helpers.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"helpers.d.ts","sourceRoot":"https://raw.githubusercontent.com/cheeriojs/cheerio-select/ef063a6ca4c3f0d02d2fc3505e750b6fb81c448d/src/","sources":["helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAGzC,wBAAgB,eAAe,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAGtD;AAED,wBAAgB,cAAc,CAC1B,SAAS,EAAE,QAAQ,EAAE,EAAE,GACxB,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,CAAC,CAa/C"}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.groupSelectors = exports.getDocumentRoot = void 0;
|
||||
var positionals_js_1 = require("./positionals.js");
|
||||
function getDocumentRoot(node) {
|
||||
while (node.parent)
|
||||
node = node.parent;
|
||||
return node;
|
||||
}
|
||||
exports.getDocumentRoot = getDocumentRoot;
|
||||
function groupSelectors(selectors) {
|
||||
var filteredSelectors = [];
|
||||
var plainSelectors = [];
|
||||
for (var _i = 0, selectors_1 = selectors; _i < selectors_1.length; _i++) {
|
||||
var selector = selectors_1[_i];
|
||||
if (selector.some(positionals_js_1.isFilter)) {
|
||||
filteredSelectors.push(selector);
|
||||
}
|
||||
else {
|
||||
plainSelectors.push(selector);
|
||||
}
|
||||
}
|
||||
return [plainSelectors, filteredSelectors];
|
||||
}
|
||||
exports.groupSelectors = groupSelectors;
|
||||
//# sourceMappingURL=helpers.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"helpers.js","sourceRoot":"https://raw.githubusercontent.com/cheeriojs/cheerio-select/ef063a6ca4c3f0d02d2fc3505e750b6fb81c448d/src/","sources":["helpers.ts"],"names":[],"mappings":";;;AAEA,mDAA4C;AAE5C,SAAgB,eAAe,CAAC,IAAa;IACzC,OAAO,IAAI,CAAC,MAAM;QAAE,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC;IACvC,OAAO,IAAI,CAAC;AAChB,CAAC;AAHD,0CAGC;AAED,SAAgB,cAAc,CAC1B,SAAuB;IAEvB,IAAM,iBAAiB,GAAiB,EAAE,CAAC;IAC3C,IAAM,cAAc,GAAiB,EAAE,CAAC;IAExC,KAAuB,UAAS,EAAT,uBAAS,EAAT,uBAAS,EAAT,IAAS,EAAE;QAA7B,IAAM,QAAQ,kBAAA;QACf,IAAI,QAAQ,CAAC,IAAI,CAAC,yBAAQ,CAAC,EAAE;YACzB,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;SACpC;aAAM;YACH,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;SACjC;KACJ;IAED,OAAO,CAAC,cAAc,EAAE,iBAAiB,CAAC,CAAC;AAC/C,CAAC;AAfD,wCAeC"}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { type Options as CSSSelectOptions } from "css-select";
|
||||
import type { Element, AnyNode, Document } from "domhandler";
|
||||
export { filters, pseudos, aliases } from "css-select";
|
||||
export interface Options extends CSSSelectOptions<AnyNode, Element> {
|
||||
/** Optional reference to the root of the document. If not set, this will be computed when needed. */
|
||||
root?: Document;
|
||||
}
|
||||
export declare function is(element: Element, selector: string | ((el: Element) => boolean), options?: Options): boolean;
|
||||
export declare function some(elements: Element[], selector: string | ((el: Element) => boolean), options?: Options): boolean;
|
||||
export declare function filter(selector: string, elements: AnyNode[], options?: Options): Element[];
|
||||
export declare function select(selector: string | ((el: Element) => boolean), root: AnyNode | AnyNode[], options?: Options, limit?: number): Element[];
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"https://raw.githubusercontent.com/cheeriojs/cheerio-select/ef063a6ca4c3f0d02d2fc3505e750b6fb81c448d/src/","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAEH,KAAK,OAAO,IAAI,gBAAgB,EAEnC,MAAM,YAAY,CAAC;AAGpB,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAU7D,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAYvD,MAAM,WAAW,OAAQ,SAAQ,gBAAgB,CAAC,OAAO,EAAE,OAAO,CAAC;IAC/D,qGAAqG;IACrG,IAAI,CAAC,EAAE,QAAQ,CAAC;CACnB;AAED,wBAAgB,EAAE,CACd,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,OAAO,KAAK,OAAO,CAAC,EAC7C,OAAO,GAAE,OAAY,GACtB,OAAO,CAET;AAED,wBAAgB,IAAI,CAChB,QAAQ,EAAE,OAAO,EAAE,EACnB,QAAQ,EAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,OAAO,KAAK,OAAO,CAAC,EAC7C,OAAO,GAAE,OAAY,GACtB,OAAO,CAWT;AAsCD,wBAAgB,MAAM,CAClB,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,OAAO,EAAE,EACnB,OAAO,GAAE,OAAY,GACtB,OAAO,EAAE,CAEX;AAoGD,wBAAgB,MAAM,CAClB,QAAQ,EAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,OAAO,KAAK,OAAO,CAAC,EAC7C,IAAI,EAAE,OAAO,GAAG,OAAO,EAAE,EACzB,OAAO,GAAE,OAAY,EACrB,KAAK,SAAW,GACjB,OAAO,EAAE,CA2BX"}
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
"use strict";
|
||||
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);
|
||||
};
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
|
||||
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
||||
if (ar || !(i in from)) {
|
||||
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
||||
ar[i] = from[i];
|
||||
}
|
||||
}
|
||||
return to.concat(ar || Array.prototype.slice.call(from));
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.select = exports.filter = exports.some = exports.is = exports.aliases = exports.pseudos = exports.filters = void 0;
|
||||
var css_what_1 = require("css-what");
|
||||
var css_select_1 = require("css-select");
|
||||
var DomUtils = __importStar(require("domutils"));
|
||||
var boolbase = __importStar(require("boolbase"));
|
||||
var helpers_js_1 = require("./helpers.js");
|
||||
var positionals_js_1 = require("./positionals.js");
|
||||
// Re-export pseudo extension points
|
||||
var css_select_2 = require("css-select");
|
||||
Object.defineProperty(exports, "filters", { enumerable: true, get: function () { return css_select_2.filters; } });
|
||||
Object.defineProperty(exports, "pseudos", { enumerable: true, get: function () { return css_select_2.pseudos; } });
|
||||
Object.defineProperty(exports, "aliases", { enumerable: true, get: function () { return css_select_2.aliases; } });
|
||||
var UNIVERSAL_SELECTOR = {
|
||||
type: css_what_1.SelectorType.Universal,
|
||||
namespace: null,
|
||||
};
|
||||
var SCOPE_PSEUDO = {
|
||||
type: css_what_1.SelectorType.Pseudo,
|
||||
name: "scope",
|
||||
data: null,
|
||||
};
|
||||
function is(element, selector, options) {
|
||||
if (options === void 0) { options = {}; }
|
||||
return some([element], selector, options);
|
||||
}
|
||||
exports.is = is;
|
||||
function some(elements, selector, options) {
|
||||
if (options === void 0) { options = {}; }
|
||||
if (typeof selector === "function")
|
||||
return elements.some(selector);
|
||||
var _a = (0, helpers_js_1.groupSelectors)((0, css_what_1.parse)(selector)), plain = _a[0], filtered = _a[1];
|
||||
return ((plain.length > 0 && elements.some((0, css_select_1._compileToken)(plain, options))) ||
|
||||
filtered.some(function (sel) { return filterBySelector(sel, elements, options).length > 0; }));
|
||||
}
|
||||
exports.some = some;
|
||||
function filterByPosition(filter, elems, data, options) {
|
||||
var num = typeof data === "string" ? parseInt(data, 10) : NaN;
|
||||
switch (filter) {
|
||||
case "first":
|
||||
case "lt":
|
||||
// Already done in `getLimit`
|
||||
return elems;
|
||||
case "last":
|
||||
return elems.length > 0 ? [elems[elems.length - 1]] : elems;
|
||||
case "nth":
|
||||
case "eq":
|
||||
return isFinite(num) && Math.abs(num) < elems.length
|
||||
? [num < 0 ? elems[elems.length + num] : elems[num]]
|
||||
: [];
|
||||
case "gt":
|
||||
return isFinite(num) ? elems.slice(num + 1) : [];
|
||||
case "even":
|
||||
return elems.filter(function (_, i) { return i % 2 === 0; });
|
||||
case "odd":
|
||||
return elems.filter(function (_, i) { return i % 2 === 1; });
|
||||
case "not": {
|
||||
var filtered_1 = new Set(filterParsed(data, elems, options));
|
||||
return elems.filter(function (e) { return !filtered_1.has(e); });
|
||||
}
|
||||
}
|
||||
}
|
||||
function filter(selector, elements, options) {
|
||||
if (options === void 0) { options = {}; }
|
||||
return filterParsed((0, css_what_1.parse)(selector), elements, options);
|
||||
}
|
||||
exports.filter = filter;
|
||||
/**
|
||||
* Filter a set of elements by a selector.
|
||||
*
|
||||
* Will return elements in the original order.
|
||||
*
|
||||
* @param selector Selector to filter by.
|
||||
* @param elements Elements to filter.
|
||||
* @param options Options for selector.
|
||||
*/
|
||||
function filterParsed(selector, elements, options) {
|
||||
if (elements.length === 0)
|
||||
return [];
|
||||
var _a = (0, helpers_js_1.groupSelectors)(selector), plainSelectors = _a[0], filteredSelectors = _a[1];
|
||||
var found;
|
||||
if (plainSelectors.length) {
|
||||
var filtered = filterElements(elements, plainSelectors, options);
|
||||
// If there are no filters, just return
|
||||
if (filteredSelectors.length === 0) {
|
||||
return filtered;
|
||||
}
|
||||
// Otherwise, we have to do some filtering
|
||||
if (filtered.length) {
|
||||
found = new Set(filtered);
|
||||
}
|
||||
}
|
||||
for (var i = 0; i < filteredSelectors.length && (found === null || found === void 0 ? void 0 : found.size) !== elements.length; i++) {
|
||||
var filteredSelector = filteredSelectors[i];
|
||||
var missing = found
|
||||
? elements.filter(function (e) { return DomUtils.isTag(e) && !found.has(e); })
|
||||
: elements;
|
||||
if (missing.length === 0)
|
||||
break;
|
||||
var filtered = filterBySelector(filteredSelector, elements, options);
|
||||
if (filtered.length) {
|
||||
if (!found) {
|
||||
/*
|
||||
* If we haven't found anything before the last selector,
|
||||
* just return what we found now.
|
||||
*/
|
||||
if (i === filteredSelectors.length - 1) {
|
||||
return filtered;
|
||||
}
|
||||
found = new Set(filtered);
|
||||
}
|
||||
else {
|
||||
filtered.forEach(function (el) { return found.add(el); });
|
||||
}
|
||||
}
|
||||
}
|
||||
return typeof found !== "undefined"
|
||||
? (found.size === elements.length
|
||||
? elements
|
||||
: // Filter elements to preserve order
|
||||
elements.filter(function (el) {
|
||||
return found.has(el);
|
||||
}))
|
||||
: [];
|
||||
}
|
||||
function filterBySelector(selector, elements, options) {
|
||||
var _a;
|
||||
if (selector.some(css_what_1.isTraversal)) {
|
||||
/*
|
||||
* Get root node, run selector with the scope
|
||||
* set to all of our nodes.
|
||||
*/
|
||||
var root = (_a = options.root) !== null && _a !== void 0 ? _a : (0, helpers_js_1.getDocumentRoot)(elements[0]);
|
||||
var opts = __assign(__assign({}, options), { context: elements, relativeSelector: false });
|
||||
selector.push(SCOPE_PSEUDO);
|
||||
return findFilterElements(root, selector, opts, true, elements.length);
|
||||
}
|
||||
// Performance optimization: If we don't have to traverse, just filter set.
|
||||
return findFilterElements(elements, selector, options, false, elements.length);
|
||||
}
|
||||
function select(selector, root, options, limit) {
|
||||
if (options === void 0) { options = {}; }
|
||||
if (limit === void 0) { limit = Infinity; }
|
||||
if (typeof selector === "function") {
|
||||
return find(root, selector);
|
||||
}
|
||||
var _a = (0, helpers_js_1.groupSelectors)((0, css_what_1.parse)(selector)), plain = _a[0], filtered = _a[1];
|
||||
var results = filtered.map(function (sel) {
|
||||
return findFilterElements(root, sel, options, true, limit);
|
||||
});
|
||||
// Plain selectors can be queried in a single go
|
||||
if (plain.length) {
|
||||
results.push(findElements(root, plain, options, limit));
|
||||
}
|
||||
if (results.length === 0) {
|
||||
return [];
|
||||
}
|
||||
// If there was only a single selector, just return the result
|
||||
if (results.length === 1) {
|
||||
return results[0];
|
||||
}
|
||||
// Sort results, filtering for duplicates
|
||||
return DomUtils.uniqueSort(results.reduce(function (a, b) { return __spreadArray(__spreadArray([], a, true), b, true); }));
|
||||
}
|
||||
exports.select = select;
|
||||
/**
|
||||
*
|
||||
* @param root Element(s) to search from.
|
||||
* @param selector Selector to look for.
|
||||
* @param options Options for querying.
|
||||
* @param queryForSelector Query multiple levels deep for the initial selector, even if it doesn't contain a traversal.
|
||||
*/
|
||||
function findFilterElements(root, selector, options, queryForSelector, totalLimit) {
|
||||
var filterIndex = selector.findIndex(positionals_js_1.isFilter);
|
||||
var sub = selector.slice(0, filterIndex);
|
||||
var filter = selector[filterIndex];
|
||||
// If we are at the end of the selector, we can limit the number of elements to retrieve.
|
||||
var partLimit = selector.length - 1 === filterIndex ? totalLimit : Infinity;
|
||||
/*
|
||||
* Set the number of elements to retrieve.
|
||||
* Eg. for :first, we only have to get a single element.
|
||||
*/
|
||||
var limit = (0, positionals_js_1.getLimit)(filter.name, filter.data, partLimit);
|
||||
if (limit === 0)
|
||||
return [];
|
||||
/*
|
||||
* Skip `findElements` call if our selector starts with a positional
|
||||
* pseudo.
|
||||
*/
|
||||
var elemsNoLimit = sub.length === 0 && !Array.isArray(root)
|
||||
? DomUtils.getChildren(root).filter(DomUtils.isTag)
|
||||
: sub.length === 0
|
||||
? (Array.isArray(root) ? root : [root]).filter(DomUtils.isTag)
|
||||
: queryForSelector || sub.some(css_what_1.isTraversal)
|
||||
? findElements(root, [sub], options, limit)
|
||||
: filterElements(root, [sub], options);
|
||||
var elems = elemsNoLimit.slice(0, limit);
|
||||
var result = filterByPosition(filter.name, elems, filter.data, options);
|
||||
if (result.length === 0 || selector.length === filterIndex + 1) {
|
||||
return result;
|
||||
}
|
||||
var remainingSelector = selector.slice(filterIndex + 1);
|
||||
var remainingHasTraversal = remainingSelector.some(css_what_1.isTraversal);
|
||||
if (remainingHasTraversal) {
|
||||
if ((0, css_what_1.isTraversal)(remainingSelector[0])) {
|
||||
var type = remainingSelector[0].type;
|
||||
if (type === css_what_1.SelectorType.Sibling ||
|
||||
type === css_what_1.SelectorType.Adjacent) {
|
||||
// If we have a sibling traversal, we need to also look at the siblings.
|
||||
result = (0, css_select_1.prepareContext)(result, DomUtils, true);
|
||||
}
|
||||
// Avoid a traversal-first selector error.
|
||||
remainingSelector.unshift(UNIVERSAL_SELECTOR);
|
||||
}
|
||||
options = __assign(__assign({}, options), {
|
||||
// Avoid absolutizing the selector
|
||||
relativeSelector: false,
|
||||
/*
|
||||
* Add a custom root func, to make sure traversals don't match elements
|
||||
* that aren't a part of the considered tree.
|
||||
*/
|
||||
rootFunc: function (el) { return result.includes(el); } });
|
||||
}
|
||||
else if (options.rootFunc && options.rootFunc !== boolbase.trueFunc) {
|
||||
options = __assign(__assign({}, options), { rootFunc: boolbase.trueFunc });
|
||||
}
|
||||
/*
|
||||
* If we have another filter, recursively call `findFilterElements`,
|
||||
* with the `recursive` flag disabled. We only have to look for more
|
||||
* elements when we see a traversal.
|
||||
*
|
||||
* Otherwise,
|
||||
*/
|
||||
return remainingSelector.some(positionals_js_1.isFilter)
|
||||
? findFilterElements(result, remainingSelector, options, false, totalLimit)
|
||||
: remainingHasTraversal
|
||||
? // Query existing elements to resolve traversal.
|
||||
findElements(result, [remainingSelector], options, totalLimit)
|
||||
: // If we don't have any more traversals, simply filter elements.
|
||||
filterElements(result, [remainingSelector], options);
|
||||
}
|
||||
function findElements(root, sel, options, limit) {
|
||||
var query = (0, css_select_1._compileToken)(sel, options, root);
|
||||
return find(root, query, limit);
|
||||
}
|
||||
function find(root, query, limit) {
|
||||
if (limit === void 0) { limit = Infinity; }
|
||||
var elems = (0, css_select_1.prepareContext)(root, DomUtils, query.shouldTestNextSiblings);
|
||||
return DomUtils.find(function (node) { return DomUtils.isTag(node) && query(node); }, elems, true, limit);
|
||||
}
|
||||
function filterElements(elements, sel, options) {
|
||||
var els = (Array.isArray(elements) ? elements : [elements]).filter(DomUtils.isTag);
|
||||
if (els.length === 0)
|
||||
return els;
|
||||
var query = (0, css_select_1._compileToken)(sel, options);
|
||||
return query === boolbase.trueFunc ? els : els.filter(query);
|
||||
}
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+10
@@ -0,0 +1,10 @@
|
||||
import type { Selector, PseudoSelector } from "css-what";
|
||||
export declare type Filter = "first" | "last" | "eq" | "nth" | "gt" | "lt" | "even" | "odd" | "not";
|
||||
export declare const filterNames: Set<string>;
|
||||
export interface CheerioSelector extends PseudoSelector {
|
||||
name: Filter;
|
||||
data: string | null;
|
||||
}
|
||||
export declare function isFilter(s: Selector): s is CheerioSelector;
|
||||
export declare function getLimit(filter: Filter, data: string | null, partLimit: number): number;
|
||||
//# sourceMappingURL=positionals.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"positionals.d.ts","sourceRoot":"https://raw.githubusercontent.com/cheeriojs/cheerio-select/ef063a6ca4c3f0d02d2fc3505e750b6fb81c448d/src/","sources":["positionals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAEzD,oBAAY,MAAM,GACZ,OAAO,GACP,MAAM,GACN,IAAI,GACJ,KAAK,GACL,IAAI,GACJ,IAAI,GACJ,MAAM,GACN,KAAK,GACL,KAAK,CAAC;AACZ,eAAO,MAAM,WAAW,EAAE,GAAG,CAAC,MAAM,CASlC,CAAC;AAEH,MAAM,WAAW,eAAgB,SAAQ,cAAc;IACnD,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AAED,wBAAgB,QAAQ,CAAC,CAAC,EAAE,QAAQ,GAAG,CAAC,IAAI,eAAe,CAS1D;AAED,wBAAgB,QAAQ,CACpB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,GAAG,IAAI,EACnB,SAAS,EAAE,MAAM,GAClB,MAAM,CAyBR"}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getLimit = exports.isFilter = exports.filterNames = void 0;
|
||||
exports.filterNames = new Set([
|
||||
"first",
|
||||
"last",
|
||||
"eq",
|
||||
"gt",
|
||||
"nth",
|
||||
"lt",
|
||||
"even",
|
||||
"odd",
|
||||
]);
|
||||
function isFilter(s) {
|
||||
if (s.type !== "pseudo")
|
||||
return false;
|
||||
if (exports.filterNames.has(s.name))
|
||||
return true;
|
||||
if (s.name === "not" && Array.isArray(s.data)) {
|
||||
// Only consider `:not` with embedded filters
|
||||
return s.data.some(function (s) { return s.some(isFilter); });
|
||||
}
|
||||
return false;
|
||||
}
|
||||
exports.isFilter = isFilter;
|
||||
function getLimit(filter, data, partLimit) {
|
||||
var num = data != null ? parseInt(data, 10) : NaN;
|
||||
switch (filter) {
|
||||
case "first":
|
||||
return 1;
|
||||
case "nth":
|
||||
case "eq":
|
||||
return isFinite(num) ? (num >= 0 ? num + 1 : Infinity) : 0;
|
||||
case "lt":
|
||||
return isFinite(num)
|
||||
? num >= 0
|
||||
? Math.min(num, partLimit)
|
||||
: Infinity
|
||||
: 0;
|
||||
case "gt":
|
||||
return isFinite(num) ? Infinity : 0;
|
||||
case "odd":
|
||||
return 2 * partLimit;
|
||||
case "even":
|
||||
return 2 * partLimit - 1;
|
||||
case "last":
|
||||
case "not":
|
||||
return Infinity;
|
||||
}
|
||||
}
|
||||
exports.getLimit = getLimit;
|
||||
//# sourceMappingURL=positionals.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"positionals.js","sourceRoot":"https://raw.githubusercontent.com/cheeriojs/cheerio-select/ef063a6ca4c3f0d02d2fc3505e750b6fb81c448d/src/","sources":["positionals.ts"],"names":[],"mappings":";;;AAYa,QAAA,WAAW,GAAgB,IAAI,GAAG,CAAS;IACpD,OAAO;IACP,MAAM;IACN,IAAI;IACJ,IAAI;IACJ,KAAK;IACL,IAAI;IACJ,MAAM;IACN,KAAK;CACR,CAAC,CAAC;AAOH,SAAgB,QAAQ,CAAC,CAAW;IAChC,IAAI,CAAC,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtC,IAAI,mBAAW,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IACzC,IAAI,CAAC,CAAC,IAAI,KAAK,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE;QAC3C,6CAA6C;QAC7C,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,UAAC,CAAC,IAAK,OAAA,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAhB,CAAgB,CAAC,CAAC;KAC/C;IAED,OAAO,KAAK,CAAC;AACjB,CAAC;AATD,4BASC;AAED,SAAgB,QAAQ,CACpB,MAAc,EACd,IAAmB,EACnB,SAAiB;IAEjB,IAAM,GAAG,GAAG,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;IAEpD,QAAQ,MAAM,EAAE;QACZ,KAAK,OAAO;YACR,OAAO,CAAC,CAAC;QACb,KAAK,KAAK,CAAC;QACX,KAAK,IAAI;YACL,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC/D,KAAK,IAAI;YACL,OAAO,QAAQ,CAAC,GAAG,CAAC;gBAChB,CAAC,CAAC,GAAG,IAAI,CAAC;oBACN,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,SAAS,CAAC;oBAC1B,CAAC,CAAC,QAAQ;gBACd,CAAC,CAAC,CAAC,CAAC;QACZ,KAAK,IAAI;YACL,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;QACxC,KAAK,KAAK;YACN,OAAO,CAAC,GAAG,SAAS,CAAC;QACzB,KAAK,MAAM;YACP,OAAO,CAAC,GAAG,SAAS,GAAG,CAAC,CAAC;QAC7B,KAAK,MAAM,CAAC;QACZ,KAAK,KAAK;YACN,OAAO,QAAQ,CAAC;KACvB;AACL,CAAC;AA7BD,4BA6BC"}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"name": "cheerio-select",
|
||||
"description": "CSS selector engine supporting jQuery selectors",
|
||||
"version": "2.1.0",
|
||||
"author": "Felix Boehm <me@feedic.com>",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/fb55"
|
||||
},
|
||||
"license": "BSD-2-Clause",
|
||||
"sideEffects": false,
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/cheeriojs/cheerio-select.git"
|
||||
},
|
||||
"directories": {
|
||||
"lib": "lib/"
|
||||
},
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/index.d.ts",
|
||||
"module": "lib/esm/index.js",
|
||||
"exports": {
|
||||
"require": "./lib/index.js",
|
||||
"import": "./lib/esm/index.js"
|
||||
},
|
||||
"files": [
|
||||
"lib/**/*"
|
||||
],
|
||||
"scripts": {
|
||||
"test": "npm run test:jest && npm run lint",
|
||||
"test:jest": "jest",
|
||||
"lint": "npm run lint:es && npm run lint:prettier",
|
||||
"lint:es": "eslint src",
|
||||
"lint:prettier": "npm run format:prettier:raw -- --check",
|
||||
"format": "npm run format:es && npm run format:prettier",
|
||||
"format:es": "npm run lint:es -- --fix",
|
||||
"format:prettier": "npm run format:prettier:raw -- --write",
|
||||
"format:prettier:raw": "prettier '**/*.{ts,md,json,yml}'",
|
||||
"build": "npm run build:cjs && npm run build:esm",
|
||||
"build:cjs": "tsc --sourceRoot https://raw.githubusercontent.com/cheeriojs/cheerio-select/$(git rev-parse HEAD)/src/",
|
||||
"build:esm": "npm run build:cjs -- --module esnext --target es2019 --outDir lib/esm && echo '{\"type\":\"module\"}' > lib/esm/package.json",
|
||||
"prepare": "npm run build"
|
||||
},
|
||||
"dependencies": {
|
||||
"boolbase": "^1.0.0",
|
||||
"css-select": "^5.1.0",
|
||||
"css-what": "^6.1.0",
|
||||
"domelementtype": "^2.3.0",
|
||||
"domhandler": "^5.0.3",
|
||||
"domutils": "^3.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/boolbase": "^1.0.1",
|
||||
"@types/jest": "^27.5.0",
|
||||
"@types/node": "^17.0.33",
|
||||
"@typescript-eslint/eslint-plugin": "^5.23.0",
|
||||
"@typescript-eslint/parser": "^5.23.0",
|
||||
"eslint": "^8.15.0",
|
||||
"eslint-config-prettier": "^8.5.0",
|
||||
"htmlparser2": "^8.0.1",
|
||||
"jest": "^27.5.1",
|
||||
"prettier": "^2.6.2",
|
||||
"ts-jest": "^27.1.4",
|
||||
"typescript": "^4.6.4"
|
||||
},
|
||||
"jest": {
|
||||
"preset": "ts-jest",
|
||||
"testEnvironment": "node",
|
||||
"coverageProvider": "v8",
|
||||
"moduleNameMapper": {
|
||||
"^(.*)\\.js$": "$1"
|
||||
}
|
||||
},
|
||||
"prettier": {
|
||||
"tabWidth": 4
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 The Cheerio 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.
|
||||
+229
@@ -0,0 +1,229 @@
|
||||
<h1 align="center">cheerio</h1>
|
||||
|
||||
<h5 align="center">The fast, flexible, and elegant library for parsing and manipulating HTML and XML.</h5>
|
||||
|
||||
<div align="center">
|
||||
<a href="https://github.com/cheeriojs/cheerio/actions/workflows/ci.yml">
|
||||
<img src="https://github.com/cheeriojs/cheerio/actions/workflows/ci.yml/badge.svg" alt="Build Status">
|
||||
</a>
|
||||
<a href="https://coveralls.io/github/cheeriojs/cheerio">
|
||||
<img src="https://img.shields.io/coveralls/github/cheeriojs/cheerio/main" alt="Coverage">
|
||||
</a>
|
||||
<a href="#backers">
|
||||
<img src="https://img.shields.io/opencollective/backers/cheerio" alt="OpenCollective backers">
|
||||
</a>
|
||||
<a href="#sponsors">
|
||||
<img src="https://img.shields.io/opencollective/sponsors/cheerio" alt="OpenCollective sponsors">
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<br>
|
||||
|
||||
[中文文档 (Chinese Readme)](https://github.com/cheeriojs/cheerio/wiki/Chinese-README)
|
||||
|
||||
```js
|
||||
import * as cheerio from 'cheerio';
|
||||
const $ = cheerio.load('<h2 class="title">Hello world</h2>');
|
||||
|
||||
$('h2.title').text('Hello there!');
|
||||
$('h2').addClass('welcome');
|
||||
|
||||
$.html();
|
||||
//=> <html><head></head><body><h2 class="title welcome">Hello there!</h2></body></html>
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
Install Cheerio using a package manager like npm, yarn, or bun.
|
||||
|
||||
```bash
|
||||
npm install cheerio
|
||||
# or
|
||||
bun add cheerio
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
**❤ Proven syntax:** Cheerio implements a subset of core jQuery. Cheerio
|
||||
removes all the DOM inconsistencies and browser cruft from the jQuery library,
|
||||
revealing its truly gorgeous API.
|
||||
|
||||
**ϟ Blazingly fast:** Cheerio works with a very simple, consistent DOM
|
||||
model. As a result parsing, manipulating, and rendering are incredibly
|
||||
efficient.
|
||||
|
||||
**❁ Incredibly flexible:** Cheerio wraps around
|
||||
[parse5](https://github.com/inikulin/parse5) for parsing HTML and can optionally
|
||||
use the forgiving [htmlparser2](https://github.com/fb55/htmlparser2/). Cheerio
|
||||
can parse nearly any HTML or XML document. Cheerio works in both browser and
|
||||
server environments.
|
||||
|
||||
## API
|
||||
|
||||
### Loading
|
||||
|
||||
First you need to load in the HTML. This step in jQuery is implicit, since
|
||||
jQuery operates on the one, baked-in DOM. With Cheerio, we need to pass in the
|
||||
HTML document.
|
||||
|
||||
```js
|
||||
// ESM or TypeScript:
|
||||
import * as cheerio from 'cheerio';
|
||||
|
||||
// In other environments:
|
||||
const cheerio = require('cheerio');
|
||||
|
||||
const $ = cheerio.load('<ul id="fruits">...</ul>');
|
||||
|
||||
$.html();
|
||||
//=> <html><head></head><body><ul id="fruits">...</ul></body></html>
|
||||
```
|
||||
|
||||
### Selectors
|
||||
|
||||
Once you've loaded the HTML, you can use jQuery-style selectors to find elements
|
||||
within the document.
|
||||
|
||||
#### \$( selector, [context], [root] )
|
||||
|
||||
`selector` searches within the `context` scope which searches within the `root`
|
||||
scope. `selector` and `context` can be a string expression, DOM Element, array
|
||||
of DOM elements, or cheerio object. `root`, if provided, is typically the HTML
|
||||
document string.
|
||||
|
||||
This selector method is the starting point for traversing and manipulating the
|
||||
document. Like in jQuery, it's the primary method for selecting elements in the
|
||||
document.
|
||||
|
||||
```js
|
||||
$('.apple', '#fruits').text();
|
||||
//=> Apple
|
||||
|
||||
$('ul .pear').attr('class');
|
||||
//=> pear
|
||||
|
||||
$('li[class=orange]').html();
|
||||
//=> Orange
|
||||
```
|
||||
|
||||
### Rendering
|
||||
|
||||
When you're ready to render the document, you can call the `html` method on the
|
||||
"root" selection:
|
||||
|
||||
```js
|
||||
$.root().html();
|
||||
//=> <html>
|
||||
// <head></head>
|
||||
// <body>
|
||||
// <ul id="fruits">
|
||||
// <li class="apple">Apple</li>
|
||||
// <li class="orange">Orange</li>
|
||||
// <li class="pear">Pear</li>
|
||||
// </ul>
|
||||
// </body>
|
||||
// </html>
|
||||
```
|
||||
|
||||
If you want to render the
|
||||
[`outerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML)
|
||||
of a selection, you can use the `outerHTML` prop:
|
||||
|
||||
```js
|
||||
$('.pear').prop('outerHTML');
|
||||
//=> <li class="pear">Pear</li>
|
||||
```
|
||||
|
||||
You may also render the text content of a Cheerio object using the `text`
|
||||
method:
|
||||
|
||||
```js
|
||||
const $ = cheerio.load('This is <em>content</em>.');
|
||||
$('body').text();
|
||||
//=> This is content.
|
||||
```
|
||||
|
||||
### The "DOM Node" object
|
||||
|
||||
Cheerio collections are made up of objects that bear some resemblance to
|
||||
[browser-based DOM nodes](https://developer.mozilla.org/en-US/docs/Web/API/Node).
|
||||
You can expect them to define the following properties:
|
||||
|
||||
- `tagName`
|
||||
- `parentNode`
|
||||
- `previousSibling`
|
||||
- `nextSibling`
|
||||
- `nodeValue`
|
||||
- `firstChild`
|
||||
- `childNodes`
|
||||
- `lastChild`
|
||||
|
||||
## Screencasts
|
||||
|
||||
[https://vimeo.com/31950192](https://vimeo.com/31950192)
|
||||
|
||||
> This video tutorial is a follow-up to Nettut's "How to Scrape Web Pages with
|
||||
> Node.js and jQuery", using cheerio instead of JSDOM + jQuery. This video shows
|
||||
> how easy it is to use cheerio and how much faster cheerio is than JSDOM +
|
||||
> jQuery.
|
||||
|
||||
## Cheerio in the real world
|
||||
|
||||
Are you using cheerio in production? Add it to the
|
||||
[wiki](https://github.com/cheeriojs/cheerio/wiki/Cheerio-in-Production)!
|
||||
|
||||
## Sponsors
|
||||
|
||||
Does your company use Cheerio in production? Please consider
|
||||
[sponsoring this project](https://github.com/cheeriojs/cheerio?sponsor=1)! Your
|
||||
help will allow maintainers to dedicate more time and resources to its
|
||||
development and support.
|
||||
|
||||
**Headlining Sponsors**
|
||||
|
||||
<!-- BEGIN SPONSORS: headliner -->
|
||||
|
||||
<a href="https://tidelift.com/subscription/pkg/npm-cheerio" target="_blank" rel="noopener noreferrer">
|
||||
<img height="128px" width="128px" src="https://humble.imgix.net/https%3A%2F%2Fgithub.com%2Ftidelift.png?ixlib=js-3.8.0&w=128&h=128&fit=fillmax&fill=solid&s=0713e6ee5c7ab01e7559df695c1e8cd9" title="Tidelift" alt="Tidelift"></img>
|
||||
</a>
|
||||
<a href="https://github.com/" target="_blank" rel="noopener noreferrer">
|
||||
<img height="128px" width="128px" src="https://humble.imgix.net/https%3A%2F%2Fgithub.com%2Fgithub.png?ixlib=js-3.8.0&w=128&h=128&fit=fillmax&fill=solid&s=a1e87ca289de84eb32ea85432cf8ad11" title="Github" alt="Github"></img>
|
||||
</a>
|
||||
<a href="https://www.airbnb.com/" target="_blank" rel="noopener noreferrer">
|
||||
<img height="128px" width="128px" src="https://humble.imgix.net/https%3A%2F%2Fgithub.com%2Fairbnb.png?ixlib=js-3.8.0&w=128&h=128&fit=fillmax&fill=solid&s=384cad45e10faea516202ad10801f895" title="AirBnB" alt="AirBnB"></img>
|
||||
</a>
|
||||
<a href="https://hasdata.com" target="_blank" rel="noopener noreferrer">
|
||||
<img height="128px" width="128px" src="https://humble.imgix.net/https%3A%2F%2Fhasdata.com%2Ffavicon.svg?ixlib=js-3.8.0&w=128&h=128&fit=fillmax&fill=solid&s=21933842d61dec74a961fc57754e58cb" title="HasData" alt="HasData"></img>
|
||||
</a>
|
||||
|
||||
<!-- END SPONSORS -->
|
||||
|
||||
**Other Sponsors**
|
||||
|
||||
<!-- BEGIN SPONSORS: sponsor -->
|
||||
|
||||
<a href="https://onlinecasinosspelen.com" target="_blank" rel="noopener noreferrer">
|
||||
<img height="64px" width="64px" src="https://humble.imgix.net/https%3A%2F%2Fimages.opencollective.com%2Fonlinecasinosspelen%2F99ac6a2%2Flogo.png?ixlib=js-3.8.0&w=64&h=64&fit=fillmax&fill=solid&s=8ec1ec058845b823858f22205485be02" title="OnlineCasinosSpelen" alt="OnlineCasinosSpelen"></img>
|
||||
</a>
|
||||
<a href="https://Nieuwe-Casinos.net" target="_blank" rel="noopener noreferrer">
|
||||
<img height="64px" width="64px" src="https://humble.imgix.net/https%3A%2F%2Fimages.opencollective.com%2Fnieuwecasinos%2Fc67d423%2Flogo.png?ixlib=js-3.8.0&w=64&h=64&fit=fillmax&fill=solid&s=ed55d86b80b1aa8cf89b033020521945" title="Nieuwe-Casinos.net" alt="Nieuwe-Casinos.net"></img>
|
||||
</a>
|
||||
|
||||
<!-- END SPONSORS -->
|
||||
|
||||
## Backers
|
||||
|
||||
[Become a backer](https://github.com/cheeriojs/cheerio?sponsor=1) to show your
|
||||
support for Cheerio and help us maintain and improve this open source project.
|
||||
|
||||
<!-- BEGIN SPONSORS: backer -->
|
||||
|
||||
<a href="https://kafidoff.com" target="_blank" rel="noopener noreferrer">
|
||||
<img height="64px" width="64px" src="https://humble.imgix.net/https%3A%2F%2Fimages.opencollective.com%2Fkafidoff-vasy%2Fd7ff85c%2Favatar.png?ixlib=js-3.8.0&w=64&h=64&fit=fillmax&fill=solid&s=a41c66c2f9b1d3a7a241e425e7aa2d09" title="Vasy Kafidoff" alt="Vasy Kafidoff"></img>
|
||||
</a>
|
||||
|
||||
<!-- END SPONSORS -->
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
+385
@@ -0,0 +1,385 @@
|
||||
/**
|
||||
* Methods for getting and modifying attributes.
|
||||
*
|
||||
* @module cheerio/attributes
|
||||
*/
|
||||
import { type AnyNode, type Element } from 'domhandler';
|
||||
import type { Cheerio } from '../cheerio.js';
|
||||
/**
|
||||
* Method for getting attributes. Gets the attribute value for only the first
|
||||
* element in the matched set.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('ul').attr('id');
|
||||
* //=> fruits
|
||||
* ```
|
||||
*
|
||||
* @param name - Name of the attribute.
|
||||
* @returns The attribute's value.
|
||||
* @see {@link https://api.jquery.com/attr/}
|
||||
*/
|
||||
export declare function attr<T extends AnyNode>(this: Cheerio<T>, name: string): string | undefined;
|
||||
/**
|
||||
* Method for getting all attributes and their values of the first element in
|
||||
* the matched set.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('ul').attr();
|
||||
* //=> { id: 'fruits' }
|
||||
* ```
|
||||
*
|
||||
* @returns The attribute's values.
|
||||
* @see {@link https://api.jquery.com/attr/}
|
||||
*/
|
||||
export declare function attr<T extends AnyNode>(this: Cheerio<T>): Record<string, string> | undefined;
|
||||
/**
|
||||
* Method for setting attributes. Sets the attribute value for all elements in
|
||||
* the matched set. If you set an attribute's value to `null`, you remove that
|
||||
* attribute. You may also pass a `map` and `function`.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('.apple').attr('id', 'favorite').prop('outerHTML');
|
||||
* //=> <li class="apple" id="favorite">Apple</li>
|
||||
* ```
|
||||
*
|
||||
* @param name - Name of the attribute.
|
||||
* @param value - The new value of the attribute.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/attr/}
|
||||
*/
|
||||
export declare function attr<T extends AnyNode>(this: Cheerio<T>, name: string, value?: string | null | ((this: Element, i: number, attrib: string) => string | null)): Cheerio<T>;
|
||||
/**
|
||||
* Method for setting multiple attributes at once. Sets the attribute value for
|
||||
* all elements in the matched set. If you set an attribute's value to `null`,
|
||||
* you remove that attribute.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('.apple').attr({ id: 'favorite' }).prop('outerHTML');
|
||||
* //=> <li class="apple" id="favorite">Apple</li>
|
||||
* ```
|
||||
*
|
||||
* @param values - Map of attribute names and values.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/attr/}
|
||||
*/
|
||||
export declare function attr<T extends AnyNode>(this: Cheerio<T>, values: Record<string, string | null>): Cheerio<T>;
|
||||
interface StyleProp {
|
||||
length: number;
|
||||
[key: string]: string | number;
|
||||
[index: number]: string;
|
||||
}
|
||||
/**
|
||||
* Method for getting and setting properties. Gets the property value for only
|
||||
* the first element in the matched set.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('input[type="checkbox"]').prop('checked');
|
||||
* //=> false
|
||||
*
|
||||
* $('input[type="checkbox"]').prop('checked', true).val();
|
||||
* //=> ok
|
||||
* ```
|
||||
*
|
||||
* @param name - Name of the property.
|
||||
* @returns If `value` is specified the instance itself, otherwise the prop's
|
||||
* value.
|
||||
* @see {@link https://api.jquery.com/prop/}
|
||||
*/
|
||||
export declare function prop<T extends AnyNode>(this: Cheerio<T>, name: 'tagName' | 'nodeName'): string | undefined;
|
||||
export declare function prop<T extends AnyNode>(this: Cheerio<T>, name: 'innerHTML' | 'outerHTML' | 'innerText' | 'textContent'): string | null;
|
||||
/**
|
||||
* Get a parsed CSS style object.
|
||||
*
|
||||
* @param name - Name of the property.
|
||||
* @returns The style object, or `undefined` if the element has no `style`
|
||||
* attribute.
|
||||
*/
|
||||
export declare function prop<T extends AnyNode>(this: Cheerio<T>, name: 'style'): StyleProp | undefined;
|
||||
/**
|
||||
* Resolve `href` or `src` of supported elements. Requires the `baseURI` option
|
||||
* to be set, and a global `URL` object to be part of the environment.
|
||||
*
|
||||
* @example With `baseURI` set to `'https://example.com'`:
|
||||
*
|
||||
* ```js
|
||||
* $('<img src="image.png">').prop('src');
|
||||
* //=> 'https://example.com/image.png'
|
||||
* ```
|
||||
*
|
||||
* @param name - Name of the property.
|
||||
* @returns The resolved URL, or `undefined` if the element is not supported.
|
||||
*/
|
||||
export declare function prop<T extends AnyNode>(this: Cheerio<T>, name: 'href' | 'src'): string | undefined;
|
||||
/**
|
||||
* Get a property of an element.
|
||||
*
|
||||
* @param name - Name of the property.
|
||||
* @returns The property's value.
|
||||
*/
|
||||
export declare function prop<T extends AnyNode, K extends keyof Element>(this: Cheerio<T>, name: K): Element[K];
|
||||
/**
|
||||
* Set a property of an element.
|
||||
*
|
||||
* @param name - Name of the property.
|
||||
* @param value - Value to set the property to.
|
||||
* @returns The instance itself.
|
||||
*/
|
||||
export declare function prop<T extends AnyNode, K extends keyof Element>(this: Cheerio<T>, name: K, value: Element[K] | ((this: Element, i: number, prop: K) => Element[keyof Element])): Cheerio<T>;
|
||||
/**
|
||||
* Set multiple properties of an element.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('input[type="checkbox"]').prop({
|
||||
* checked: true,
|
||||
* disabled: false,
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param map - Object of properties to set.
|
||||
* @returns The instance itself.
|
||||
*/
|
||||
export declare function prop<T extends AnyNode>(this: Cheerio<T>, map: Record<string, string | Element[keyof Element] | boolean>): Cheerio<T>;
|
||||
/**
|
||||
* Set a property of an element.
|
||||
*
|
||||
* @param name - Name of the property.
|
||||
* @param value - Value to set the property to.
|
||||
* @returns The instance itself.
|
||||
*/
|
||||
export declare function prop<T extends AnyNode>(this: Cheerio<T>, name: string, value: string | boolean | null | ((this: Element, i: number, prop: string) => string | boolean)): Cheerio<T>;
|
||||
/**
|
||||
* Get a property of an element.
|
||||
*
|
||||
* @param name - The property's name.
|
||||
* @returns The property's value.
|
||||
*/
|
||||
export declare function prop<T extends AnyNode>(this: Cheerio<T>, name: string): string;
|
||||
/**
|
||||
* Method for getting data attributes, for only the first element in the matched
|
||||
* set.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('<div data-apple-color="red"></div>').data('apple-color');
|
||||
* //=> 'red'
|
||||
* ```
|
||||
*
|
||||
* @param name - Name of the data attribute.
|
||||
* @returns The data attribute's value, or `undefined` if the attribute does not
|
||||
* exist.
|
||||
* @see {@link https://api.jquery.com/data/}
|
||||
*/
|
||||
export declare function data<T extends AnyNode>(this: Cheerio<T>, name: string): unknown;
|
||||
/**
|
||||
* Method for getting all of an element's data attributes, for only the first
|
||||
* element in the matched set.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('<div data-apple-color="red"></div>').data();
|
||||
* //=> { appleColor: 'red' }
|
||||
* ```
|
||||
*
|
||||
* @returns A map with all of the data attributes.
|
||||
* @see {@link https://api.jquery.com/data/}
|
||||
*/
|
||||
export declare function data<T extends AnyNode>(this: Cheerio<T>): Record<string, unknown>;
|
||||
/**
|
||||
* Method for setting data attributes, for only the first element in the matched
|
||||
* set.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* const apple = $('.apple').data('kind', 'mac');
|
||||
*
|
||||
* apple.data('kind');
|
||||
* //=> 'mac'
|
||||
* ```
|
||||
*
|
||||
* @param name - Name of the data attribute.
|
||||
* @param value - The new value.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/data/}
|
||||
*/
|
||||
export declare function data<T extends AnyNode>(this: Cheerio<T>, name: string, value: unknown): Cheerio<T>;
|
||||
/**
|
||||
* Method for setting multiple data attributes at once, for only the first
|
||||
* element in the matched set.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* const apple = $('.apple').data({ kind: 'mac' });
|
||||
*
|
||||
* apple.data('kind');
|
||||
* //=> 'mac'
|
||||
* ```
|
||||
*
|
||||
* @param values - Map of names to values.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/data/}
|
||||
*/
|
||||
export declare function data<T extends AnyNode>(this: Cheerio<T>, values: Record<string, unknown>): Cheerio<T>;
|
||||
/**
|
||||
* Method for getting the value of input, select, and textarea. Note: Support
|
||||
* for `map`, and `function` has not been added yet.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('input[type="text"]').val();
|
||||
* //=> input_text
|
||||
* ```
|
||||
*
|
||||
* @returns The value.
|
||||
* @see {@link https://api.jquery.com/val/}
|
||||
*/
|
||||
export declare function val<T extends AnyNode>(this: Cheerio<T>): string | undefined | string[];
|
||||
/**
|
||||
* Method for setting the value of input, select, and textarea. Note: Support
|
||||
* for `map`, and `function` has not been added yet.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('input[type="text"]').val('test').prop('outerHTML');
|
||||
* //=> <input type="text" value="test"/>
|
||||
* ```
|
||||
*
|
||||
* @param value - The new value.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/val/}
|
||||
*/
|
||||
export declare function val<T extends AnyNode>(this: Cheerio<T>, value: string | string[]): Cheerio<T>;
|
||||
/**
|
||||
* Method for removing attributes by `name`.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('.pear').removeAttr('class').prop('outerHTML');
|
||||
* //=> <li>Pear</li>
|
||||
*
|
||||
* $('.apple').attr('id', 'favorite');
|
||||
* $('.apple').removeAttr('id class').prop('outerHTML');
|
||||
* //=> <li>Apple</li>
|
||||
* ```
|
||||
*
|
||||
* @param name - Name of the attribute.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/removeAttr/}
|
||||
*/
|
||||
export declare function removeAttr<T extends AnyNode>(this: Cheerio<T>, name: string): Cheerio<T>;
|
||||
/**
|
||||
* Check to see if _any_ of the matched elements have the given `className`.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('.pear').hasClass('pear');
|
||||
* //=> true
|
||||
*
|
||||
* $('apple').hasClass('fruit');
|
||||
* //=> false
|
||||
*
|
||||
* $('li').hasClass('pear');
|
||||
* //=> true
|
||||
* ```
|
||||
*
|
||||
* @param className - Name of the class.
|
||||
* @returns Indicates if an element has the given `className`.
|
||||
* @see {@link https://api.jquery.com/hasClass/}
|
||||
*/
|
||||
export declare function hasClass<T extends AnyNode>(this: Cheerio<T>, className: string): boolean;
|
||||
/**
|
||||
* Adds class(es) to all of the matched elements. Also accepts a `function`.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('.pear').addClass('fruit').prop('outerHTML');
|
||||
* //=> <li class="pear fruit">Pear</li>
|
||||
*
|
||||
* $('.apple').addClass('fruit red').prop('outerHTML');
|
||||
* //=> <li class="apple fruit red">Apple</li>
|
||||
* ```
|
||||
*
|
||||
* @param value - Name of new class.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/addClass/}
|
||||
*/
|
||||
export declare function addClass<T extends AnyNode, R extends ArrayLike<T>>(this: R, value?: string | ((this: Element, i: number, className: string) => string | undefined)): R;
|
||||
/**
|
||||
* Removes one or more space-separated classes from the selected elements. If no
|
||||
* `className` is defined, all classes will be removed. Also accepts a
|
||||
* `function`.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('.pear').removeClass('pear').prop('outerHTML');
|
||||
* //=> <li class="">Pear</li>
|
||||
*
|
||||
* $('.apple').addClass('red').removeClass().prop('outerHTML');
|
||||
* //=> <li class="">Apple</li>
|
||||
* ```
|
||||
*
|
||||
* @param name - Name of the class. If not specified, removes all elements.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/removeClass/}
|
||||
*/
|
||||
export declare function removeClass<T extends AnyNode, R extends ArrayLike<T>>(this: R, name?: string | ((this: Element, i: number, className: string) => string | undefined)): R;
|
||||
/**
|
||||
* Add or remove class(es) from the matched elements, depending on either the
|
||||
* class's presence or the value of the switch argument. Also accepts a
|
||||
* `function`.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('.apple.green').toggleClass('fruit green red').prop('outerHTML');
|
||||
* //=> <li class="apple fruit red">Apple</li>
|
||||
*
|
||||
* $('.apple.green').toggleClass('fruit green red', true).prop('outerHTML');
|
||||
* //=> <li class="apple green fruit red">Apple</li>
|
||||
* ```
|
||||
*
|
||||
* @param value - Name of the class. Can also be a function.
|
||||
* @param stateVal - If specified the state of the class.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/toggleClass/}
|
||||
*/
|
||||
export declare function toggleClass<T extends AnyNode, R extends ArrayLike<T>>(this: R, value?: string | ((this: Element, i: number, className: string, stateVal?: boolean) => string), stateVal?: boolean): R;
|
||||
export {};
|
||||
//# sourceMappingURL=attributes.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"attributes.d.ts","sourceRoot":"","sources":["../../../src/api/attributes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,EAAS,KAAK,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,YAAY,CAAC;AAC/D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AA6F7C;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,MAAM,GACX,MAAM,GAAG,SAAS,CAAC;AACtB;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,GACf,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAAC;AACtC;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,MAAM,EACZ,KAAK,CAAC,EACF,MAAM,GACN,IAAI,GACJ,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,CAAC,GAChE,OAAO,CAAC,CAAC,CAAC,CAAC;AACd;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,GACpC,OAAO,CAAC,CAAC,CAAC,CAAC;AAyFd,UAAU,SAAS;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IAC/B,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,SAAS,GAAG,UAAU,GAC3B,MAAM,GAAG,SAAS,CAAC;AACtB,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,WAAW,GAAG,WAAW,GAAG,WAAW,GAAG,aAAa,GAC5D,MAAM,GAAG,IAAI,CAAC;AACjB;;;;;;GAMG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,OAAO,GACZ,SAAS,GAAG,SAAS,CAAC;AACzB;;;;;;;;;;;;;GAaG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,MAAM,GAAG,KAAK,GACnB,MAAM,GAAG,SAAS,CAAC;AACtB;;;;;GAKG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EAAE,CAAC,SAAS,MAAM,OAAO,EAC7D,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,CAAC,GACN,OAAO,CAAC,CAAC,CAAC,CAAC;AACd;;;;;;GAMG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EAAE,CAAC,SAAS,MAAM,OAAO,EAC7D,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,CAAC,EACP,KAAK,EACD,OAAO,CAAC,CAAC,CAAC,GACV,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,KAAK,OAAO,CAAC,MAAM,OAAO,CAAC,CAAC,GAClE,OAAO,CAAC,CAAC,CAAC,CAAC;AACd;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,OAAO,CAAC,GAAG,OAAO,CAAC,GAC7D,OAAO,CAAC,CAAC,CAAC,CAAC;AACd;;;;;;GAMG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,MAAM,EACZ,KAAK,EACD,MAAM,GACN,OAAO,GACP,IAAI,GACJ,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,KAAK,MAAM,GAAG,OAAO,CAAC,GACjE,OAAO,CAAC,CAAC,CAAC,CAAC;AACd;;;;;GAKG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;AA8NhF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,MAAM,GACX,OAAO,CAAC;AACX;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,GACf,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAC3B;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,CAAC,CAAC,CAAC;AACd;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EACpC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC9B,OAAO,CAAC,CAAC,CAAC,CAAC;AAgCd;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,OAAO,EACnC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,GACf,MAAM,GAAG,SAAS,GAAG,MAAM,EAAE,CAAC;AACjC;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,OAAO,EACnC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,GACvB,OAAO,CAAC,CAAC,CAAC,CAAC;AAuEd;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,UAAU,CAAC,CAAC,SAAS,OAAO,EAC1C,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,CAAC,CAAC,CAUZ;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,OAAO,EACxC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,SAAS,EAAE,MAAM,GAChB,OAAO,CAoBT;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,OAAO,EAAE,CAAC,SAAS,SAAS,CAAC,CAAC,CAAC,EAChE,IAAI,EAAE,CAAC,EACP,KAAK,CAAC,EACF,MAAM,GACN,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC,GACxE,CAAC,CAyCH;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,WAAW,CAAC,CAAC,SAAS,OAAO,EAAE,CAAC,SAAS,SAAS,CAAC,CAAC,CAAC,EACnE,IAAI,EAAE,CAAC,EACP,IAAI,CAAC,EACD,MAAM,GACN,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC,GACxE,CAAC,CA2CH;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,WAAW,CAAC,CAAC,SAAS,OAAO,EAAE,CAAC,SAAS,SAAS,CAAC,CAAC,CAAC,EACnE,IAAI,EAAE,CAAC,EACP,KAAK,CAAC,EACF,MAAM,GACN,CAAC,CACC,IAAI,EAAE,OAAO,EACb,CAAC,EAAE,MAAM,EACT,SAAS,EAAE,MAAM,EACjB,QAAQ,CAAC,EAAE,OAAO,KACf,MAAM,CAAC,EAChB,QAAQ,CAAC,EAAE,OAAO,GACjB,CAAC,CA+CH"}
|
||||
+636
@@ -0,0 +1,636 @@
|
||||
/**
|
||||
* Methods for getting and modifying attributes.
|
||||
*
|
||||
* @module cheerio/attributes
|
||||
*/
|
||||
var _a;
|
||||
import { text } from '../static.js';
|
||||
import { domEach, camelCase, cssCase } from '../utils.js';
|
||||
import { isTag } from 'domhandler';
|
||||
import { innerText, textContent } from 'domutils';
|
||||
import { ElementType } from 'htmlparser2';
|
||||
const hasOwn =
|
||||
// @ts-expect-error `hasOwn` is a standard object method
|
||||
(_a = Object.hasOwn) !== null && _a !== void 0 ? _a : ((object, prop) => Object.prototype.hasOwnProperty.call(object, prop));
|
||||
const rspace = /\s+/;
|
||||
const dataAttrPrefix = 'data-';
|
||||
// Attributes that are booleans
|
||||
const rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i;
|
||||
// Matches strings that look like JSON objects or arrays
|
||||
const rbrace = /^{[^]*}$|^\[[^]*]$/;
|
||||
function getAttr(elem, name, xmlMode) {
|
||||
var _a;
|
||||
if (!elem || !isTag(elem))
|
||||
return undefined;
|
||||
(_a = elem.attribs) !== null && _a !== void 0 ? _a : (elem.attribs = {});
|
||||
// Return the entire attribs object if no attribute specified
|
||||
if (!name) {
|
||||
return elem.attribs;
|
||||
}
|
||||
if (hasOwn(elem.attribs, name)) {
|
||||
// Get the (decoded) attribute
|
||||
return !xmlMode && rboolean.test(name) ? name : elem.attribs[name];
|
||||
}
|
||||
// Mimic the DOM and return text content as value for `option's`
|
||||
if (elem.name === 'option' && name === 'value') {
|
||||
return text(elem.children);
|
||||
}
|
||||
// Mimic DOM with default value for radios/checkboxes
|
||||
if (elem.name === 'input' &&
|
||||
(elem.attribs['type'] === 'radio' || elem.attribs['type'] === 'checkbox') &&
|
||||
name === 'value') {
|
||||
return 'on';
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
/**
|
||||
* Sets the value of an attribute. The attribute will be deleted if the value is
|
||||
* `null`.
|
||||
*
|
||||
* @private
|
||||
* @param el - The element to set the attribute on.
|
||||
* @param name - The attribute's name.
|
||||
* @param value - The attribute's value.
|
||||
*/
|
||||
function setAttr(el, name, value) {
|
||||
if (value === null) {
|
||||
removeAttribute(el, name);
|
||||
}
|
||||
else {
|
||||
el.attribs[name] = `${value}`;
|
||||
}
|
||||
}
|
||||
export function attr(name, value) {
|
||||
// Set the value (with attr map support)
|
||||
if (typeof name === 'object' || value !== undefined) {
|
||||
if (typeof value === 'function') {
|
||||
if (typeof name !== 'string') {
|
||||
{
|
||||
throw new Error('Bad combination of arguments.');
|
||||
}
|
||||
}
|
||||
return domEach(this, (el, i) => {
|
||||
if (isTag(el))
|
||||
setAttr(el, name, value.call(el, i, el.attribs[name]));
|
||||
});
|
||||
}
|
||||
return domEach(this, (el) => {
|
||||
if (!isTag(el))
|
||||
return;
|
||||
if (typeof name === 'object') {
|
||||
for (const objName of Object.keys(name)) {
|
||||
const objValue = name[objName];
|
||||
setAttr(el, objName, objValue);
|
||||
}
|
||||
}
|
||||
else {
|
||||
setAttr(el, name, value);
|
||||
}
|
||||
});
|
||||
}
|
||||
return arguments.length > 1
|
||||
? this
|
||||
: getAttr(this[0], name, this.options.xmlMode);
|
||||
}
|
||||
/**
|
||||
* Gets a node's prop.
|
||||
*
|
||||
* @private
|
||||
* @category Attributes
|
||||
* @param el - Element to get the prop of.
|
||||
* @param name - Name of the prop.
|
||||
* @param xmlMode - Disable handling of special HTML attributes.
|
||||
* @returns The prop's value.
|
||||
*/
|
||||
function getProp(el, name, xmlMode) {
|
||||
return name in el
|
||||
? // @ts-expect-error TS doesn't like us accessing the value directly here.
|
||||
el[name]
|
||||
: !xmlMode && rboolean.test(name)
|
||||
? getAttr(el, name, false) !== undefined
|
||||
: getAttr(el, name, xmlMode);
|
||||
}
|
||||
/**
|
||||
* Sets the value of a prop.
|
||||
*
|
||||
* @private
|
||||
* @param el - The element to set the prop on.
|
||||
* @param name - The prop's name.
|
||||
* @param value - The prop's value.
|
||||
* @param xmlMode - Disable handling of special HTML attributes.
|
||||
*/
|
||||
function setProp(el, name, value, xmlMode) {
|
||||
if (name in el) {
|
||||
// @ts-expect-error Overriding value
|
||||
el[name] = value;
|
||||
}
|
||||
else {
|
||||
setAttr(el, name, !xmlMode && rboolean.test(name)
|
||||
? value
|
||||
? ''
|
||||
: null
|
||||
: `${value}`);
|
||||
}
|
||||
}
|
||||
export function prop(name, value) {
|
||||
var _a;
|
||||
if (typeof name === 'string' && value === undefined) {
|
||||
const el = this[0];
|
||||
if (!el)
|
||||
return undefined;
|
||||
switch (name) {
|
||||
case 'style': {
|
||||
const property = this.css();
|
||||
const keys = Object.keys(property);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
property[i] = keys[i];
|
||||
}
|
||||
property.length = keys.length;
|
||||
return property;
|
||||
}
|
||||
case 'tagName':
|
||||
case 'nodeName': {
|
||||
if (!isTag(el))
|
||||
return undefined;
|
||||
return el.name.toUpperCase();
|
||||
}
|
||||
case 'href':
|
||||
case 'src': {
|
||||
if (!isTag(el))
|
||||
return undefined;
|
||||
const prop = (_a = el.attribs) === null || _a === void 0 ? void 0 : _a[name];
|
||||
if (typeof URL !== 'undefined' &&
|
||||
((name === 'href' && (el.tagName === 'a' || el.tagName === 'link')) ||
|
||||
(name === 'src' &&
|
||||
(el.tagName === 'img' ||
|
||||
el.tagName === 'iframe' ||
|
||||
el.tagName === 'audio' ||
|
||||
el.tagName === 'video' ||
|
||||
el.tagName === 'source'))) &&
|
||||
prop !== undefined &&
|
||||
this.options.baseURI) {
|
||||
return new URL(prop, this.options.baseURI).href;
|
||||
}
|
||||
return prop;
|
||||
}
|
||||
case 'innerText': {
|
||||
return innerText(el);
|
||||
}
|
||||
case 'textContent': {
|
||||
return textContent(el);
|
||||
}
|
||||
case 'outerHTML': {
|
||||
if (el.type === ElementType.Root)
|
||||
return this.html();
|
||||
return this.clone().wrap('<container />').parent().html();
|
||||
}
|
||||
case 'innerHTML': {
|
||||
return this.html();
|
||||
}
|
||||
default: {
|
||||
if (!isTag(el))
|
||||
return undefined;
|
||||
return getProp(el, name, this.options.xmlMode);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof name === 'object' || value !== undefined) {
|
||||
if (typeof value === 'function') {
|
||||
if (typeof name === 'object') {
|
||||
throw new TypeError('Bad combination of arguments.');
|
||||
}
|
||||
return domEach(this, (el, i) => {
|
||||
if (isTag(el)) {
|
||||
setProp(el, name, value.call(el, i, getProp(el, name, this.options.xmlMode)), this.options.xmlMode);
|
||||
}
|
||||
});
|
||||
}
|
||||
return domEach(this, (el) => {
|
||||
if (!isTag(el))
|
||||
return;
|
||||
if (typeof name === 'object') {
|
||||
for (const key of Object.keys(name)) {
|
||||
const val = name[key];
|
||||
setProp(el, key, val, this.options.xmlMode);
|
||||
}
|
||||
}
|
||||
else {
|
||||
setProp(el, name, value, this.options.xmlMode);
|
||||
}
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
/**
|
||||
* Sets the value of a data attribute.
|
||||
*
|
||||
* @private
|
||||
* @param elem - The element to set the data attribute on.
|
||||
* @param name - The data attribute's name.
|
||||
* @param value - The data attribute's value.
|
||||
*/
|
||||
function setData(elem, name, value) {
|
||||
var _a;
|
||||
(_a = elem.data) !== null && _a !== void 0 ? _a : (elem.data = {});
|
||||
if (typeof name === 'object')
|
||||
Object.assign(elem.data, name);
|
||||
else if (typeof name === 'string' && value !== undefined) {
|
||||
elem.data[name] = value;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Read _all_ HTML5 `data-*` attributes from the equivalent HTML5 `data-*`
|
||||
* attribute, and cache the value in the node's internal data store.
|
||||
*
|
||||
* @private
|
||||
* @category Attributes
|
||||
* @param el - Element to get the data attribute of.
|
||||
* @returns A map with all of the data attributes.
|
||||
*/
|
||||
function readAllData(el) {
|
||||
for (const domName of Object.keys(el.attribs)) {
|
||||
if (!domName.startsWith(dataAttrPrefix)) {
|
||||
continue;
|
||||
}
|
||||
const jsName = camelCase(domName.slice(dataAttrPrefix.length));
|
||||
if (!hasOwn(el.data, jsName)) {
|
||||
el.data[jsName] = parseDataValue(el.attribs[domName]);
|
||||
}
|
||||
}
|
||||
return el.data;
|
||||
}
|
||||
/**
|
||||
* Read the specified attribute from the equivalent HTML5 `data-*` attribute,
|
||||
* and (if present) cache the value in the node's internal data store.
|
||||
*
|
||||
* @private
|
||||
* @category Attributes
|
||||
* @param el - Element to get the data attribute of.
|
||||
* @param name - Name of the data attribute.
|
||||
* @returns The data attribute's value.
|
||||
*/
|
||||
function readData(el, name) {
|
||||
const domName = dataAttrPrefix + cssCase(name);
|
||||
const data = el.data;
|
||||
if (hasOwn(data, name)) {
|
||||
return data[name];
|
||||
}
|
||||
if (hasOwn(el.attribs, domName)) {
|
||||
return (data[name] = parseDataValue(el.attribs[domName]));
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
/**
|
||||
* Coerce string data-* attributes to their corresponding JavaScript primitives.
|
||||
*
|
||||
* @private
|
||||
* @category Attributes
|
||||
* @param value - The value to parse.
|
||||
* @returns The parsed value.
|
||||
*/
|
||||
function parseDataValue(value) {
|
||||
if (value === 'null')
|
||||
return null;
|
||||
if (value === 'true')
|
||||
return true;
|
||||
if (value === 'false')
|
||||
return false;
|
||||
const num = Number(value);
|
||||
if (value === String(num))
|
||||
return num;
|
||||
if (rbrace.test(value)) {
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
}
|
||||
catch {
|
||||
/* Ignore */
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
export function data(name, value) {
|
||||
var _a;
|
||||
const elem = this[0];
|
||||
if (!elem || !isTag(elem))
|
||||
return;
|
||||
const dataEl = elem;
|
||||
(_a = dataEl.data) !== null && _a !== void 0 ? _a : (dataEl.data = {});
|
||||
// Return the entire data object if no data specified
|
||||
if (name == null) {
|
||||
return readAllData(dataEl);
|
||||
}
|
||||
// Set the value (with attr map support)
|
||||
if (typeof name === 'object' || value !== undefined) {
|
||||
domEach(this, (el) => {
|
||||
if (isTag(el)) {
|
||||
if (typeof name === 'object')
|
||||
setData(el, name);
|
||||
else
|
||||
setData(el, name, value);
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
return readData(dataEl, name);
|
||||
}
|
||||
export function val(value) {
|
||||
const querying = arguments.length === 0;
|
||||
const element = this[0];
|
||||
if (!element || !isTag(element))
|
||||
return querying ? undefined : this;
|
||||
switch (element.name) {
|
||||
case 'textarea': {
|
||||
return this.text(value);
|
||||
}
|
||||
case 'select': {
|
||||
const option = this.find('option:selected');
|
||||
if (!querying) {
|
||||
if (this.attr('multiple') == null && typeof value === 'object') {
|
||||
return this;
|
||||
}
|
||||
this.find('option').removeAttr('selected');
|
||||
const values = typeof value === 'object' ? value : [value];
|
||||
for (const val of values) {
|
||||
this.find(`option[value="${val}"]`).attr('selected', '');
|
||||
}
|
||||
return this;
|
||||
}
|
||||
return this.attr('multiple')
|
||||
? option.toArray().map((el) => text(el.children))
|
||||
: option.attr('value');
|
||||
}
|
||||
case 'button':
|
||||
case 'input':
|
||||
case 'option': {
|
||||
return querying
|
||||
? this.attr('value')
|
||||
: this.attr('value', value);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
/**
|
||||
* Remove an attribute.
|
||||
*
|
||||
* @private
|
||||
* @param elem - Node to remove attribute from.
|
||||
* @param name - Name of the attribute to remove.
|
||||
*/
|
||||
function removeAttribute(elem, name) {
|
||||
if (!elem.attribs || !hasOwn(elem.attribs, name))
|
||||
return;
|
||||
delete elem.attribs[name];
|
||||
}
|
||||
/**
|
||||
* Splits a space-separated list of names to individual names.
|
||||
*
|
||||
* @category Attributes
|
||||
* @param names - Names to split.
|
||||
* @returns - Split names.
|
||||
*/
|
||||
function splitNames(names) {
|
||||
return names ? names.trim().split(rspace) : [];
|
||||
}
|
||||
/**
|
||||
* Method for removing attributes by `name`.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('.pear').removeAttr('class').prop('outerHTML');
|
||||
* //=> <li>Pear</li>
|
||||
*
|
||||
* $('.apple').attr('id', 'favorite');
|
||||
* $('.apple').removeAttr('id class').prop('outerHTML');
|
||||
* //=> <li>Apple</li>
|
||||
* ```
|
||||
*
|
||||
* @param name - Name of the attribute.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/removeAttr/}
|
||||
*/
|
||||
export function removeAttr(name) {
|
||||
const attrNames = splitNames(name);
|
||||
for (const attrName of attrNames) {
|
||||
domEach(this, (elem) => {
|
||||
if (isTag(elem))
|
||||
removeAttribute(elem, attrName);
|
||||
});
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Check to see if _any_ of the matched elements have the given `className`.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('.pear').hasClass('pear');
|
||||
* //=> true
|
||||
*
|
||||
* $('apple').hasClass('fruit');
|
||||
* //=> false
|
||||
*
|
||||
* $('li').hasClass('pear');
|
||||
* //=> true
|
||||
* ```
|
||||
*
|
||||
* @param className - Name of the class.
|
||||
* @returns Indicates if an element has the given `className`.
|
||||
* @see {@link https://api.jquery.com/hasClass/}
|
||||
*/
|
||||
export function hasClass(className) {
|
||||
return this.toArray().some((elem) => {
|
||||
const clazz = isTag(elem) && elem.attribs['class'];
|
||||
let idx = -1;
|
||||
if (clazz && className.length > 0) {
|
||||
while ((idx = clazz.indexOf(className, idx + 1)) > -1) {
|
||||
const end = idx + className.length;
|
||||
if ((idx === 0 || rspace.test(clazz[idx - 1])) &&
|
||||
(end === clazz.length || rspace.test(clazz[end]))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Adds class(es) to all of the matched elements. Also accepts a `function`.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('.pear').addClass('fruit').prop('outerHTML');
|
||||
* //=> <li class="pear fruit">Pear</li>
|
||||
*
|
||||
* $('.apple').addClass('fruit red').prop('outerHTML');
|
||||
* //=> <li class="apple fruit red">Apple</li>
|
||||
* ```
|
||||
*
|
||||
* @param value - Name of new class.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/addClass/}
|
||||
*/
|
||||
export function addClass(value) {
|
||||
// Support functions
|
||||
if (typeof value === 'function') {
|
||||
return domEach(this, (el, i) => {
|
||||
if (isTag(el)) {
|
||||
const className = el.attribs['class'] || '';
|
||||
addClass.call([el], value.call(el, i, className));
|
||||
}
|
||||
});
|
||||
}
|
||||
// Return if no value or not a string or function
|
||||
if (!value || typeof value !== 'string')
|
||||
return this;
|
||||
const classNames = value.split(rspace);
|
||||
const numElements = this.length;
|
||||
for (let i = 0; i < numElements; i++) {
|
||||
const el = this[i];
|
||||
// If selected element isn't a tag, move on
|
||||
if (!isTag(el))
|
||||
continue;
|
||||
// If we don't already have classes — always set xmlMode to false here, as it doesn't matter for classes
|
||||
const className = getAttr(el, 'class', false);
|
||||
if (className) {
|
||||
let setClass = ` ${className} `;
|
||||
// Check if class already exists
|
||||
for (const cn of classNames) {
|
||||
const appendClass = `${cn} `;
|
||||
if (!setClass.includes(` ${appendClass}`))
|
||||
setClass += appendClass;
|
||||
}
|
||||
setAttr(el, 'class', setClass.trim());
|
||||
}
|
||||
else {
|
||||
setAttr(el, 'class', classNames.join(' ').trim());
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Removes one or more space-separated classes from the selected elements. If no
|
||||
* `className` is defined, all classes will be removed. Also accepts a
|
||||
* `function`.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('.pear').removeClass('pear').prop('outerHTML');
|
||||
* //=> <li class="">Pear</li>
|
||||
*
|
||||
* $('.apple').addClass('red').removeClass().prop('outerHTML');
|
||||
* //=> <li class="">Apple</li>
|
||||
* ```
|
||||
*
|
||||
* @param name - Name of the class. If not specified, removes all elements.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/removeClass/}
|
||||
*/
|
||||
export function removeClass(name) {
|
||||
// Handle if value is a function
|
||||
if (typeof name === 'function') {
|
||||
return domEach(this, (el, i) => {
|
||||
if (isTag(el)) {
|
||||
removeClass.call([el], name.call(el, i, el.attribs['class'] || ''));
|
||||
}
|
||||
});
|
||||
}
|
||||
const classes = splitNames(name);
|
||||
const numClasses = classes.length;
|
||||
const removeAll = arguments.length === 0;
|
||||
return domEach(this, (el) => {
|
||||
if (!isTag(el))
|
||||
return;
|
||||
if (removeAll) {
|
||||
// Short circuit the remove all case as this is the nice one
|
||||
el.attribs['class'] = '';
|
||||
}
|
||||
else {
|
||||
const elClasses = splitNames(el.attribs['class']);
|
||||
let changed = false;
|
||||
for (let j = 0; j < numClasses; j++) {
|
||||
const index = elClasses.indexOf(classes[j]);
|
||||
if (index !== -1) {
|
||||
elClasses.splice(index, 1);
|
||||
changed = true;
|
||||
/*
|
||||
* We have to do another pass to ensure that there are not duplicate
|
||||
* classes listed
|
||||
*/
|
||||
j--;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
el.attribs['class'] = elClasses.join(' ');
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Add or remove class(es) from the matched elements, depending on either the
|
||||
* class's presence or the value of the switch argument. Also accepts a
|
||||
* `function`.
|
||||
*
|
||||
* @category Attributes
|
||||
* @example
|
||||
*
|
||||
* ```js
|
||||
* $('.apple.green').toggleClass('fruit green red').prop('outerHTML');
|
||||
* //=> <li class="apple fruit red">Apple</li>
|
||||
*
|
||||
* $('.apple.green').toggleClass('fruit green red', true).prop('outerHTML');
|
||||
* //=> <li class="apple green fruit red">Apple</li>
|
||||
* ```
|
||||
*
|
||||
* @param value - Name of the class. Can also be a function.
|
||||
* @param stateVal - If specified the state of the class.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/toggleClass/}
|
||||
*/
|
||||
export function toggleClass(value, stateVal) {
|
||||
// Support functions
|
||||
if (typeof value === 'function') {
|
||||
return domEach(this, (el, i) => {
|
||||
if (isTag(el)) {
|
||||
toggleClass.call([el], value.call(el, i, el.attribs['class'] || '', stateVal), stateVal);
|
||||
}
|
||||
});
|
||||
}
|
||||
// Return if no value or not a string or function
|
||||
if (!value || typeof value !== 'string')
|
||||
return this;
|
||||
const classNames = value.split(rspace);
|
||||
const numClasses = classNames.length;
|
||||
const state = typeof stateVal === 'boolean' ? (stateVal ? 1 : -1) : 0;
|
||||
const numElements = this.length;
|
||||
for (let i = 0; i < numElements; i++) {
|
||||
const el = this[i];
|
||||
// If selected element isn't a tag, move on
|
||||
if (!isTag(el))
|
||||
continue;
|
||||
const elementClasses = splitNames(el.attribs['class']);
|
||||
// Check if class already exists
|
||||
for (let j = 0; j < numClasses; j++) {
|
||||
// Check if the class name is currently defined
|
||||
const index = elementClasses.indexOf(classNames[j]);
|
||||
// Add if stateValue === true or we are toggling and there is no value
|
||||
if (state >= 0 && index === -1) {
|
||||
elementClasses.push(classNames[j]);
|
||||
}
|
||||
else if (state <= 0 && index !== -1) {
|
||||
// Otherwise remove but only if the item exists
|
||||
elementClasses.splice(index, 1);
|
||||
}
|
||||
}
|
||||
el.attribs['class'] = elementClasses.join(' ');
|
||||
}
|
||||
return this;
|
||||
}
|
||||
//# sourceMappingURL=attributes.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+42
@@ -0,0 +1,42 @@
|
||||
import { type Element, type AnyNode } from 'domhandler';
|
||||
import type { Cheerio } from '../cheerio.js';
|
||||
/**
|
||||
* Get the value of a style property for the first element in the set of matched
|
||||
* elements.
|
||||
*
|
||||
* @category CSS
|
||||
* @param names - Optionally the names of the properties of interest.
|
||||
* @returns A map of all of the style properties.
|
||||
* @see {@link https://api.jquery.com/css/}
|
||||
*/
|
||||
export declare function css<T extends AnyNode>(this: Cheerio<T>, names?: string[]): Record<string, string> | undefined;
|
||||
/**
|
||||
* Get the value of a style property for the first element in the set of matched
|
||||
* elements.
|
||||
*
|
||||
* @category CSS
|
||||
* @param name - The name of the property.
|
||||
* @returns The property value for the given name.
|
||||
* @see {@link https://api.jquery.com/css/}
|
||||
*/
|
||||
export declare function css<T extends AnyNode>(this: Cheerio<T>, name: string): string | undefined;
|
||||
/**
|
||||
* Set one CSS property for every matched element.
|
||||
*
|
||||
* @category CSS
|
||||
* @param prop - The name of the property.
|
||||
* @param val - The new value.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/css/}
|
||||
*/
|
||||
export declare function css<T extends AnyNode>(this: Cheerio<T>, prop: string, val: string | ((this: Element, i: number, style: string) => string | undefined)): Cheerio<T>;
|
||||
/**
|
||||
* Set multiple CSS properties for every matched element.
|
||||
*
|
||||
* @category CSS
|
||||
* @param map - A map of property names and values.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/css/}
|
||||
*/
|
||||
export declare function css<T extends AnyNode>(this: Cheerio<T>, map: Record<string, string>): Cheerio<T>;
|
||||
//# sourceMappingURL=css.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"css.d.ts","sourceRoot":"","sources":["../../../src/api/css.ts"],"names":[],"mappings":"AACA,OAAO,EAAS,KAAK,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,YAAY,CAAC;AAC/D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAE7C;;;;;;;;GAQG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,OAAO,EACnC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,KAAK,CAAC,EAAE,MAAM,EAAE,GACf,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAAC;AACtC;;;;;;;;GAQG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,OAAO,EACnC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,MAAM,GACX,MAAM,GAAG,SAAS,CAAC;AACtB;;;;;;;;GAQG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,OAAO,EACnC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,IAAI,EAAE,MAAM,EACZ,GAAG,EACC,MAAM,GACN,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC,GACpE,OAAO,CAAC,CAAC,CAAC,CAAC;AACd;;;;;;;GAOG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,OAAO,EACnC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,EAChB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC1B,OAAO,CAAC,CAAC,CAAC,CAAC"}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
import { domEach } from '../utils.js';
|
||||
import { isTag } from 'domhandler';
|
||||
/**
|
||||
* Set multiple CSS properties for every matched element.
|
||||
*
|
||||
* @category CSS
|
||||
* @param prop - The names of the properties.
|
||||
* @param val - The new values.
|
||||
* @returns The instance itself.
|
||||
* @see {@link https://api.jquery.com/css/}
|
||||
*/
|
||||
export function css(prop, val) {
|
||||
if ((prop != null && val != null) ||
|
||||
// When `prop` is a "plain" object
|
||||
(typeof prop === 'object' && !Array.isArray(prop))) {
|
||||
return domEach(this, (el, i) => {
|
||||
if (isTag(el)) {
|
||||
// `prop` can't be an array here anymore.
|
||||
setCss(el, prop, val, i);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (this.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return getCss(this[0], prop);
|
||||
}
|
||||
/**
|
||||
* Set styles of all elements.
|
||||
*
|
||||
* @private
|
||||
* @param el - Element to set style of.
|
||||
* @param prop - Name of property.
|
||||
* @param value - Value to set property to.
|
||||
* @param idx - Optional index within the selection.
|
||||
*/
|
||||
function setCss(el, prop, value, idx) {
|
||||
if (typeof prop === 'string') {
|
||||
const styles = getCss(el);
|
||||
const val = typeof value === 'function' ? value.call(el, idx, styles[prop]) : value;
|
||||
if (val === '') {
|
||||
delete styles[prop];
|
||||
}
|
||||
else if (val != null) {
|
||||
styles[prop] = val;
|
||||
}
|
||||
el.attribs['style'] = stringify(styles);
|
||||
}
|
||||
else if (typeof prop === 'object') {
|
||||
const keys = Object.keys(prop);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const k = keys[i];
|
||||
setCss(el, k, prop[k], i);
|
||||
}
|
||||
}
|
||||
}
|
||||
function getCss(el, prop) {
|
||||
if (!el || !isTag(el))
|
||||
return;
|
||||
const styles = parse(el.attribs['style']);
|
||||
if (typeof prop === 'string') {
|
||||
return styles[prop];
|
||||
}
|
||||
if (Array.isArray(prop)) {
|
||||
const newStyles = {};
|
||||
for (const item of prop) {
|
||||
if (styles[item] != null) {
|
||||
newStyles[item] = styles[item];
|
||||
}
|
||||
}
|
||||
return newStyles;
|
||||
}
|
||||
return styles;
|
||||
}
|
||||
/**
|
||||
* Stringify `obj` to styles.
|
||||
*
|
||||
* @private
|
||||
* @category CSS
|
||||
* @param obj - Object to stringify.
|
||||
* @returns The serialized styles.
|
||||
*/
|
||||
function stringify(obj) {
|
||||
return Object.keys(obj).reduce((str, prop) => `${str}${str ? ' ' : ''}${prop}: ${obj[prop]};`, '');
|
||||
}
|
||||
/**
|
||||
* Parse `styles`.
|
||||
*
|
||||
* @private
|
||||
* @category CSS
|
||||
* @param styles - Styles to be parsed.
|
||||
* @returns The parsed styles.
|
||||
*/
|
||||
function parse(styles) {
|
||||
styles = (styles || '').trim();
|
||||
if (!styles)
|
||||
return {};
|
||||
const obj = {};
|
||||
let key;
|
||||
for (const str of styles.split(';')) {
|
||||
const n = str.indexOf(':');
|
||||
// If there is no :, or if it is the first/last character, add to the previous item's value
|
||||
if (n < 1 || n === str.length - 1) {
|
||||
const trimmed = str.trimEnd();
|
||||
if (trimmed.length > 0 && key !== undefined) {
|
||||
obj[key] += `;${trimmed}`;
|
||||
}
|
||||
}
|
||||
else {
|
||||
key = str.slice(0, n).trim();
|
||||
obj[key] = str.slice(n + 1).trim();
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
//# sourceMappingURL=css.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"css.js","sourceRoot":"","sources":["../../../src/api/css.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,KAAK,EAA8B,MAAM,YAAY,CAAC;AAyD/D;;;;;;;;GAQG;AACH,MAAM,UAAU,GAAG,CAEjB,IAAiD,EACjD,GAEqE;IAErE,IACE,CAAC,IAAI,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,CAAC;QAC7B,kCAAkC;QAClC,CAAC,OAAO,IAAI,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,EAClD,CAAC;QACD,OAAO,OAAO,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE;YAC7B,IAAI,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC;gBACd,yCAAyC;gBACzC,MAAM,CAAC,EAAE,EAAE,IAAc,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;YACrC,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IAED,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACtB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAc,CAAC,CAAC;AACzC,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,MAAM,CACb,EAAW,EACX,IAAqC,EACrC,KAGa,EACb,GAAW;IAEX,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC7B,MAAM,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;QAE1B,MAAM,GAAG,GACP,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;QAE1E,IAAI,GAAG,KAAK,EAAE,EAAE,CAAC;YACf,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC;QACtB,CAAC;aAAM,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,MAAM,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC;QACrB,CAAC;QAED,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;IAC1C,CAAC;SAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QACpC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC/B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACrC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,MAAM,CAAC,EAAE,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QAC5B,CAAC;IACH,CAAC;AACH,CAAC;AAsBD,SAAS,MAAM,CACb,EAAW,EACX,IAAwB;IAExB,IAAI,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAAE,OAAO;IAE9B,MAAM,MAAM,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC;IAC1C,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC7B,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC;IACtB,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QACxB,MAAM,SAAS,GAA2B,EAAE,CAAC;QAC7C,KAAK,MAAM,IAAI,IAAI,IAAI,EAAE,CAAC;YACxB,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;gBACzB,SAAS,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;YACjC,CAAC;QACH,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,SAAS,CAAC,GAA2B;IAC5C,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,CAC5B,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,KAAK,GAAG,CAAC,IAAI,CAAC,GAAG,EAC9D,EAAE,CACH,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,KAAK,CAAC,MAAc;IAC3B,MAAM,GAAG,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IAE/B,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,CAAC;IAEvB,MAAM,GAAG,GAA2B,EAAE,CAAC;IAEvC,IAAI,GAAuB,CAAC;IAE5B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACpC,MAAM,CAAC,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC3B,2FAA2F;QAC3F,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAClC,MAAM,OAAO,GAAG,GAAG,CAAC,OAAO,EAAE,CAAC;YAC9B,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;gBAC5C,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,OAAO,EAAE,CAAC;YAC5B,CAAC;QACH,CAAC;aAAM,CAAC;YACN,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;YAC7B,GAAG,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QACrC,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC"}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user