8889841cindex.js000066600000014347150541235540006232 0ustar00/*! * media-typer * Copyright(c) 2014 Douglas Christopher Wilson * MIT Licensed */ /** * RegExp to match *( ";" parameter ) in RFC 2616 sec 3.7 * * parameter = token "=" ( token | quoted-string ) * token = 1* * separators = "(" | ")" | "<" | ">" | "@" * | "," | ";" | ":" | "\" | <"> * | "/" | "[" | "]" | "?" | "=" * | "{" | "}" | SP | HT * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) * qdtext = > * quoted-pair = "\" CHAR * CHAR = * TEXT = * LWS = [CRLF] 1*( SP | HT ) * CRLF = CR LF * CR = * LF = * SP = * SHT = * CTL = * OCTET = */ var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g; var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/ var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ /** * RegExp to match quoted-pair in RFC 2616 * * quoted-pair = "\" CHAR * CHAR = */ var qescRegExp = /\\([\u0000-\u007f])/g; /** * RegExp to match chars that must be quoted-pair in RFC 2616 */ var quoteRegExp = /([\\"])/g; /** * RegExp to match type in RFC 6838 * * type-name = restricted-name * subtype-name = restricted-name * restricted-name = restricted-name-first *126restricted-name-chars * restricted-name-first = ALPHA / DIGIT * restricted-name-chars = ALPHA / DIGIT / "!" / "#" / * "$" / "&" / "-" / "^" / "_" * restricted-name-chars =/ "." ; Characters before first dot always * ; specify a facet name * restricted-name-chars =/ "+" ; Characters after last plus always * ; specify a structured syntax suffix * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z * DIGIT = %x30-39 ; 0-9 */ var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/ var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/ var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; /** * Module exports. */ exports.format = format exports.parse = parse /** * Format object to media type. * * @param {object} obj * @return {string} * @api public */ function format(obj) { if (!obj || typeof obj !== 'object') { throw new TypeError('argument obj is required') } var parameters = obj.parameters var subtype = obj.subtype var suffix = obj.suffix var type = obj.type if (!type || !typeNameRegExp.test(type)) { throw new TypeError('invalid type') } if (!subtype || !subtypeNameRegExp.test(subtype)) { throw new TypeError('invalid subtype') } // format as type/subtype var string = type + '/' + subtype // append +suffix if (suffix) { if (!typeNameRegExp.test(suffix)) { throw new TypeError('invalid suffix') } string += '+' + suffix } // 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} * @api public */ function parse(string) { if (!string) { throw new TypeError('argument string is required') } // support req/res-like objects as argument if (typeof string === 'object') { string = getcontenttype(string) } 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) : string var key var match var obj = splitType(type) var params = {} 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') } params[key] = value } if (index !== -1 && index !== string.length) { throw new TypeError('invalid parameter format') } obj.parameters = params return obj } /** * Get content-type from req/res objects. * * @param {object} * @return {Object} * @api 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} * @api 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') + '"' } /** * Simply "type/subtype+siffx" into parts. * * @param {string} string * @return {Object} * @api private */ function splitType(string) { var match = typeRegExp.exec(string.toLowerCase()) if (!match) { throw new TypeError('invalid media type') } var type = match[1] var subtype = match[2] var suffix // suffix after last + var index = subtype.lastIndexOf('+') if (index !== -1) { suffix = subtype.substr(index + 1) subtype = subtype.substr(0, index) } var obj = { type: type, subtype: subtype, suffix: suffix } return obj } README.md000066600000004503150541235540006035 0ustar00# media-typer [![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] Simple RFC 6838 media type parser ## Installation ```sh $ npm install media-typer ``` ## API ```js var typer = require('media-typer') ``` ### typer.parse(string) ```js var obj = typer.parse('image/svg+xml; charset=utf-8') ``` Parse a media 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 type of the media type (always lower case). Example: `'image'` - `subtype`: The subtype of the media type (always lower case). Example: `'svg'` - `suffix`: The suffix of the media type (always lower case). Example: `'xml'` - `parameters`: An object of the parameters in the media type (name of parameter always lower case). Example: `{charset: 'utf-8'}` ### typer.parse(req) ```js var obj = typer.parse(req) ``` Parse the `content-type` header from the given `req`. Short-cut for `typer.parse(req.headers['content-type'])`. ### typer.parse(res) ```js var obj = typer.parse(res) ``` Parse the `content-type` header set on the given `res`. Short-cut for `typer.parse(res.getHeader('content-type'))`. ### typer.format(obj) ```js var obj = typer.format({type: 'image', subtype: 'svg', suffix: 'xml'}) ``` Format an object into a media type string. This will return a string of the mime type for the given object. For the properties of the object, see the documentation for `typer.parse(string)`. ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/media-typer.svg?style=flat [npm-url]: https://npmjs.org/package/media-typer [node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg?style=flat [node-version-url]: http://nodejs.org/download/ [travis-image]: https://img.shields.io/travis/jshttp/media-typer.svg?style=flat [travis-url]: https://travis-ci.org/jshttp/media-typer [coveralls-image]: https://img.shields.io/coveralls/jshttp/media-typer.svg?style=flat [coveralls-url]: https://coveralls.io/r/jshttp/media-typer [downloads-image]: https://img.shields.io/npm/dm/media-typer.svg?style=flat [downloads-url]: https://npmjs.org/package/media-typer LICENSE000066600000002101150541235540005553 0ustar00(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. HISTORY.md000066600000000715150541235540006242 0ustar000.3.0 / 2014-09-07 ================== * Support Node.js 0.6 * Throw error when parameter format invalid on parse 0.2.0 / 2014-06-18 ================== * Add `typer.format()` to format media types 0.1.0 / 2014-06-17 ================== * Accept `req` as argument to `parse` * Accept `res` as argument to `parse` * Parse media type with extra LWS between type and first parameter 0.0.0 / 2014-06-13 ================== * Initial implementation package.json000066600000001367150541235540007051 0ustar00{ "name": "media-typer", "description": "Simple RFC 6838 media type parser and formatter", "version": "0.3.0", "author": "Douglas Christopher Wilson ", "license": "MIT", "repository": "jshttp/media-typer", "devDependencies": { "istanbul": "0.3.2", "mocha": "~1.21.4", "should": "~4.0.4" }, "files": [ "LICENSE", "HISTORY.md", "index.js" ], "engines": { "node": ">= 0.6" }, "scripts": { "test": "mocha --reporter spec --check-leaks --bail 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/" } }