Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES Module conversion #92

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
env:
es6: true
parserOptions:
sourceType: "module"
rules:
eol-last: error
indent: ["error", 2, { "SwitchCase": 1 }]
Expand Down
3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
coverage/
node_modules/
npm-debug.log
package-lock.json
npm-debug.log
100 changes: 3 additions & 97 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,107 +1,13 @@
language: node_js
node_js:
- "0.6"
- "0.8"
- "0.10"
- "0.12"
- "1.8"
- "2.5"
- "3.3"
- "4.9"
- "5.12"
- "6.17"
- "7.10"
- "8.16"
- "9.11"
- "10.15"
- "11.15"
- "12.2"
- "10"
- "11"
- "12"
sudo: false
dist: trusty
env:
global:
# Suppress Node.js 0.6 compile warnings
- "CXXCOM='$CXX -o $TARGET -c $CXXFLAGS $CCFLAGS -Wno-unused-local-typedefs -Wno-maybe-uninitialized -Wno-narrowing -Wno-strict-overflow $_CCCOMCOM $SOURCES'"
cache:
directories:
- node_modules
before_install:
- |
# Setup utility functions
function node_version_lt () {
[[ "$(v "$TRAVIS_NODE_VERSION")" -lt "$(v "${1}")" ]]
}
function npm_module_installed () {
npm -lsp ls | grep -Fq "$(pwd)/node_modules/${1}:${1}@"
}
function npm_remove_module_re () {
node -e '
fs = require("fs");
p = JSON.parse(fs.readFileSync("package.json", "utf8"));
r = RegExp(process.argv[1]);
for (k in p.devDependencies) {
if (r.test(k)) delete p.devDependencies[k];
}
fs.writeFileSync("package.json", JSON.stringify(p, null, 2) + "\n");
' "$@"
}
function npm_use_module () {
node -e '
fs = require("fs");
p = JSON.parse(fs.readFileSync("package.json", "utf8"));
p.devDependencies[process.argv[1]] = process.argv[2];
fs.writeFileSync("package.json", JSON.stringify(p, null, 2) + "\n");
' "$@"
}
function v () {
tr '.' '\n' <<< "${1}" \
| awk '{ printf "%03d", $0 }' \
| sed 's/^0*//'
}
# Configure npm
- |
# Skip updating shrinkwrap / lock
npm config set shrinkwrap false
- |
# Remove benchmark dependencies
npm_remove_module_re '(^|-)benchmark$'
# Setup Node.js version-specific dependencies
- |
# Configure eslint for linting
if node_version_lt '6.0'; then npm_remove_module_re '^eslint(-|$)'
fi
- |
# Configure istanbul for coverage
if node_version_lt '0.10'; then npm_remove_module_re '^istanbul$'
fi
- |
# Configure mocha for testing
if node_version_lt '0.8' ; then npm_use_module 'mocha' '1.21.5'
elif node_version_lt '0.10'; then npm_use_module 'mocha' '2.5.3'
elif node_version_lt '4.0' ; then npm_use_module 'mocha' '3.5.3'
elif node_version_lt '6.0' ; then npm_use_module 'mocha' '5.2.0'
fi
# Update Node.js modules
- |
# Prune & rebuild node_modules
if [[ -d node_modules ]]; then
npm prune
npm rebuild
fi
before_scrpt:
- |
# Contents of node_modules
npm -s ls ||:
script:
- |
# Run test script, depending on istanbul install
if npm_module_installed 'istanbul'; then npm run-script test-ci
else npm test
fi
- |
# Run linting, if eslint exists
if npm_module_installed 'eslint'; then npm run-script lint
fi
after_script:
- |
# Upload coverage to coveralls if exists
Expand Down
41 changes: 20 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,29 @@ Basic HTTP cookie parser and serializer for HTTP servers.
## Installation

```sh
$ npm install cookie
npm install cookie
```

## API
## Basic Example

```js
var cookie = require('cookie');
import {parse, serialize } from 'cookie';
// parse a cookie string
const cookies = parse('foo=bar; equation=E%3Dmc%5E2');
console.log(cookies); // { foo: 'bar', equation: 'E=mc^2' }

// set a foo cookie to bar
serialize('foo', 'bar');
```

## API

