Commit f064c792 authored by Muddsair Sharif's avatar Muddsair Sharif
Browse files

Initial commit

parents
Pipeline #8 canceled with stages
/**
* Module dependencies.
*/
var crypto = require('crypto');
/**
* Sign the given `val` with `secret`.
*
* @param {String} val
* @param {String} secret
* @return {String}
* @api private
*/
exports.sign = function(val, secret){
if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string.");
if ('string' != typeof secret) throw new TypeError("Secret string must be provided.");
return val + '.' + crypto
.createHmac('sha256', secret)
.update(val)
.digest('base64')
.replace(/\=+$/, '');
};
/**
* Unsign and decode the given `val` with `secret`,
* returning `false` if the signature is invalid.
*
* @param {String} val
* @param {String} secret
* @return {String|Boolean}
* @api private
*/
exports.unsign = function(val, secret){
if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided.");
if ('string' != typeof secret) throw new TypeError("Secret string must be provided.");
var str = val.slice(0, val.lastIndexOf('.'))
, mac = exports.sign(str, secret);
return sha1(mac) == sha1(val) ? str : false;
};
/**
* Private
*/
function sha1(str){
return crypto.createHash('sha1').update(str).digest('hex');
}
{
"_args": [
[
{
"raw": "cookie-signature@1.0.6",
"scope": null,
"escapedName": "cookie-signature",
"name": "cookie-signature",
"rawSpec": "1.0.6",
"spec": "1.0.6",
"type": "version"
},
"C:\\Users\\Giuliano\\Desktop\\nasaproject\\node_modules\\express"
]
],
"_from": "cookie-signature@1.0.6",
"_id": "cookie-signature@1.0.6",
"_inCache": true,
"_location": "/cookie-signature",
"_nodeVersion": "0.10.36",
"_npmUser": {
"name": "natevw",
"email": "natevw@yahoo.com"
},
"_npmVersion": "2.3.0",
"_phantomChildren": {},
"_requested": {
"raw": "cookie-signature@1.0.6",
"scope": null,
"escapedName": "cookie-signature",
"name": "cookie-signature",
"rawSpec": "1.0.6",
"spec": "1.0.6",
"type": "version"
},
"_requiredBy": [
"/express"
],
"_resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
"_shasum": "e303a882b342cc3ee8ca513a79999734dab3ae2c",
"_shrinkwrap": null,
"_spec": "cookie-signature@1.0.6",
"_where": "C:\\Users\\Giuliano\\Desktop\\nasaproject\\node_modules\\express",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@learnboost.com"
},
"bugs": {
"url": "https://github.com/visionmedia/node-cookie-signature/issues"
},
"dependencies": {},
"description": "Sign and unsign cookies",
"devDependencies": {
"mocha": "*",
"should": "*"
},
"directories": {},
"dist": {
"shasum": "e303a882b342cc3ee8ca513a79999734dab3ae2c",
"tarball": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz"
},
"gitHead": "391b56cf44d88c493491b7e3fc53208cfb976d2a",
"homepage": "https://github.com/visionmedia/node-cookie-signature#readme",
"keywords": [
"cookie",
"sign",
"unsign"
],
"license": "MIT",
"main": "index",
"maintainers": [
{
"name": "tjholowaychuk",
"email": "tj@vision-media.ca"
},
{
"name": "natevw",
"email": "natevw@yahoo.com"
}
],
"name": "cookie-signature",
"optionalDependencies": {},
"readme": "\n# cookie-signature\n\n Sign and unsign cookies.\n\n## Example\n\n```js\nvar cookie = require('cookie-signature');\n\nvar val = cookie.sign('hello', 'tobiiscool');\nval.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI');\n\nvar val = cookie.sign('hello', 'tobiiscool');\ncookie.unsign(val, 'tobiiscool').should.equal('hello');\ncookie.unsign(val, 'luna').should.be.false;\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 LearnBoost <tj@learnboost.com>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
"readmeFilename": "Readme.md",
"repository": {
"type": "git",
"url": "git+https://github.com/visionmedia/node-cookie-signature.git"
},
"scripts": {
"test": "mocha --require should --reporter spec"
},
"version": "1.0.6"
}
0.3.1 / 2016-05-26
==================
* Fix `sameSite: true` to work with draft-7 clients
- `true` now sends `SameSite=Strict` instead of `SameSite`
0.3.0 / 2016-05-26
==================
* Add `sameSite` option
- Replaces `firstPartyOnly` option, never implemented by browsers
* Improve error message when `encode` is not a function
* Improve error message when `expires` is not a `Date`
0.2.4 / 2016-05-20
==================
* perf: enable strict mode
* perf: use for loop in parse
* perf: use string concatination for serialization
0.2.3 / 2015-10-25
==================
* Fix cookie `Max-Age` to never be a floating point number
0.2.2 / 2015-09-17
==================
* Fix regression when setting empty cookie value
- Ease the new restriction, which is just basic header-level validation
* Fix typo in invalid value errors
0.2.1 / 2015-09-17
==================
* Throw on invalid values provided to `serialize`
- Ensures the resulting string is a valid HTTP header value
0.2.0 / 2015-08-13
==================
* Add `firstPartyOnly` option
* Throw better error for invalid argument to parse
* perf: hoist regular expression
0.1.5 / 2015-09-17
==================
* Fix regression when setting empty cookie value
- Ease the new restriction, which is just basic header-level validation
* Fix typo in invalid value errors
0.1.4 / 2015-09-17
==================
* Throw better error for invalid argument to parse
* Throw on invalid values provided to `serialize`
- Ensures the resulting string is a valid HTTP header value
0.1.3 / 2015-05-19
==================
* Reduce the scope of try-catch deopt
* Remove argument reassignments
0.1.2 / 2014-04-16
==================
* Remove unnecessary files from npm package
0.1.1 / 2014-02-23
==================
* Fix bad parse when cookie value contained a comma
* Fix support for `maxAge` of `0`
0.1.0 / 2013-05-01
==================
* Add `decode` option
* Add `encode` option
0.0.6 / 2013-04-08
==================
* Ignore cookie parts missing `=`
0.0.5 / 2012-10-29
==================
* Return raw cookie value if value unescape errors
0.0.4 / 2012-06-21
==================
* Use encode/decodeURIComponent for cookie encoding/decoding
- Improve server/client interoperability
0.0.3 / 2012-06-06
==================
* Only escape special characters per the cookie RFC
0.0.2 / 2012-06-01
==================
* Fix `maxAge` option to not throw error
0.0.1 / 2012-05-28
==================
* Add more tests
0.0.0 / 2012-05-28
==================
* Initial release
(The MIT License)
Copyright (c) 2012-2014 Roman Shtylman <shtylman@gmail.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.
# cookie
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Basic HTTP cookie parser and serializer for HTTP servers.
## Installation
```sh
$ npm install cookie
```
## API
```js
var cookie = require('cookie');
```
### cookie.parse(str, options)
Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs.
The `str` argument is the string representing a `Cookie` header value and `options` is an
optional object containing additional parsing options.
```js
var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2');
// { foo: 'bar', equation: 'E=mc^2' }
```
#### Options
`cookie.parse` accepts these properties in the options object.
##### decode
Specifies a function that will be used to decode a cookie's value. Since the value of a cookie
has a limited character set (and must be a simple string), this function can be used to decode
a previously-encoded cookie value into a JavaScript string or other object.
The default function is the global `decodeURIComponent`, which will decode any URL-encoded
sequences into their byte representations.
**note** if an error is thrown from this function, the original, non-decoded cookie value will
be returned as the cookie's value.
### cookie.serialize(name, value, options)
Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the
name for the cookie, the `value` argument is the value to set the cookie to, and the `options`
argument is an optional object containing additional serialization options.
```js
var setCookie = cookie.serialize('foo', 'bar');
// foo=bar
```
#### Options
`cookie.serialize` accepts these properties in the options object.
##### domain
Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6266-5.2.3]. By default, no
domain is set, and most clients will consider the cookie to apply to only the current domain.
##### encode
Specifies a function that will be used to encode a cookie's value. Since value of a cookie
has a limited character set (and must be a simple string), this function can be used to encode
a value into a string suited for a cookie's value.
The default function is the global `ecodeURIComponent`, which will encode a JavaScript string
into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range.
##### expires
Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6266-5.2.1].
By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and
will delete it on a condition like exiting a web browser application.
**note** the [cookie storage model specification][rfc-6266-5.3] states that if both `expires` and
`magAge` are set, then `maxAge` takes precedence, but it is possiblke not all clients by obey this,
so if both are set, they should point to the same date and time.
##### httpOnly
Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6266-5.2.6]. When truthy,
the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set.
**note** be careful when setting this to `true`, as compliant clients will not allow client-side
JavaScript to see the cookie in `document.cookie`.
##### maxAge
Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6266-5.2.2].
The given number will be converted to an integer by rounding down. By default, no maximum age is set.
**note** the [cookie storage model specification][rfc-6266-5.3] states that if both `expires` and
`magAge` are set, then `maxAge` takes precedence, but it is possiblke not all clients by obey this,
so if both are set, they should point to the same date and time.
##### path
Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6266-5.2.4]. By default, the path
is considered the ["default path"][rfc-6266-5.1.4]. By default, no maximum age is set, and most
clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting
a web browser application.
##### sameSite
Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][draft-west-first-party-cookies-07].
- `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
- `false` will not set the `SameSite` attribute.
- `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
- `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
More information about the different enforcement levels can be found in the specification
https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1.1
**note** This is an attribute that has not yet been fully standardized, and may change in the future.
This also means many clients may ignore this attribute until they understand it.
##### secure
Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6266-5.2.5]. When truthy,
the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to
the server in the future if the browser does not have an HTTPS connection.
## Example
The following example uses this module in conjunction with the Node.js core HTTP server
to prompt a user for their name and display it back on future visits.
```js
var cookie = require('cookie');
var escapeHtml = require('escape-html');
var http = require('http');
var url = require('url');
function onRequest(req, res) {
// Parse the query string
var query = url.parse(req.url, true, true).query;
if (query && query.name) {
// Set a new cookie with the name
res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), {
httpOnly: true,
maxAge: 60 * 60 * 24 * 7 // 1 week
}));
// Redirect back after setting cookie
res.statusCode = 302;
res.setHeader('Location', req.headers.referer || '/');
res.end();
return;
}
// Parse the cookies on the request
var cookies = cookie.parse(req.headers.cookie || '');
// Get the visitor name set in the cookie
var name = cookies.name;
res.setHeader('Content-Type', 'text/html; charset=UTF-8');
if (name) {
res.write('<p>Welcome back, <b>' + escapeHtml(name) + '</b>!</p>');
} else {
res.write('<p>Hello, new visitor!</p>');
}
res.write('<form method="GET">');
res.write('<input placeholder="enter your name" name="name"> <input type="submit" value="Set Name">');
res.end('</form');
}
http.createServer(onRequest).listen(3000);
```
## Testing
```sh
$ npm test
```
## References
- [RFC 6266: HTTP State Management Mechanism][rfc-6266]
- [Same-site Cookies][draft-west-first-party-cookies-07]
[draft-west-first-party-cookies-07]: https://tools.ietf.org/html/draft-west-first-party-cookies-07
[rfc-6266]: https://tools.ietf.org/html/rfc6266
[rfc-6266-5.1.4]: https://tools.ietf.org/html/rfc6266#section-5.1.4
[rfc-6266-5.2.1]: https://tools.ietf.org/html/rfc6266#section-5.2.1
[rfc-6266-5.2.2]: https://tools.ietf.org/html/rfc6266#section-5.2.2
[rfc-6266-5.2.3]: https://tools.ietf.org/html/rfc6266#section-5.2.3
[rfc-6266-5.2.4]: https://tools.ietf.org/html/rfc6266#section-5.2.4
[rfc-6266-5.3]: https://tools.ietf.org/html/rfc6266#section-5.3
## License
[MIT](LICENSE)
[npm-image]: https://img.shields.io/npm/v/cookie.svg
[npm-url]: https://npmjs.org/package/cookie
[node-version-image]: https://img.shields.io/node/v/cookie.svg
[node-version-url]: https://nodejs.org/en/download
[travis-image]: https://img.shields.io/travis/jshttp/cookie/master.svg
[travis-url]: https://travis-ci.org/jshttp/cookie
[coveralls-image]: https://img.shields.io/coveralls/jshttp/cookie/master.svg
[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master
[downloads-image]: https://img.shields.io/npm/dm/cookie.svg
[downloads-url]: https://npmjs.org/package/cookie
/*!
* cookie
* Copyright(c) 2012-2014 Roman Shtylman
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module exports.
* @public
*/
exports.parse = parse;
exports.serialize = serialize;
/**
* Module variables.
* @private
*/
var decode = decodeURIComponent;
var encode = encodeURIComponent;
var pairSplitRegExp = /; */;
/**
* RegExp to match field-content in RFC 7230 sec 3.2
*
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
* field-vchar = VCHAR / obs-text
* obs-text = %x80-FF
*/
var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
/**
* Parse a cookie header.
*
* Parse the given cookie header string into an object
* The object has the various cookies as keys(names) => values
*
* @param {string} str
* @param {object} [options]
* @return {object}
* @public
*/
function parse(str, options) {
if (typeof str !== 'string') {
throw new TypeError('argument str must be a string');
}
var obj = {}
var opt = options || {};
var pairs = str.split(pairSplitRegExp);
var dec = opt.decode || decode;
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i];
var eq_idx = pair.indexOf('=');
// skip things that don't look like key=value
if (eq_idx < 0) {
continue;
}
var key = pair.substr(0, eq_idx).trim()
var val = pair.substr(++eq_idx, pair.length).trim();
// quoted values
if ('"' == val[0]) {
val = val.slice(1, -1);
}
// only assign once
if (undefined == obj[key]) {
obj[key] = tryDecode(val, dec);
}
}
return obj;
}
/**
* Serialize data into a cookie header.
*
* Serialize the a name value pair into a cookie string suitable for
* http headers. An optional options object specified cookie parameters.
*
* serialize('foo', 'bar', { httpOnly: true })
* => "foo=bar; httpOnly"
*
* @param {string} name
* @param {string} val
* @param {object} [options]
* @return {string}
* @public
*/
function serialize(name, val, options) {
var opt = options || {};
var enc = opt.encode || encode;
if (typeof enc !== 'function') {
throw new TypeError('option encode is invalid');
}
if (!fieldContentRegExp.test(name)) {
throw new TypeError('argument name is invalid');
}
var value = enc(val);
if (value && !fieldContentRegExp.test(value)) {
throw new TypeError('argument val is invalid');
}
var str = name + '=' + value;
if (null != opt.maxAge) {
var maxAge = opt.maxAge - 0;
if (isNaN(maxAge)) throw new Error('maxAge should be a Number');
str += '; Max-Age=' + Math.floor(maxAge);
}
if (opt.domain) {
if (!fieldContentRegExp.test(opt.domain)) {
throw new TypeError('option domain is invalid');
}
str += '; Domain=' + opt.domain;
}
if (opt.path) {
if (!fieldContentRegExp.test(opt.path)) {
throw new TypeError('option path is invalid');
}
str += '; Path=' + opt.path;
}
if (opt.expires) {
if (typeof opt.expires.toUTCString !== 'function') {
throw new TypeError('option expires is invalid');
}
str += '; Expires=' + opt.expires.toUTCString();
}
if (opt.httpOnly) {
str += '; HttpOnly';
}
if (opt.secure) {
str += '; Secure';
}
if (opt.sameSite) {
var sameSite = typeof opt.sameSite === 'string'
? opt.sameSite.toLowerCase() : opt.sameSite;
switch (sameSite) {
case true:
str += '; SameSite=Strict';
break;
case 'lax':
str += '; SameSite=Lax';
break;
case 'strict':
str += '; SameSite=Strict';
break;
default:
throw new TypeError('option sameSite is invalid');
}
}
return str;
}
/**
* Try decoding a string using a decoding function.
*
* @param {string} str
* @param {function} decode
* @private
*/
function tryDecode(str, decode) {
try {
return decode(str);
} catch (e) {
return str;
}
}
{
"_args": [
[
{
"raw": "cookie@0.3.1",
"scope": null,
"escapedName": "cookie",
"name": "cookie",
"rawSpec": "0.3.1",
"spec": "0.3.1",
"type": "version"
},
"C:\\Users\\Giuliano\\Desktop\\nasaproject\\node_modules\\express"
]
],
"_from": "cookie@0.3.1",
"_id": "cookie@0.3.1",
"_inCache": true,
"_location": "/cookie",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/cookie-0.3.1.tgz_1464323556714_0.6435900838114321"
},
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"_npmVersion": "1.4.28",
"_phantomChildren": {},
"_requested": {
"raw": "cookie@0.3.1",
"scope": null,
"escapedName": "cookie",
"name": "cookie",
"rawSpec": "0.3.1",
"spec": "0.3.1",
"type": "version"
},
"_requiredBy": [
"/express"
],
"_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz",
"_shasum": "e7e0a1f9ef43b4c8ba925c5c5a96e806d16873bb",
"_shrinkwrap": null,
"_spec": "cookie@0.3.1",
"_where": "C:\\Users\\Giuliano\\Desktop\\nasaproject\\node_modules\\express",
"author": {
"name": "Roman Shtylman",
"email": "shtylman@gmail.com"
},
"bugs": {
"url": "https://github.com/jshttp/cookie/issues"
},
"contributors": [
{
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
}
],
"dependencies": {},
"description": "HTTP server cookie parsing and serialization",
"devDependencies": {
"istanbul": "0.4.3",
"mocha": "1.21.5"
},
"directories": {},
"dist": {
"shasum": "e7e0a1f9ef43b4c8ba925c5c5a96e806d16873bb",
"tarball": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz"
},
"engines": {
"node": ">= 0.6"
},
"files": [
"HISTORY.md",
"LICENSE",
"README.md",
"index.js"
],
"gitHead": "e3c77d497d66c8b8d4b677b8954c1b192a09f0b3",
"homepage": "https://github.com/jshttp/cookie#readme",
"keywords": [
"cookie",
"cookies"
],
"license": "MIT",
"maintainers": [
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"name": "cookie",
"optionalDependencies": {},
"readme": "# cookie\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Build Status][travis-image]][travis-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\nBasic HTTP cookie parser and serializer for HTTP servers.\n\n## Installation\n\n```sh\n$ npm install cookie\n```\n\n## API\n\n```js\nvar cookie = require('cookie');\n```\n\n### cookie.parse(str, options)\n\nParse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs.\nThe `str` argument is the string representing a `Cookie` header value and `options` is an\noptional object containing additional parsing options.\n\n```js\nvar cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2');\n// { foo: 'bar', equation: 'E=mc^2' }\n```\n\n#### Options\n\n`cookie.parse` accepts these properties in the options object.\n\n##### decode\n\nSpecifies a function that will be used to decode a cookie's value. Since the value of a cookie\nhas a limited character set (and must be a simple string), this function can be used to decode\na previously-encoded cookie value into a JavaScript string or other object.\n\nThe default function is the global `decodeURIComponent`, which will decode any URL-encoded\nsequences into their byte representations.\n\n**note** if an error is thrown from this function, the original, non-decoded cookie value will\nbe returned as the cookie's value.\n\n### cookie.serialize(name, value, options)\n\nSerialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the\nname for the cookie, the `value` argument is the value to set the cookie to, and the `options`\nargument is an optional object containing additional serialization options.\n\n```js\nvar setCookie = cookie.serialize('foo', 'bar');\n// foo=bar\n```\n\n#### Options\n\n`cookie.serialize` accepts these properties in the options object.\n\n##### domain\n\nSpecifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6266-5.2.3]. By default, no\ndomain is set, and most clients will consider the cookie to apply to only the current domain.\n\n##### encode\n\nSpecifies a function that will be used to encode a cookie's value. Since value of a cookie\nhas a limited character set (and must be a simple string), this function can be used to encode\na value into a string suited for a cookie's value.\n\nThe default function is the global `ecodeURIComponent`, which will encode a JavaScript string\ninto UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range.\n\n##### expires\n\nSpecifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6266-5.2.1].\nBy default, no expiration is set, and most clients will consider this a \"non-persistent cookie\" and\nwill delete it on a condition like exiting a web browser application.\n\n**note** the [cookie storage model specification][rfc-6266-5.3] states that if both `expires` and\n`magAge` are set, then `maxAge` takes precedence, but it is possiblke not all clients by obey this,\nso if both are set, they should point to the same date and time.\n\n##### httpOnly\n\nSpecifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6266-5.2.6]. When truthy,\nthe `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set.\n\n**note** be careful when setting this to `true`, as compliant clients will not allow client-side\nJavaScript to see the cookie in `document.cookie`.\n\n##### maxAge\n\nSpecifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6266-5.2.2].\nThe given number will be converted to an integer by rounding down. By default, no maximum age is set.\n\n**note** the [cookie storage model specification][rfc-6266-5.3] states that if both `expires` and\n`magAge` are set, then `maxAge` takes precedence, but it is possiblke not all clients by obey this,\nso if both are set, they should point to the same date and time.\n\n##### path\n\nSpecifies the value for the [`Path` `Set-Cookie` attribute][rfc-6266-5.2.4]. By default, the path\nis considered the [\"default path\"][rfc-6266-5.1.4]. By default, no maximum age is set, and most\nclients will consider this a \"non-persistent cookie\" and will delete it on a condition like exiting\na web browser application.\n\n##### sameSite\n\nSpecifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][draft-west-first-party-cookies-07].\n\n - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.\n - `false` will not set the `SameSite` attribute.\n - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.\n - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.\n\nMore information about the different enforcement levels can be found in the specification\nhttps://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1.1\n\n**note** This is an attribute that has not yet been fully standardized, and may change in the future.\nThis also means many clients may ignore this attribute until they understand it.\n\n##### secure\n\nSpecifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6266-5.2.5]. When truthy,\nthe `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.\n\n**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to\nthe server in the future if the browser does not have an HTTPS connection.\n\n## Example\n\nThe following example uses this module in conjunction with the Node.js core HTTP server\nto prompt a user for their name and display it back on future visits.\n\n```js\nvar cookie = require('cookie');\nvar escapeHtml = require('escape-html');\nvar http = require('http');\nvar url = require('url');\n\nfunction onRequest(req, res) {\n // Parse the query string\n var query = url.parse(req.url, true, true).query;\n\n if (query && query.name) {\n // Set a new cookie with the name\n res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), {\n httpOnly: true,\n maxAge: 60 * 60 * 24 * 7 // 1 week\n }));\n\n // Redirect back after setting cookie\n res.statusCode = 302;\n res.setHeader('Location', req.headers.referer || '/');\n res.end();\n return;\n }\n\n // Parse the cookies on the request\n var cookies = cookie.parse(req.headers.cookie || '');\n\n // Get the visitor name set in the cookie\n var name = cookies.name;\n\n res.setHeader('Content-Type', 'text/html; charset=UTF-8');\n\n if (name) {\n res.write('<p>Welcome back, <b>' + escapeHtml(name) + '</b>!</p>');\n } else {\n res.write('<p>Hello, new visitor!</p>');\n }\n\n res.write('<form method=\"GET\">');\n res.write('<input placeholder=\"enter your name\" name=\"name\"> <input type=\"submit\" value=\"Set Name\">');\n res.end('</form');\n}\n\nhttp.createServer(onRequest).listen(3000);\n```\n\n## Testing\n\n```sh\n$ npm test\n```\n\n## References\n\n- [RFC 6266: HTTP State Management Mechanism][rfc-6266]\n- [Same-site Cookies][draft-west-first-party-cookies-07]\n\n[draft-west-first-party-cookies-07]: https://tools.ietf.org/html/draft-west-first-party-cookies-07\n[rfc-6266]: https://tools.ietf.org/html/rfc6266\n[rfc-6266-5.1.4]: https://tools.ietf.org/html/rfc6266#section-5.1.4\n[rfc-6266-5.2.1]: https://tools.ietf.org/html/rfc6266#section-5.2.1\n[rfc-6266-5.2.2]: https://tools.ietf.org/html/rfc6266#section-5.2.2\n[rfc-6266-5.2.3]: https://tools.ietf.org/html/rfc6266#section-5.2.3\n[rfc-6266-5.2.4]: https://tools.ietf.org/html/rfc6266#section-5.2.4\n[rfc-6266-5.3]: https://tools.ietf.org/html/rfc6266#section-5.3\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/cookie.svg\n[npm-url]: https://npmjs.org/package/cookie\n[node-version-image]: https://img.shields.io/node/v/cookie.svg\n[node-version-url]: https://nodejs.org/en/download\n[travis-image]: https://img.shields.io/travis/jshttp/cookie/master.svg\n[travis-url]: https://travis-ci.org/jshttp/cookie\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/cookie/master.svg\n[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/cookie.svg\n[downloads-url]: https://npmjs.org/package/cookie\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/jshttp/cookie.git"
},
"scripts": {
"test": "mocha --reporter spec --bail --check-leaks test/",
"test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/"
},
"version": "0.3.1"
}
The MIT License (MIT)
Copyright (c) 2015-2016, Jon Schlinkert
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.
/*!
* copy-descriptor <https://github.com/jonschlinkert/copy-descriptor>
*
* Copyright (c) 2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
/**
* Copy a descriptor from one object to another.
*
* ```js
* function App() {
* this.cache = {};
* }
* App.prototype.set = function(key, val) {
* this.cache[key] = val;
* return this;
* };
* Object.defineProperty(App.prototype, 'count', {
* get: function() {
* return Object.keys(this.cache).length;
* }
* });
*
* copy(App.prototype, 'count', 'len');
*
* // create an instance
* var app = new App();
*
* app.set('a', true);
* app.set('b', true);
* app.set('c', true);
*
* console.log(app.count);
* //=> 3
* console.log(app.len);
* //=> 3
* ```
* @name copy
* @param {Object} `receiver` The target object
* @param {Object} `provider` The provider object
* @param {String} `from` The key to copy on provider.
* @param {String} `to` Optionally specify a new key name to use.
* @return {Object}
* @api public
*/
module.exports = function copyDescriptor(receiver, provider, from, to) {
if (!isObject(provider) && typeof provider !== 'function') {
to = from;
from = provider;
provider = receiver;
}
if (!isObject(receiver) && typeof receiver !== 'function') {
throw new TypeError('expected the first argument to be an object');
}
if (!isObject(provider) && typeof provider !== 'function') {
throw new TypeError('expected provider to be an object');
}
if (typeof to !== 'string') {
to = from;
}
if (typeof from !== 'string') {
throw new TypeError('expected key to be a string');
}
if (!(from in provider)) {
throw new Error('property "' + from + '" does not exist');
}
var val = Object.getOwnPropertyDescriptor(provider, from);
if (val) Object.defineProperty(receiver, to, val);
};
function isObject(val) {
return {}.toString.call(val) === '[object Object]';
}
{
"_from": "copy-descriptor@^0.1.0",
"_id": "copy-descriptor@0.1.1",
"_inBundle": false,
"_integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=",
"_location": "/copy-descriptor",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "copy-descriptor@^0.1.0",
"name": "copy-descriptor",
"escapedName": "copy-descriptor",
"rawSpec": "^0.1.0",
"saveSpec": null,
"fetchSpec": "^0.1.0"
},
"_requiredBy": [
"/object-copy"
],
"_resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz",
"_shasum": "676f6eb3c39997c2ee1ac3a924fd6124748f578d",
"_spec": "copy-descriptor@^0.1.0",
"_where": "/Users/Chorthip/Documents/GitKraken/nasaproject/node_modules/object-copy",
"author": {
"name": "Jon Schlinkert",
"url": "https://github.com/jonschlinkert"
},
"bugs": {
"url": "https://github.com/jonschlinkert/copy-descriptor/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Copy a descriptor from object A to object B",
"devDependencies": {
"gulp-format-md": "^0.1.9",
"mocha": "^2.5.3"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/jonschlinkert/copy-descriptor",
"keywords": [
"copy",
"descriptor"
],
"license": "MIT",
"main": "index.js",
"name": "copy-descriptor",
"repository": {
"type": "git",
"url": "git+https://github.com/jonschlinkert/copy-descriptor.git"
},
"scripts": {
"test": "mocha"
},
"verb": {
"toc": false,
"layout": "default",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"related": {
"list": [
"is-accessor-descriptor",
"is-data-descriptor",
"is-descriptor",
"is-plain-object",
"isobject"
]
},
"lint": {
"reflinks": true
},
"reflinks": [
"verb-readme-generator",
"verb"
]
},
"version": "0.1.1"
}
Copyright Node.js contributors. All rights reserved.
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.
# core-util-is
The `util.is*` functions introduced in Node v0.12.
diff --git a/lib/util.js b/lib/util.js
index a03e874..9074e8e 100644
--- a/lib/util.js
+++ b/lib/util.js
@@ -19,430 +19,6 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
-var formatRegExp = /%[sdj%]/g;
-exports.format = function(f) {
- if (!isString(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
- }
- return objects.join(' ');
- }
-
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
- }
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject(x)) {
- str += ' ' + x;
- } else {
- str += ' ' + inspect(x);
- }
- }
- return str;
-};
-
-
-// Mark that a method should not be used.
-// Returns a modified function which warns once by default.
-// If --no-deprecation is set, then it is a no-op.
-exports.deprecate = function(fn, msg) {
- // Allow for deprecating things in the process of starting up.
- if (isUndefined(global.process)) {
- return function() {
- return exports.deprecate(fn, msg).apply(this, arguments);
- };
- }
-
- if (process.noDeprecation === true) {
- return fn;
- }
-
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (process.throwDeprecation) {
- throw new Error(msg);
- } else if (process.traceDeprecation) {
- console.trace(msg);
- } else {
- console.error(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
-
- return deprecated;
-};
-
-
-var debugs = {};
-var debugEnviron;
-exports.debuglog = function(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = process.env.NODE_DEBUG || '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = process.pid;
- debugs[set] = function() {
- var msg = exports.format.apply(exports, arguments);
- console.error('%s %d: %s', set, pid, msg);
- };
- } else {
- debugs[set] = function() {};
- }
- }
- return debugs[set];
-};
-
-
-/**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
- */
-/* legacy: obj, showHidden, depth, colors*/
-function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- exports._extend(ctx, opts);
- }
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
-}
-exports.inspect = inspect;
-
-
-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
-inspect.colors = {
- 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39]
-};
-
-// Don't use 'blue' not visible on cmd.exe
-inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
-};
-
-
-function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
-
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
- }
-}
-
-
-function stylizeNoColor(str, styleType) {
- return str;
-}
-
-
-function arrayToHash(array) {
- var hash = {};
-
- array.forEach(function(val, idx) {
- hash[val] = true;
- });
-
- return hash;
-}
-
-
-function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
-
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
-
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
-
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
-
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
- }
-
- var base = '', array = false, braces = ['{', '}'];
-
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
- }
-
- // Make functions say that they are functions
- if (isFunction(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
- }
-
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
-
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
-
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
- }
-
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
-
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
- }
- }
-
- ctx.seen.push(value);
-
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
-
- ctx.seen.pop();
-
- return reduceToSingleString(output, base, braces);
-}
-
-
-function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
- }
- if (isNumber(value)) {
- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
- if (value === 0 && 1 / value < 0)
- return ctx.stylize('-0', 'number');
- return ctx.stylize('' + value, 'number');
- }
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
-}
-
-
-function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
-}
-
-
-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
-}
-
-
-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- if (!hasOwnProperty(visibleKeys, key)) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
- } else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
-
- return name + ': ' + str;
-}
-
-
-function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
-
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
- }
-
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
-}
-
-
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
@@ -522,166 +98,10 @@ function isPrimitive(arg) {
exports.isPrimitive = isPrimitive;
function isBuffer(arg) {
- return arg instanceof Buffer;
+ return Buffer.isBuffer(arg);
}
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
-}
-
-
-function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
-}
-
-
-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
-
-// 26 Feb 16:19:34
-function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
-}
-
-
-// log is just a thin wrapper to console.log that prepends a timestamp
-exports.log = function() {
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
-};
-
-
-/**
- * Inherit the prototype methods from one constructor into another.
- *
- * The Function.prototype.inherits from lang.js rewritten as a standalone
- * function (not on Function.prototype). NOTE: If this file is to be loaded
- * during bootstrapping this function needs to be rewritten using some native
- * functions as prototype setup using normal JavaScript does not work as
- * expected during bootstrapping (see mirror.js in r114903).
- *
- * @param {function} ctor Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor Constructor function to inherit prototype from.
- */
-exports.inherits = function(ctor, superCtor) {
- ctor.super_ = superCtor;
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
-};
-
-exports._extend = function(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject(add)) return origin;
-
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
- }
- return origin;
-};
-
-function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
-}
-
-
-// Deprecated old stuff.
-
-exports.p = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- console.error(exports.inspect(arguments[i]));
- }
-}, 'util.p: Use console.error() instead');
-
-
-exports.exec = exports.deprecate(function() {
- return require('child_process').exec.apply(this, arguments);
-}, 'util.exec is now called `child_process.exec`.');
-
-
-exports.print = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stdout.write(String(arguments[i]));
- }
-}, 'util.print: Use console.log instead');
-
-
-exports.puts = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stdout.write(arguments[i] + '\n');
- }
-}, 'util.puts: Use console.log instead');
-
-
-exports.debug = exports.deprecate(function(x) {
- process.stderr.write('DEBUG: ' + x + '\n');
-}, 'util.debug: Use console.error instead');
-
-
-exports.error = exports.deprecate(function(x) {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stderr.write(arguments[i] + '\n');
- }
-}, 'util.error: Use console.error instead');
-
-
-exports.pump = exports.deprecate(function(readStream, writeStream, callback) {
- var callbackCalled = false;
-
- function call(a, b, c) {
- if (callback && !callbackCalled) {
- callback(a, b, c);
- callbackCalled = true;
- }
- }
-
- readStream.addListener('data', function(chunk) {
- if (writeStream.write(chunk) === false) readStream.pause();
- });
-
- writeStream.addListener('drain', function() {
- readStream.resume();
- });
-
- readStream.addListener('end', function() {
- writeStream.end();
- });
-
- readStream.addListener('close', function() {
- call();
- });
-
- readStream.addListener('error', function(err) {
- writeStream.end();
- call(err);
- });
-
- writeStream.addListener('error', function(err) {
- readStream.destroy();
- call(err);
- });
-}, 'util.pump(): Use readableStream.pipe() instead');
-
-
-var uv;
-exports._errnoException = function(err, syscall) {
- if (isUndefined(uv)) uv = process.binding('uv');
- var errname = uv.errname(err);
- var e = new Error(syscall + ' ' + errname);
- e.code = errname;
- e.errno = errname;
- e.syscall = syscall;
- return e;
-};
+}
\ No newline at end of file
// Copyright Joyent, Inc. and other Node 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.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
{
"_from": "core-util-is@~1.0.0",
"_id": "core-util-is@1.0.2",
"_inBundle": false,
"_integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=",
"_location": "/core-util-is",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "core-util-is@~1.0.0",
"name": "core-util-is",
"escapedName": "core-util-is",
"rawSpec": "~1.0.0",
"saveSpec": null,
"fetchSpec": "~1.0.0"
},
"_requiredBy": [
"/readable-stream"
],
"_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
"_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7",
"_spec": "core-util-is@~1.0.0",
"_where": "/Users/Chorthip/Documents/GitKraken/nasaproject/node_modules/readable-stream",
"author": {
"name": "Isaac Z. Schlueter",
"email": "i@izs.me",
"url": "http://blog.izs.me/"
},
"bugs": {
"url": "https://github.com/isaacs/core-util-is/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "The `util.is*` functions introduced in Node v0.12.",
"devDependencies": {
"tap": "^2.3.0"
},
"homepage": "https://github.com/isaacs/core-util-is#readme",
"keywords": [
"util",
"isBuffer",
"isArray",
"isNumber",
"isString",
"isRegExp",
"isThis",
"isThat",
"polyfill"
],
"license": "MIT",
"main": "lib/util.js",
"name": "core-util-is",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/core-util-is.git"
},
"scripts": {
"test": "tap test.js"
},
"version": "1.0.2"
}
var assert = require('tap');
var t = require('./lib/util');
assert.equal(t.isArray([]), true);
assert.equal(t.isArray({}), false);
assert.equal(t.isBoolean(null), false);
assert.equal(t.isBoolean(true), true);
assert.equal(t.isBoolean(false), true);
assert.equal(t.isNull(null), true);
assert.equal(t.isNull(undefined), false);
assert.equal(t.isNull(false), false);
assert.equal(t.isNull(), false);
assert.equal(t.isNullOrUndefined(null), true);
assert.equal(t.isNullOrUndefined(undefined), true);
assert.equal(t.isNullOrUndefined(false), false);
assert.equal(t.isNullOrUndefined(), true);
assert.equal(t.isNumber(null), false);
assert.equal(t.isNumber('1'), false);
assert.equal(t.isNumber(1), true);
assert.equal(t.isString(null), false);
assert.equal(t.isString('1'), true);
assert.equal(t.isString(1), false);
assert.equal(t.isSymbol(null), false);
assert.equal(t.isSymbol('1'), false);
assert.equal(t.isSymbol(1), false);
assert.equal(t.isSymbol(Symbol()), true);
assert.equal(t.isUndefined(null), false);
assert.equal(t.isUndefined(undefined), true);
assert.equal(t.isUndefined(false), false);
assert.equal(t.isUndefined(), true);
assert.equal(t.isRegExp(null), false);
assert.equal(t.isRegExp('1'), false);
assert.equal(t.isRegExp(new RegExp()), true);
assert.equal(t.isObject({}), true);
assert.equal(t.isObject([]), true);
assert.equal(t.isObject(new RegExp()), true);
assert.equal(t.isObject(new Date()), true);
assert.equal(t.isDate(null), false);
assert.equal(t.isDate('1'), false);
assert.equal(t.isDate(new Date()), true);
assert.equal(t.isError(null), false);
assert.equal(t.isError({ err: true }), false);
assert.equal(t.isError(new Error()), true);
assert.equal(t.isFunction(null), false);
assert.equal(t.isFunction({ }), false);
assert.equal(t.isFunction(function() {}), true);
assert.equal(t.isPrimitive(null), true);
assert.equal(t.isPrimitive(''), true);
assert.equal(t.isPrimitive(0), true);
assert.equal(t.isPrimitive(new Date()), false);
assert.equal(t.isBuffer(null), false);
assert.equal(t.isBuffer({}), false);
assert.equal(t.isBuffer(new Buffer(0)), true);
'use strict';
var captureStackTrace = require('capture-stack-trace');
function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
module.exports = function createErrorClass(className, setup) {
if (typeof className !== 'string') {
throw new TypeError('Expected className to be a string');
}
if (/[^0-9a-zA-Z_$]/.test(className)) {
throw new Error('className contains invalid characters');
}
setup = setup || function (message) {
this.message = message;
};
var ErrorClass = function () {
Object.defineProperty(this, 'name', {
configurable: true,
value: className,
writable: true
});
captureStackTrace(this, this.constructor);
setup.apply(this, arguments);
};
inherits(ErrorClass, Error);
return ErrorClass;
};
The MIT License (MIT)
Copyright (c) Vsevolod Strukchinsky <floatdrop@gmail.com> (github.com/floatdrop)
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.
{
"_from": "create-error-class@^3.0.0",
"_id": "create-error-class@3.0.2",
"_inBundle": false,
"_integrity": "sha1-Br56vvlHo/FKMP1hBnHUAbyot7Y=",
"_location": "/create-error-class",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "create-error-class@^3.0.0",
"name": "create-error-class",
"escapedName": "create-error-class",
"rawSpec": "^3.0.0",
"saveSpec": null,
"fetchSpec": "^3.0.0"
},
"_requiredBy": [
"/got"
],
"_resolved": "https://registry.npmjs.org/create-error-class/-/create-error-class-3.0.2.tgz",
"_shasum": "06be7abef947a3f14a30fd610671d401bca8b7b6",
"_spec": "create-error-class@^3.0.0",
"_where": "/Users/Chorthip/Documents/GitKraken/nasaproject/node_modules/got",
"author": {
"name": "Vsevolod Strukchinsky",
"email": "floatdrop@gmail.com",
"url": "github.com/floatdrop"
},
"bugs": {
"url": "https://github.com/floatdrop/create-error-class/issues"
},
"bundleDependencies": false,
"dependencies": {
"capture-stack-trace": "^1.0.0"
},
"deprecated": false,
"description": "Create Error classes",
"devDependencies": {
"mocha": "*"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/floatdrop/create-error-class#readme",
"keywords": [],
"license": "MIT",
"name": "create-error-class",
"repository": {
"type": "git",
"url": "git+https://github.com/floatdrop/create-error-class.git"
},
"scripts": {
"test": "mocha"
},
"version": "3.0.2"
}
# create-error-class [![Build Status](https://travis-ci.org/floatdrop/create-error-class.svg?branch=master)](https://travis-ci.org/floatdrop/create-error-class)
> Create error class
## Install
```
$ npm install --save create-error-class
```
## Usage
```js
var createErrorClass = require('create-error-class');
var HTTPError = createErrorClass('HTTPError', function (props) {
this.message = 'Status code is ' + props.statusCode;
});
throw new HTTPError({statusCode: 404});
```
## API
### createErrorClass(className, [setup])
Return constructor of Errors with `className`.
#### className
*Required*
Type: `string`
Class name of Error Object. Should contain characters from `[0-9a-zA-Z_$]` range.
#### setup
Type: `function`
Setup function, that will be called after each Error object is created from constructor with context of Error object.
By default `setup` function sets `this.message` as first argument:
```js
var MyError = createErrorClass('MyError');
new MyError('Something gone wrong!').message; // => 'Something gone wrong!'
```
## License
MIT © [Vsevolod Strukchinsky](http://github.com/floatdrop)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment