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

Initial commit

parents
Pipeline #8 canceled with stages
module.exports = function (xs, fn) {
var res = [];
for (var i = 0; i < xs.length; i++) {
var x = fn(xs[i], i);
if (isArray(x)) res.push.apply(res, x);
else res.push(x);
}
return res;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
{
"_from": "concat-map@0.0.1",
"_id": "concat-map@0.0.1",
"_inBundle": false,
"_integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
"_location": "/concat-map",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "concat-map@0.0.1",
"name": "concat-map",
"escapedName": "concat-map",
"rawSpec": "0.0.1",
"saveSpec": null,
"fetchSpec": "0.0.1"
},
"_requiredBy": [
"/brace-expansion"
],
"_resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"_shasum": "d8a96bd77fd68df7793a73036a3ba0d5405d477b",
"_spec": "concat-map@0.0.1",
"_where": "/Users/Chorthip/Documents/GitKraken/nasaproject/node_modules/brace-expansion",
"author": {
"name": "James Halliday",
"email": "mail@substack.net",
"url": "http://substack.net"
},
"bugs": {
"url": "https://github.com/substack/node-concat-map/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "concatenative mapdashery",
"devDependencies": {
"tape": "~2.4.0"
},
"directories": {
"example": "example",
"test": "test"
},
"homepage": "https://github.com/substack/node-concat-map#readme",
"keywords": [
"concat",
"concatMap",
"map",
"functional",
"higher-order"
],
"license": "MIT",
"main": "index.js",
"name": "concat-map",
"repository": {
"type": "git",
"url": "git://github.com/substack/node-concat-map.git"
},
"scripts": {
"test": "tape test/*.js"
},
"testling": {
"files": "test/*.js",
"browsers": {
"ie": [
6,
7,
8,
9
],
"ff": [
3.5,
10,
15
],
"chrome": [
10,
22
],
"safari": [
5.1
],
"opera": [
12
]
}
},
"version": "0.0.1"
}
var concatMap = require('../');
var test = require('tape');
test('empty or not', function (t) {
var xs = [ 1, 2, 3, 4, 5, 6 ];
var ixes = [];
var ys = concatMap(xs, function (x, ix) {
ixes.push(ix);
return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
});
t.same(ys, [ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]);
t.same(ixes, [ 0, 1, 2, 3, 4, 5 ]);
t.end();
});
test('always something', function (t) {
var xs = [ 'a', 'b', 'c', 'd' ];
var ys = concatMap(xs, function (x) {
return x === 'b' ? [ 'B', 'B', 'B' ] : [ x ];
});
t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]);
t.end();
});
test('scalars', function (t) {
var xs = [ 'a', 'b', 'c', 'd' ];
var ys = concatMap(xs, function (x) {
return x === 'b' ? [ 'B', 'B', 'B' ] : x;
});
t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]);
t.end();
});
test('undefs', function (t) {
var xs = [ 'a', 'b', 'c', 'd' ];
var ys = concatMap(xs, function () {});
t.same(ys, [ undefined, undefined, undefined, undefined ]);
t.end();
});
'use strict';
const path = require('path');
const os = require('os');
const fs = require('graceful-fs');
const makeDir = require('make-dir');
const xdgBasedir = require('xdg-basedir');
const writeFileAtomic = require('write-file-atomic');
const dotProp = require('dot-prop');
const uniqueString = require('unique-string');
const configDir = xdgBasedir.config || path.join(os.tmpdir(), uniqueString());
const permissionError = 'You don\'t have access to this file.';
const makeDirOptions = {mode: 0o0700};
const writeFileOptions = {mode: 0o0600};
class Configstore {
constructor(id, defaults, opts) {
opts = opts || {};
const pathPrefix = opts.globalConfigPath ?
path.join(id, 'config.json') :
path.join('configstore', `${id}.json`);
this.path = path.join(configDir, pathPrefix);
this.all = Object.assign({}, defaults, this.all);
}
get all() {
try {
return JSON.parse(fs.readFileSync(this.path, 'utf8'));
} catch (err) {
// Create dir if it doesn't exist
if (err.code === 'ENOENT') {
makeDir.sync(path.dirname(this.path), makeDirOptions);
return {};
}
// Improve the message of permission errors
if (err.code === 'EACCES') {
err.message = `${err.message}\n${permissionError}\n`;
}
// Empty the file if it encounters invalid JSON
if (err.name === 'SyntaxError') {
writeFileAtomic.sync(this.path, '', writeFileOptions);
return {};
}
throw err;
}
}
set all(val) {
try {
// Make sure the folder exists as it could have been deleted in the meantime
makeDir.sync(path.dirname(this.path), makeDirOptions);
writeFileAtomic.sync(this.path, JSON.stringify(val, null, '\t'), writeFileOptions);
} catch (err) {
// Improve the message of permission errors
if (err.code === 'EACCES') {
err.message = `${err.message}\n${permissionError}\n`;
}
throw err;
}
}
get size() {
return Object.keys(this.all || {}).length;
}
get(key) {
return dotProp.get(this.all, key);
}
set(key, val) {
const config = this.all;
if (arguments.length === 1) {
for (const k of Object.keys(key)) {
dotProp.set(config, k, key[k]);
}
} else {
dotProp.set(config, key, val);
}
this.all = config;
}
has(key) {
return dotProp.has(this.all, key);
}
delete(key) {
const config = this.all;
dotProp.delete(config, key);
this.all = config;
}
clear() {
this.all = {};
}
}
module.exports = Configstore;
Copyright Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE 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 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
{
"_from": "configstore@^3.0.0",
"_id": "configstore@3.1.2",
"_inBundle": false,
"_integrity": "sha512-vtv5HtGjcYUgFrXc6Kx747B83MRRVS5R1VTEQoXvuP+kMI+if6uywV0nDGoiydJRy4yk7h9od5Og0kxx4zUXmw==",
"_location": "/configstore",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "configstore@^3.0.0",
"name": "configstore",
"escapedName": "configstore",
"rawSpec": "^3.0.0",
"saveSpec": null,
"fetchSpec": "^3.0.0"
},
"_requiredBy": [
"/update-notifier"
],
"_resolved": "https://registry.npmjs.org/configstore/-/configstore-3.1.2.tgz",
"_shasum": "c6f25defaeef26df12dd33414b001fe81a543f8f",
"_spec": "configstore@^3.0.0",
"_where": "/Users/Chorthip/Documents/GitKraken/nasaproject/node_modules/update-notifier",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/yeoman/configstore/issues"
},
"bundleDependencies": false,
"dependencies": {
"dot-prop": "^4.1.0",
"graceful-fs": "^4.1.2",
"make-dir": "^1.0.0",
"unique-string": "^1.0.0",
"write-file-atomic": "^2.0.0",
"xdg-basedir": "^3.0.0"
},
"deprecated": false,
"description": "Easily load and save config without having to think about where and how",
"devDependencies": {
"ava": "*",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/yeoman/configstore#readme",
"keywords": [
"config",
"store",
"storage",
"conf",
"configuration",
"settings",
"preferences",
"json",
"data",
"persist",
"persistent",
"save"
],
"license": "BSD-2-Clause",
"name": "configstore",
"repository": {
"type": "git",
"url": "git+https://github.com/yeoman/configstore.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "3.1.2"
}
# configstore [![Build Status](https://travis-ci.org/yeoman/configstore.svg?branch=master)](https://travis-ci.org/yeoman/configstore)
> Easily load and persist config without having to think about where and how
Config is stored in a JSON file located in `$XDG_CONFIG_HOME` or `~/.config`.<br>
Example: `~/.config/configstore/some-id.json`
*If you need this for Electron, check out [`electron-store`](https://github.com/sindresorhus/electron-store) instead.*
## Usage
```js
const Configstore = require('configstore');
const pkg = require('./package.json');
// create a Configstore instance with an unique ID e.g.
// Package name and optionally some default values
const conf = new Configstore(pkg.name, {foo: 'bar'});
console.log(conf.get('foo'));
//=> 'bar'
conf.set('awesome', true);
console.log(conf.get('awesome'));
//=> true
// Use dot-notation to access nested properties
conf.set('bar.baz', true);
console.log(conf.get('bar'));
//=> {baz: true}
conf.delete('awesome');
console.log(conf.get('awesome'));
//=> undefined
```
## API
### Configstore(packageName, [defaults], [options])
Returns a new instance.
#### packageName
Type: `string`
Name of your package.
#### defaults
Type: `Object`
Default config.
#### options
##### globalConfigPath
Type: `boolean`<br>
Default: `false`
Store the config at `$CONFIG/package-name/config.json` instead of the default `$CONFIG/configstore/package-name.json`. This is not recommended as you might end up conflicting with other tools, rendering the "without having to think" idea moot.
### Instance
You can use [dot-notation](https://github.com/sindresorhus/dot-prop) in a `key` to access nested properties.
### .set(key, value)
Set an item.
### .set(object)
Set multiple items at once.
### .get(key)
Get an item.
### .has(key)
Check if an item exists.
### .delete(key)
Delete an item.
### .clear()
Delete all items.
### .size
Get the item count.
### .path
Get the path to the config file. Can be used to show the user where the config file is located or even better open it for them.
### .all
Get all the config as an object or replace the current config with an object:
```js
conf.all = {
hello: 'world'
};
```
## License
[BSD license](http://opensource.org/licenses/bsd-license.php)<br>
Copyright Google
0.5.2 / 2016-12-08
==================
* Fix `parse` to accept any linear whitespace character
0.5.1 / 2016-01-17
==================
* perf: enable strict mode
0.5.0 / 2014-10-11
==================
* Add `parse` function
0.4.0 / 2014-09-21
==================
* Expand non-Unicode `filename` to the full ISO-8859-1 charset
0.3.0 / 2014-09-20
==================
* Add `fallback` option
* Add `type` option
0.2.0 / 2014-09-19
==================
* Reduce ambiguity of file names with hex escape in buggy browsers
0.1.2 / 2014-09-19
==================
* Fix periodic invalid Unicode filename header
0.1.1 / 2014-09-19
==================
* Fix invalid characters appearing in `filename*` parameter
0.1.0 / 2014-09-18
==================
* Make the `filename` argument optional
0.0.0 / 2014-09-18
==================
* Initial release
(The MIT License)
Copyright (c) 2014 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.
# content-disposition
[![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]
Create and parse HTTP `Content-Disposition` header
## Installation
```sh
$ npm install content-disposition
```
## API
```js
var contentDisposition = require('content-disposition')
```
### contentDisposition(filename, options)
Create an attachment `Content-Disposition` header value using the given file name,
if supplied. The `filename` is optional and if no file name is desired, but you
want to specify `options`, set `filename` to `undefined`.
```js
res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf'))
```
**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this
header through a means different from `setHeader` in Node.js, you'll want to specify
the `'binary'` encoding in Node.js.
#### Options
`contentDisposition` accepts these properties in the options object.
##### fallback
If the `filename` option is outside ISO-8859-1, then the file name is actually
stored in a supplemental field for clients that support Unicode file names and
a ISO-8859-1 version of the file name is automatically generated.
This specifies the ISO-8859-1 file name to override the automatic generation or
disables the generation all together, defaults to `true`.
- A string will specify the ISO-8859-1 file name to use in place of automatic
generation.
- `false` will disable including a ISO-8859-1 file name and only include the
Unicode version (unless the file name is already ISO-8859-1).
- `true` will enable automatic generation if the file name is outside ISO-8859-1.
If the `filename` option is ISO-8859-1 and this option is specified and has a
different value, then the `filename` option is encoded in the extended field
and this set as the fallback field, even though they are both ISO-8859-1.
##### type
Specifies the disposition type, defaults to `"attachment"`. This can also be
`"inline"`, or any other value (all values except inline are treated like
`attachment`, but can convey additional information if both parties agree to
it). The type is normalized to lower-case.
### contentDisposition.parse(string)
```js
var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt');
```
Parse a `Content-Disposition` header string. This automatically handles extended
("Unicode") parameters by decoding them and providing them under the standard
parameter name. This will return an object with the following properties (examples
are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`):
- `type`: The disposition type (always lower case). Example: `'attachment'`
- `parameters`: An object of the parameters in the disposition (name of parameter
always lower case and extended versions replace non-extended versions). Example:
`{filename: "€ rates.txt"}`
## Examples
### Send a file for download
```js
var contentDisposition = require('content-disposition')
var destroy = require('destroy')
var http = require('http')
var onFinished = require('on-finished')
var filePath = '/path/to/public/plans.pdf'
http.createServer(function onRequest(req, res) {
// set headers
res.setHeader('Content-Type', 'application/pdf')
res.setHeader('Content-Disposition', contentDisposition(filePath))
// send file
var stream = fs.createReadStream(filePath)
stream.pipe(res)
onFinished(res, function (err) {
destroy(stream)
})
})
```
## Testing
```sh
$ npm test
```
## References
- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616]
- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987]
- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266]
- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231]
[rfc-2616]: https://tools.ietf.org/html/rfc2616
[rfc-5987]: https://tools.ietf.org/html/rfc5987
[rfc-6266]: https://tools.ietf.org/html/rfc6266
[tc-2231]: http://greenbytes.de/tech/tc2231/
## License
[MIT](LICENSE)
[npm-image]: https://img.shields.io/npm/v/content-disposition.svg?style=flat
[npm-url]: https://npmjs.org/package/content-disposition
[node-version-image]: https://img.shields.io/node/v/content-disposition.svg?style=flat
[node-version-url]: https://nodejs.org/en/download
[travis-image]: https://img.shields.io/travis/jshttp/content-disposition.svg?style=flat
[travis-url]: https://travis-ci.org/jshttp/content-disposition
[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg?style=flat
[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master
[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg?style=flat
[downloads-url]: https://npmjs.org/package/content-disposition
/*!
* content-disposition
* Copyright(c) 2014 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module exports.
*/
module.exports = contentDisposition
module.exports.parse = parse
/**
* Module dependencies.
*/
var basename = require('path').basename
/**
* RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%")
*/
var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex
/**
* RegExp to match percent encoding escape.
*/
var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/
var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g
/**
* RegExp to match non-latin1 characters.
*/
var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g
/**
* RegExp to match quoted-pair in RFC 2616
*
* quoted-pair = "\" CHAR
* CHAR = <any US-ASCII character (octets 0 - 127)>
*/
var QESC_REGEXP = /\\([\u0000-\u007f])/g
/**
* RegExp to match chars that must be quoted-pair in RFC 2616
*/
var QUOTE_REGEXP = /([\\"])/g
/**
* RegExp for various RFC 2616 grammar
*
* parameter = token "=" ( token | quoted-string )
* token = 1*<any CHAR except CTLs or separators>
* separators = "(" | ")" | "<" | ">" | "@"
* | "," | ";" | ":" | "\" | <">
* | "/" | "[" | "]" | "?" | "="
* | "{" | "}" | SP | HT
* quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
* qdtext = <any TEXT except <">>
* quoted-pair = "\" CHAR
* CHAR = <any US-ASCII character (octets 0 - 127)>
* TEXT = <any OCTET except CTLs, but including LWS>
* LWS = [CRLF] 1*( SP | HT )
* CRLF = CR LF
* CR = <US-ASCII CR, carriage return (13)>
* LF = <US-ASCII LF, linefeed (10)>
* SP = <US-ASCII SP, space (32)>
* HT = <US-ASCII HT, horizontal-tab (9)>
* CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
* OCTET = <any 8-bit sequence of data>
*/
var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex
var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/
var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/
/**
* RegExp for various RFC 5987 grammar
*
* ext-value = charset "'" [ language ] "'" value-chars
* charset = "UTF-8" / "ISO-8859-1" / mime-charset
* mime-charset = 1*mime-charsetc
* mime-charsetc = ALPHA / DIGIT
* / "!" / "#" / "$" / "%" / "&"
* / "+" / "-" / "^" / "_" / "`"
* / "{" / "}" / "~"
* language = ( 2*3ALPHA [ extlang ] )
* / 4ALPHA
* / 5*8ALPHA
* extlang = *3( "-" 3ALPHA )
* value-chars = *( pct-encoded / attr-char )
* pct-encoded = "%" HEXDIG HEXDIG
* attr-char = ALPHA / DIGIT
* / "!" / "#" / "$" / "&" / "+" / "-" / "."
* / "^" / "_" / "`" / "|" / "~"
*/
var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/
/**
* RegExp for various RFC 6266 grammar
*
* disposition-type = "inline" | "attachment" | disp-ext-type
* disp-ext-type = token
* disposition-parm = filename-parm | disp-ext-parm
* filename-parm = "filename" "=" value
* | "filename*" "=" ext-value
* disp-ext-parm = token "=" value
* | ext-token "=" ext-value
* ext-token = <the characters in token, followed by "*">
*/
var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex
/**
* Create an attachment Content-Disposition header.
*
* @param {string} [filename]
* @param {object} [options]
* @param {string} [options.type=attachment]
* @param {string|boolean} [options.fallback=true]
* @return {string}
* @api public
*/
function contentDisposition (filename, options) {
var opts = options || {}
// get type
var type = opts.type || 'attachment'
// get parameters
var params = createparams(filename, opts.fallback)
// format into string
return format(new ContentDisposition(type, params))
}
/**
* Create parameters object from filename and fallback.
*
* @param {string} [filename]
* @param {string|boolean} [fallback=true]
* @return {object}
* @api private
*/
function createparams (filename, fallback) {
if (filename === undefined) {
return
}
var params = {}
if (typeof filename !== 'string') {
throw new TypeError('filename must be a string')
}
// fallback defaults to true
if (fallback === undefined) {
fallback = true
}
if (typeof fallback !== 'string' && typeof fallback !== 'boolean') {
throw new TypeError('fallback must be a string or boolean')
}
if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) {
throw new TypeError('fallback must be ISO-8859-1 string')
}
// restrict to file base name
var name = basename(filename)
// determine if name is suitable for quoted string
var isQuotedString = TEXT_REGEXP.test(name)
// generate fallback name
var fallbackName = typeof fallback !== 'string'
? fallback && getlatin1(name)
: basename(fallback)
var hasFallback = typeof fallbackName === 'string' && fallbackName !== name
// set extended filename parameter
if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) {
params['filename*'] = name
}
// set filename parameter
if (isQuotedString || hasFallback) {
params.filename = hasFallback
? fallbackName
: name
}
return params
}
/**
* Format object to Content-Disposition header.
*
* @param {object} obj
* @param {string} obj.type
* @param {object} [obj.parameters]
* @return {string}
* @api private
*/
function format (obj) {
var parameters = obj.parameters
var type = obj.type
if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) {
throw new TypeError('invalid type')
}
// start with normalized type
var string = String(type).toLowerCase()
// append parameters
if (parameters && typeof parameters === 'object') {
var param
var params = Object.keys(parameters).sort()
for (var i = 0; i < params.length; i++) {
param = params[i]
var val = param.substr(-1) === '*'
? ustring(parameters[param])
: qstring(parameters[param])
string += '; ' + param + '=' + val
}
}
return string
}
/**
* Decode a RFC 6987 field value (gracefully).
*
* @param {string} str
* @return {string}
* @api private
*/
function decodefield (str) {
var match = EXT_VALUE_REGEXP.exec(str)
if (!match) {
throw new TypeError('invalid extended field value')
}
var charset = match[1].toLowerCase()
var encoded = match[2]
var value
// to binary string
var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode)
switch (charset) {
case 'iso-8859-1':
value = getlatin1(binary)
break
case 'utf-8':
value = new Buffer(binary, 'binary').toString('utf8')
break
default:
throw new TypeError('unsupported charset in extended field')
}
return value
}
/**
* Get ISO-8859-1 version of string.
*
* @param {string} val
* @return {string}
* @api private
*/
function getlatin1 (val) {
// simple Unicode -> ISO-8859-1 transformation
return String(val).replace(NON_LATIN1_REGEXP, '?')
}
/**
* Parse Content-Disposition header string.
*
* @param {string} string
* @return {object}
* @api private
*/
function parse (string) {
if (!string || typeof string !== 'string') {
throw new TypeError('argument string is required')
}
var match = DISPOSITION_TYPE_REGEXP.exec(string)
if (!match) {
throw new TypeError('invalid type format')
}
// normalize type
var index = match[0].length
var type = match[1].toLowerCase()
var key
var names = []
var params = {}
var value
// calculate index to start at
index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';'
? index - 1
: index
// match parameters
while ((match = PARAM_REGEXP.exec(string))) {
if (match.index !== index) {
throw new TypeError('invalid parameter format')
}
index += match[0].length
key = match[1].toLowerCase()
value = match[2]
if (names.indexOf(key) !== -1) {
throw new TypeError('invalid duplicate parameter')
}
names.push(key)
if (key.indexOf('*') + 1 === key.length) {
// decode extended value
key = key.slice(0, -1)
value = decodefield(value)
// overwrite existing value
params[key] = value
continue
}
if (typeof params[key] === 'string') {
continue
}
if (value[0] === '"') {
// remove quotes and escapes
value = value
.substr(1, value.length - 2)
.replace(QESC_REGEXP, '$1')
}
params[key] = value
}
if (index !== -1 && index !== string.length) {
throw new TypeError('invalid parameter format')
}
return new ContentDisposition(type, params)
}
/**
* Percent decode a single character.
*
* @param {string} str
* @param {string} hex
* @return {string}
* @api private
*/
function pdecode (str, hex) {
return String.fromCharCode(parseInt(hex, 16))
}
/**
* Percent encode a single character.
*
* @param {string} char
* @return {string}
* @api private
*/
function pencode (char) {
var hex = String(char)
.charCodeAt(0)
.toString(16)
.toUpperCase()
return hex.length === 1
? '%0' + hex
: '%' + hex
}
/**
* Quote a string for HTTP.
*
* @param {string} val
* @return {string}
* @api private
*/
function qstring (val) {
var str = String(val)
return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"'
}
/**
* Encode a Unicode string for HTTP (RFC 5987).
*
* @param {string} val
* @return {string}
* @api private
*/
function ustring (val) {
var str = String(val)
// percent encode as UTF-8
var encoded = encodeURIComponent(str)
.replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode)
return 'UTF-8\'\'' + encoded
}
/**
* Class for parsed Content-Disposition header for v8 optimization
*/
function ContentDisposition (type, parameters) {
this.type = type
this.parameters = parameters
}
{
"_args": [
[
{
"raw": "content-disposition@0.5.2",
"scope": null,
"escapedName": "content-disposition",
"name": "content-disposition",
"rawSpec": "0.5.2",
"spec": "0.5.2",
"type": "version"
},
"C:\\Users\\Giuliano\\Desktop\\nasaproject\\node_modules\\express"
]
],
"_from": "content-disposition@0.5.2",
"_id": "content-disposition@0.5.2",
"_inCache": true,
"_location": "/content-disposition",
"_nodeVersion": "4.6.0",
"_npmOperationalInternal": {
"host": "packages-18-east.internal.npmjs.com",
"tmp": "tmp/content-disposition-0.5.2.tgz_1481246224565_0.35659545403905213"
},
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"_npmVersion": "2.15.9",
"_phantomChildren": {},
"_requested": {
"raw": "content-disposition@0.5.2",
"scope": null,
"escapedName": "content-disposition",
"name": "content-disposition",
"rawSpec": "0.5.2",
"spec": "0.5.2",
"type": "version"
},
"_requiredBy": [
"/express"
],
"_resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz",
"_shasum": "0cf68bb9ddf5f2be7961c3a85178cb85dba78cb4",
"_shrinkwrap": null,
"_spec": "content-disposition@0.5.2",
"_where": "C:\\Users\\Giuliano\\Desktop\\nasaproject\\node_modules\\express",
"bugs": {
"url": "https://github.com/jshttp/content-disposition/issues"
},
"contributors": [
{
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
}
],
"dependencies": {},
"description": "Create and parse Content-Disposition header",
"devDependencies": {
"eslint": "3.11.1",
"eslint-config-standard": "6.2.1",
"eslint-plugin-promise": "3.3.0",
"eslint-plugin-standard": "2.0.1",
"istanbul": "0.4.5",
"mocha": "1.21.5"
},
"directories": {},
"dist": {
"shasum": "0cf68bb9ddf5f2be7961c3a85178cb85dba78cb4",
"tarball": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz"
},
"engines": {
"node": ">= 0.6"
},
"files": [
"LICENSE",
"HISTORY.md",
"README.md",
"index.js"
],
"gitHead": "2a08417377cf55678c9f870b305f3c6c088920f3",
"homepage": "https://github.com/jshttp/content-disposition#readme",
"keywords": [
"content-disposition",
"http",
"rfc6266",
"res"
],
"license": "MIT",
"maintainers": [
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"name": "content-disposition",
"optionalDependencies": {},
"readme": "# content-disposition\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\nCreate and parse HTTP `Content-Disposition` header\n\n## Installation\n\n```sh\n$ npm install content-disposition\n```\n\n## API\n\n```js\nvar contentDisposition = require('content-disposition')\n```\n\n### contentDisposition(filename, options)\n\nCreate an attachment `Content-Disposition` header value using the given file name,\nif supplied. The `filename` is optional and if no file name is desired, but you\nwant to specify `options`, set `filename` to `undefined`.\n\n```js\nres.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf'))\n```\n\n**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this\nheader through a means different from `setHeader` in Node.js, you'll want to specify\nthe `'binary'` encoding in Node.js.\n\n#### Options\n\n`contentDisposition` accepts these properties in the options object.\n\n##### fallback\n\nIf the `filename` option is outside ISO-8859-1, then the file name is actually\nstored in a supplemental field for clients that support Unicode file names and\na ISO-8859-1 version of the file name is automatically generated.\n\nThis specifies the ISO-8859-1 file name to override the automatic generation or\ndisables the generation all together, defaults to `true`.\n\n - A string will specify the ISO-8859-1 file name to use in place of automatic\n generation.\n - `false` will disable including a ISO-8859-1 file name and only include the\n Unicode version (unless the file name is already ISO-8859-1).\n - `true` will enable automatic generation if the file name is outside ISO-8859-1.\n\nIf the `filename` option is ISO-8859-1 and this option is specified and has a\ndifferent value, then the `filename` option is encoded in the extended field\nand this set as the fallback field, even though they are both ISO-8859-1.\n\n##### type\n\nSpecifies the disposition type, defaults to `\"attachment\"`. This can also be\n`\"inline\"`, or any other value (all values except inline are treated like\n`attachment`, but can convey additional information if both parties agree to\nit). The type is normalized to lower-case.\n\n### contentDisposition.parse(string)\n\n```js\nvar disposition = contentDisposition.parse('attachment; filename=\"EURO rates.txt\"; filename*=UTF-8\\'\\'%e2%82%ac%20rates.txt');\n```\n\nParse a `Content-Disposition` header string. This automatically handles extended\n(\"Unicode\") parameters by decoding them and providing them under the standard\nparameter name. This will return an object with the following properties (examples\nare shown for the string `'attachment; filename=\"EURO rates.txt\"; filename*=UTF-8\\'\\'%e2%82%ac%20rates.txt'`):\n\n - `type`: The disposition type (always lower case). Example: `'attachment'`\n\n - `parameters`: An object of the parameters in the disposition (name of parameter\n always lower case and extended versions replace non-extended versions). Example:\n `{filename: \"€ rates.txt\"}`\n\n## Examples\n\n### Send a file for download\n\n```js\nvar contentDisposition = require('content-disposition')\nvar destroy = require('destroy')\nvar http = require('http')\nvar onFinished = require('on-finished')\n\nvar filePath = '/path/to/public/plans.pdf'\n\nhttp.createServer(function onRequest(req, res) {\n // set headers\n res.setHeader('Content-Type', 'application/pdf')\n res.setHeader('Content-Disposition', contentDisposition(filePath))\n\n // send file\n var stream = fs.createReadStream(filePath)\n stream.pipe(res)\n onFinished(res, function (err) {\n destroy(stream)\n })\n})\n```\n\n## Testing\n\n```sh\n$ npm test\n```\n\n## References\n\n- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616]\n- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987]\n- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266]\n- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231]\n\n[rfc-2616]: https://tools.ietf.org/html/rfc2616\n[rfc-5987]: https://tools.ietf.org/html/rfc5987\n[rfc-6266]: https://tools.ietf.org/html/rfc6266\n[tc-2231]: http://greenbytes.de/tech/tc2231/\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/content-disposition.svg?style=flat\n[npm-url]: https://npmjs.org/package/content-disposition\n[node-version-image]: https://img.shields.io/node/v/content-disposition.svg?style=flat\n[node-version-url]: https://nodejs.org/en/download\n[travis-image]: https://img.shields.io/travis/jshttp/content-disposition.svg?style=flat\n[travis-url]: https://travis-ci.org/jshttp/content-disposition\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg?style=flat\n[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg?style=flat\n[downloads-url]: https://npmjs.org/package/content-disposition\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/jshttp/content-disposition.git"
},
"scripts": {
"lint": "eslint .",
"test": "mocha --reporter spec --bail --check-leaks test/",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/"
},
"version": "0.5.2"
}
1.0.2 / 2016-05-09
==================
* perf: enable strict mode
1.0.1 / 2015-02-13
==================
* Improve missing `Content-Type` header error message
1.0.0 / 2015-02-01
==================
* Initial implementation, derived from `media-typer@0.3.0`
(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.
# content-type
[![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]
Create and parse HTTP Content-Type header according to RFC 7231
## Installation
```sh
$ npm install content-type
```
## API
```js
var contentType = require('content-type')
```
### contentType.parse(string)
```js
var obj = contentType.parse('image/svg+xml; charset=utf-8')
```
Parse a content type string. 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 (the type and subtype, always lower case).
Example: `'image/svg+xml'`
- `parameters`: An object of the parameters in the media type (name of parameter
always lower case). Example: `{charset: 'utf-8'}`
Throws a `TypeError` if the string is missing or invalid.
### contentType.parse(req)
```js
var obj = contentType.parse(req)
```
Parse the `content-type` header from the given `req`. Short-cut for
`contentType.parse(req.headers['content-type'])`.
Throws a `TypeError` if the `Content-Type` header is missing or invalid.
### contentType.parse(res)
```js
var obj = contentType.parse(res)
```
Parse the `content-type` header set on the given `res`. Short-cut for
`contentType.parse(res.getHeader('content-type'))`.
Throws a `TypeError` if the `Content-Type` header is missing or invalid.
### contentType.format(obj)
```js
var str = contentType.format({type: 'image/svg+xml'})
```
Format an object into a content type string. 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 (will be lower-cased). Example: `'image/svg+xml'`
- `parameters`: An object of the parameters in the media type (name of the
parameter will be lower-cased). 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.svg
[npm-url]: https://npmjs.org/package/content-type
[node-version-image]: https://img.shields.io/node/v/content-type.svg
[node-version-url]: http://nodejs.org/download/
[travis-image]: https://img.shields.io/travis/jshttp/content-type/master.svg
[travis-url]: https://travis-ci.org/jshttp/content-type
[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-type/master.svg
[coveralls-url]: https://coveralls.io/r/jshttp/content-type
[downloads-image]: https://img.shields.io/npm/dm/content-type.svg
[downloads-url]: https://npmjs.org/package/content-type
/*!
* content-type
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
*
* parameter = token "=" ( token / quoted-string )
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
* / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
* / DIGIT / ALPHA
* ; any VCHAR, except delimiters
* quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
* qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
* obs-text = %x80-FF
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
*/
var paramRegExp = /; *([!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) */g
var textRegExp = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/
var tokenRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/
/**
* RegExp to match quoted-pair in RFC 7230 sec 3.2.6
*
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
* obs-text = %x80-FF
*/
var qescRegExp = /\\([\u000b\u0020-\u00ff])/g
/**
* RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6
*/
var quoteRegExp = /([\\"])/g
/**
* RegExp to match type in RFC 6838
*
* media-type = type "/" subtype
* type = token
* subtype = token
*/
var typeRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+\/[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/
/**
* Module exports.
* @public
*/
exports.format = format
exports.parse = parse
/**
* Format object to media type.
*
* @param {object} obj
* @return {string}
* @public
*/
function format(obj) {
if (!obj || typeof obj !== 'object') {
throw new TypeError('argument obj is required')
}
var parameters = obj.parameters
var type = obj.type
if (!type || !typeRegExp.test(type)) {
throw new TypeError('invalid type')
}
var string = type
// append parameters
if (parameters && typeof parameters === 'object') {
var param
var params = Object.keys(parameters).sort()
for (var i = 0; i < params.length; i++) {
param = params[i]
if (!tokenRegExp.test(param)) {
throw new TypeError('invalid parameter name')
}
string += '; ' + param + '=' + qstring(parameters[param])
}
}
return string
}
/**
* Parse media type to object.
*
* @param {string|object} string
* @return {Object}
* @public
*/
function parse(string) {
if (!string) {
throw new TypeError('argument string is required')
}
if (typeof string === 'object') {
// support req/res-like objects as argument
string = getcontenttype(string)
if (typeof string !== 'string') {
throw new TypeError('content-type header is missing from object');
}
}
if (typeof string !== 'string') {
throw new TypeError('argument string is required to be a string')
}
var index = string.indexOf(';')
var type = index !== -1
? string.substr(0, index).trim()
: string.trim()
if (!typeRegExp.test(type)) {
throw new TypeError('invalid media type')
}
var key
var match
var obj = new ContentType(type.toLowerCase())
var value
paramRegExp.lastIndex = index
while (match = paramRegExp.exec(string)) {
if (match.index !== index) {
throw new TypeError('invalid parameter format')
}
index += match[0].length
key = match[1].toLowerCase()
value = match[2]
if (value[0] === '"') {
// remove quotes and escapes
value = value
.substr(1, value.length - 2)
.replace(qescRegExp, '$1')
}
obj.parameters[key] = value
}
if (index !== -1 && index !== string.length) {
throw new TypeError('invalid parameter format')
}
return obj
}
/**
* Get content-type from req/res objects.
*
* @param {object}
* @return {Object}
* @private
*/
function getcontenttype(obj) {
if (typeof obj.getHeader === 'function') {
// res-like
return obj.getHeader('content-type')
}
if (typeof obj.headers === 'object') {
// req-like
return obj.headers && obj.headers['content-type']
}
}
/**
* Quote a string if necessary.
*
* @param {string} val
* @return {string}
* @private
*/
function qstring(val) {
var str = String(val)
// no need to quote tokens
if (tokenRegExp.test(str)) {
return str
}
if (str.length > 0 && !textRegExp.test(str)) {
throw new TypeError('invalid parameter value')
}
return '"' + str.replace(quoteRegExp, '\\$1') + '"'
}
/**
* Class to represent a content type.
* @private
*/
function ContentType(type) {
this.parameters = Object.create(null)
this.type = type
}
{
"_args": [
[
{
"raw": "content-type@~1.0.2",
"scope": null,
"escapedName": "content-type",
"name": "content-type",
"rawSpec": "~1.0.2",
"spec": ">=1.0.2 <1.1.0",
"type": "range"
},
"C:\\Users\\Giuliano\\Desktop\\nasaproject\\node_modules\\express"
]
],
"_from": "content-type@>=1.0.2 <1.1.0",
"_id": "content-type@1.0.2",
"_inCache": true,
"_location": "/content-type",
"_nodeVersion": "4.4.3",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/content-type-1.0.2.tgz_1462852785748_0.5491233412176371"
},
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
},
"_npmVersion": "2.15.1",
"_phantomChildren": {},
"_requested": {
"raw": "content-type@~1.0.2",
"scope": null,
"escapedName": "content-type",
"name": "content-type",
"rawSpec": "~1.0.2",
"spec": ">=1.0.2 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/express"
],
"_resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.2.tgz",
"_shasum": "b7d113aee7a8dd27bd21133c4dc2529df1721eed",
"_shrinkwrap": null,
"_spec": "content-type@~1.0.2",
"_where": "C:\\Users\\Giuliano\\Desktop\\nasaproject\\node_modules\\express",
"author": {
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
},
"bugs": {
"url": "https://github.com/jshttp/content-type/issues"
},
"dependencies": {},
"description": "Create and parse HTTP Content-Type header",
"devDependencies": {
"istanbul": "0.4.3",
"mocha": "~1.21.5"
},
"directories": {},
"dist": {
"shasum": "b7d113aee7a8dd27bd21133c4dc2529df1721eed",
"tarball": "https://registry.npmjs.org/content-type/-/content-type-1.0.2.tgz"
},
"engines": {
"node": ">= 0.6"
},
"files": [
"LICENSE",
"HISTORY.md",
"README.md",
"index.js"
],
"gitHead": "8118763adfbbac80cf1254191889330aec8b8be7",
"homepage": "https://github.com/jshttp/content-type#readme",
"keywords": [
"content-type",
"http",
"req",
"res",
"rfc7231"
],
"license": "MIT",
"maintainers": [
{
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"name": "content-type",
"optionalDependencies": {},
"readme": "# content-type\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\nCreate and parse HTTP Content-Type header according to RFC 7231\n\n## Installation\n\n```sh\n$ npm install content-type\n```\n\n## API\n\n```js\nvar contentType = require('content-type')\n```\n\n### contentType.parse(string)\n\n```js\nvar obj = contentType.parse('image/svg+xml; charset=utf-8')\n```\n\nParse a content type string. This will return an object with the following\nproperties (examples are shown for the string `'image/svg+xml; charset=utf-8'`):\n\n - `type`: The media type (the type and subtype, always lower case).\n Example: `'image/svg+xml'`\n\n - `parameters`: An object of the parameters in the media type (name of parameter\n always lower case). Example: `{charset: 'utf-8'}`\n\nThrows a `TypeError` if the string is missing or invalid.\n\n### contentType.parse(req)\n\n```js\nvar obj = contentType.parse(req)\n```\n\nParse the `content-type` header from the given `req`. Short-cut for\n`contentType.parse(req.headers['content-type'])`.\n\nThrows a `TypeError` if the `Content-Type` header is missing or invalid.\n\n### contentType.parse(res)\n\n```js\nvar obj = contentType.parse(res)\n```\n\nParse the `content-type` header set on the given `res`. Short-cut for\n`contentType.parse(res.getHeader('content-type'))`.\n\nThrows a `TypeError` if the `Content-Type` header is missing or invalid.\n\n### contentType.format(obj)\n\n```js\nvar str = contentType.format({type: 'image/svg+xml'})\n```\n\nFormat an object into a content type string. This will return a string of the\ncontent type for the given object with the following properties (examples are\nshown that produce the string `'image/svg+xml; charset=utf-8'`):\n\n - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'`\n\n - `parameters`: An object of the parameters in the media type (name of the\n parameter will be lower-cased). Example: `{charset: 'utf-8'}`\n\nThrows a `TypeError` if the object contains an invalid type or parameter names.\n\n## License\n\n[MIT](LICENSE)\n\n[npm-image]: https://img.shields.io/npm/v/content-type.svg\n[npm-url]: https://npmjs.org/package/content-type\n[node-version-image]: https://img.shields.io/node/v/content-type.svg\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/jshttp/content-type/master.svg\n[travis-url]: https://travis-ci.org/jshttp/content-type\n[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-type/master.svg\n[coveralls-url]: https://coveralls.io/r/jshttp/content-type\n[downloads-image]: https://img.shields.io/npm/dm/content-type.svg\n[downloads-url]: https://npmjs.org/package/content-type\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/jshttp/content-type.git"
},
"scripts": {
"test": "mocha --reporter spec --check-leaks --bail 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": "1.0.2"
}
support
test
examples
*.sock
1.0.6 / 2015-02-03
==================
* use `npm test` instead of `make test` to run tests
* clearer assertion messages when checking input
1.0.5 / 2014-09-05
==================
* add license to package.json
1.0.4 / 2014-06-25
==================
* corrected avoidance of timing attacks (thanks @tenbits!)
1.0.3 / 2014-01-28
==================
* [incorrect] fix for timing attacks
1.0.2 / 2014-01-28
==================
* fix missing repository warning
* fix typo in test
1.0.1 / 2013-04-15
==================
* Revert "Changed underlying HMAC algo. to sha512."
* Revert "Fix for timing attacks on MAC verification."
0.0.1 / 2010-01-03
==================
* Initial release
# cookie-signature
Sign and unsign cookies.
## Example
```js
var cookie = require('cookie-signature');
var val = cookie.sign('hello', 'tobiiscool');
val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI');
var val = cookie.sign('hello', 'tobiiscool');
cookie.unsign(val, 'tobiiscool').should.equal('hello');
cookie.unsign(val, 'luna').should.be.false;
```
## License
(The MIT License)
Copyright (c) 2012 LearnBoost &lt;tj@learnboost.com&gt;
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.
\ No newline at end of file
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