### 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.
Expand All @@ -53,10 +56,6 @@ Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name`
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

Expand Down Expand Up @@ -132,24 +131,24 @@ the `Secure` attribute is set, otherwise it is not. By default, the `Secure` att
**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
## Advanced 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');
import { serialize, parse } from 'cookie-esm';
const escapeHtml = require('escape-html');
const http = require('http');
const url = require('url');

function onRequest(req, res) {
// Parse the query string
var query = url.parse(req.url, true, true).query;
const 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), {
res.setHeader('Set-Cookie', serialize('name', String(query.name), {
httpOnly: true,
maxAge: 60 * 60 * 24 * 7 // 1 week
}));
Expand All @@ -162,10 +161,10 @@ function onRequest(req, res) {
}

// Parse the cookies on the request
var cookies = cookie.parse(req.headers.cookie || '');
const cookies = parse(req.headers.cookie || '');

// Get the visitor name set in the cookie
var name = cookies.name;
const { name } = cookies;

res.setHeader('Content-Type', 'text/html; charset=UTF-8');

Expand Down
122 changes: 122 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
// Type definitions for cookie 0.3
// Project: https://github.com/jshttp/cookie
// Definitions by: Pine Mizune <https://github.com/pine>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

export interface CookieSerializeOptions {
/**
* Specifies the value for the Domain Set-Cookie attribute. By default, no
* domain is set, and most clients will consider the cookie to apply to only
* the current domain.
*/
domain?: string;

/**
* 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 `encodeURIComponent`, which will
* encode a JavaScript string into UTF-8 byte sequences and then URL-encode
* any that fall outside of the cookie range.
*/
encode?(val: string): string;

/**
* Specifies the `Date` object to be the value for the `Expires`
* `Set-Cookie` attribute. 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 states that if both
* `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
* possible not all clients by obey this, so if both are set, they should
* point to the same date and time.
*/
expires?: Date;
/**
* Specifies the boolean value for the `HttpOnly` `Set-Cookie` attribute.
* 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`.
*/
httpOnly?: boolean;
/**
* Specifies the number (in seconds) to be the value for the `Max-Age`
* `Set-Cookie` attribute. 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 states that if both
* `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
* possible not all clients by obey this, so if both are set, they should
* point to the same date and time.
*/
maxAge?: number;
/**
* Specifies the value for the `Path` `Set-Cookie` attribute. By default,
* the path is considered the "default path".
*/
path?: string;
/**
* Specifies the boolean or string to be the value for the `SameSite`
* `Set-Cookie` attribute.
*
* - `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.
* - `'none'` will set the SameSite attribute to None for an explicit
* cross-site cookie.
*/
sameSite?: boolean | 'lax' | 'strict' | 'none';
/**
* Specifies the boolean value for the `Secure` `Set-Cookie` attribute. 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.
*/
secure?: boolean;
}

export interface CookieParseOptions {
/**
* 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.
*/
decode?(val: string): string;
}

/**
* Parse an HTTP Cookie header string and returning an object of all cookie
* name-value pairs.
*
* @param str the string representing a `Cookie` header value
* @param options object containing parsing options
*/
export function parse(str: string, options?: CookieParseOptions): { [key: string]: string };

/**
* Serialize a cookie name-value pair into a `Set-Cookie` header string.
*
* @param name the name for the cookie
* @param val value to set the cookie to
* @param options object containing serialization options
*/
export function serialize(name: string, val: string, options?: CookieSerializeOptions): string;
13 changes: 3 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,12 @@
* cookie
* Copyright(c) 2012-2014 Roman Shtylman
* Copyright(c) 2015 Douglas Christopher Wilson
* Copyright(c) 2019 Mark Kennedy
* MIT Licensed
*/

'use strict';

/**
* Module exports.
* @public
*/

exports.parse = parse;
exports.serialize = serialize;

/**
* Module variables.
* @private
Expand Down Expand Up @@ -46,7 +39,7 @@ var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
* @public
*/

function parse(str, options) {
export function parse(str, options) {
if (typeof str !== 'string') {
throw new TypeError('argument str must be a string');
}
Expand Down Expand Up @@ -98,7 +91,7 @@ function parse(str, options) {
* @public
*/

function serialize(name, val, options) {
export function serialize(name, val, options) {
var opt = options || {};
var enc = opt.encode || encode;

Expand Down
Loading