Commit 0ecde801 by 马玮

fetch clues but not full

parent 5f399561

4.92 KB | W: | H:

713 KB | W: | H:

m2.png
m2.png
m2.png
m2.png
  • 2-up
  • Swipe
  • Onion skin
m3.png

269 KB

m4.png

104 KB

All packages installed at Sun Aug 06 2017 23:20:43 GMT+0800 (CST)
\ No newline at end of file
All packages installed at Mon Aug 07 2017 19:51:45 GMT+0800 (CST)
\ No newline at end of file
Recently updated (since 2017-07-27)
Today:
→ request@2.81.0 › http-signature@1.1.1 › jsprim@^1.2.2(1.4.1) (00:29:57)
Recently updated (since 2017-07-31)
2017-08-03
→ @3846masa/axios-cookiejar-support@*(0.1.1) (21:49:58)
../_@3846masa_axios-cookiejar-support@0.1.1@@3846masa/axios-cookiejar-support
\ No newline at end of file
../_@types_tough-cookie@2.3.1@@types/tough-cookie
\ No newline at end of file
env:
es6: true
node: true
mocha: true
extends: standard
plugins:
- standard
- promise
rules:
semi:
- error
- always
# Created by https://www.gitignore.io/api/node
### Node ###
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules
jspm_packages
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
The MIT License (MIT)
Copyright © 2016 3846masa
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.
# axios-cookiejar-support
Add [``tough-cookie``] support to [``axios``].
[``axios``]: https://github.com/mzabriskie/axios
[``tough-cookie``]: https://github.com/SalesforceEng/tough-cookie
------
[![NPM][npm-badge]][npm]
[![LICENSE][license-badge]][license]
[![CircleCI][circleci-badge]][circleci]
[![dependencies][dependencies-badge]][dependencies-david]
[![peerdependencies][peerdependencies-badge]][peerdependencies-david]
[![devdependencies][devdependencies-badge]][devdependencies-david]
[npm]: https://www.npmjs.com/package/@3846masa/axios-cookiejar-support
[license]: https://3846masa.mit-license.org
[circleci]: https://circleci.com/gh/3846masa/axios-cookiejar-support
[dependencies-david]: https://david-dm.org/3846masa/axios-cookiejar-support?view=list
[peerdependencies-david]: https://david-dm.org/3846masa/axios-cookiejar-support?type=peer&view=list
[devdependencies-david]: https://david-dm.org/3846masa/axios-cookiejar-support?type=dev&view=list
[npm-badge]: https://img.shields.io/npm/v/@3846masa/axios-cookiejar-support.svg?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAbUExURcwAAOeIiP////G7u/ri4tIZGdpFReJsbPC3t075sZwAAAAvSURBVCjPY2CgDWAThIMEsACjEhwIUCZg0dGCIqASwMAxMgXAgSzOwMAOC2TqAwBvzR4JxLaP0gAAAABJRU5ErkJggg==
[license-badge]: https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAIGNIUk0AAHomAACAhAAA%2BgAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAAVUExURSBTICJcIiNgIiZoJTuhNyt3Kf///%2BCqxSgAAAAGdFJOUwpclbn%2B4Fj6/H8AAAABYktHRAZhZrh9AAAACXBIWXMAAA3XAAAN1wFCKJt4AAAAB3RJTUUH4AkEEjEV7MDQQwAAAGBJREFUCNc1TUEKgDAMi07vE/Q%2BRD8g%2B4BbvAvi/79iMjDQJm1CC6BbDzRsZI3incIpYeYFhCaYnLiyPYnYkwWZFWoFHrSuttCmmbwXh0eJQYVON4JthZTxCzzAmyb8%2BAAKXBRyN6RyZQAAAABJRU5ErkJggg==
[circleci-badge]: https://img.shields.io/circleci/project/3846masa/axios-cookiejar-support/master.svg?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQEAYAAABPYyMiAAAAIGNIUk0AAHomAACAhAAA%2BgAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAAGYktHRP///////wlY99wAAAAHdElNRQfgCQQSJS8EYt6kAAAAiklEQVRIx2M41nqs9Xi9WDQh%2BjQQnDnz%2BS5x9KS9xJrLgN/CSXtJs5h0BzHQ1mLCDmEgL4jJpyl0AOG4JTYE4Q6gdqIi1UMM2F1OrE9xBy2xDmGgrs8wHU5nB2CGBNEOQPcBoaigThQA08AgS4QDkA3pXRChe4SBskqHiiUhreoEsmtDyhxEfKIFAG4yoGuqR9fTAAAAAElFTkSuQmCC
[dependencies-badge]: https://img.shields.io/david/3846masa/axios-cookiejar-support.svg?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAbUExURcwAAOeIiP////G7u/ri4tIZGdpFReJsbPC3t075sZwAAAAvSURBVCjPY2CgDWAThIMEsACjEhwIUCZg0dGCIqASwMAxMgXAgSzOwMAOC2TqAwBvzR4JxLaP0gAAAABJRU5ErkJggg==
[peerdependencies-badge]: https://img.shields.io/david/peer/3846masa/axios-cookiejar-support.svg?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAbUExURcwAAOeIiP////G7u/ri4tIZGdpFReJsbPC3t075sZwAAAAvSURBVCjPY2CgDWAThIMEsACjEhwIUCZg0dGCIqASwMAxMgXAgSzOwMAOC2TqAwBvzR4JxLaP0gAAAABJRU5ErkJggg==
[devdependencies-badge]: https://img.shields.io/david/dev/3846masa/axios-cookiejar-support.svg?style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAbUExURcwAAOeIiP////G7u/ri4tIZGdpFReJsbPC3t075sZwAAAAvSURBVCjPY2CgDWAThIMEsACjEhwIUCZg0dGCIqASwMAxMgXAgSzOwMAOC2TqAwBvzR4JxLaP0gAAAABJRU5ErkJggg==
## Install
```sh
$ npm i axios @3846masa/axios-cookiejar-support
```
## Usage
```js
const axios = require('axios');
const axiosCookieJarSupport = require('@3846masa/axios-cookiejar-support');
const tough = require('tough-cookie');
axiosCookieJarSupport(axios);
const cookieJar = new tough.CookieJar();
axios.get('https://google.com', {
jar: cookieJar, // tough.CookieJar or boolean
withCredentials: true // If true, send cookie stored in jar
})
.then(() => {
console.log(cookieJar);
});
```
See [examples](./example).
### Extended Request Config
c.f.) https://github.com/mzabriskie/axios#request-config
```js
{
// `jar` is tough.CookieJar instance or boolean.
// If true, axios create CookieJar automatically.
jar: undefined, // default
// **IMPORTANT**
// If false, axios DONOT send cookies from cookiejar.
withCredentials: false // default
}
```
### Browser
Running on browser, this library becomes noop (``config.jar`` might be ignored).
## Contribution
1. [Fork it]
2. Create your feature branch (``git checkout -b my-new-feature``)
3. Commit your changes (``git commit -am 'Add some feature'``)
4. Push to the branch (``git push origin my-new-feature``)
5. Create new Pull Request
[Fork it]: http://github.com/3846masa/axios-cookiejar-support/fork
## LICENSE
[MIT License](https://3846masa.mit-license.org)
## Author
![3846masa icon][3846masa-icon]
[3846masa](https://github.com/3846masa)
[3846masa-icon]: https://www.gravatar.com/avatar/cfeae69aae4f4fc102960f01d35d2d86?s=50
machine:
node:
version: 4
post:
- npm install -g npm@3
timezone: Asia/Tokyo
dependencies:
override:
- npm config set progress false
- npm config set spin false
- npm install -d
test:
override:
- npm test
deployment:
production:
tag: /v\d+(\.\d+)*/
commands:
- echo -e "$NPM_USER\n$NPM_PASS\n$NPM_EMAIL" | npm login
- npm publish --access=public
'use strict';
const axios = require('axios');
const tough = require('tough-cookie');
const axiosCookieJarSupport = require('../');
axiosCookieJarSupport(axios);
const cookieJar = new tough.CookieJar();
cookieJar.setCookieSync('key=value; domain=mockbin.org', 'https://mockbin.org');
axios.get('https://mockbin.org/request', {
jar: cookieJar,
withCredentials: true // IMPORTANT!
})
.then((response) => {
const data = response.data;
console.log(data.headers.cookie);
})
.catch((err) => {
console.error(err.stack || err);
});
'use strict';
const axios = require('axios');
const tough = require('tough-cookie');
const axiosCookieJarSupport = require('../');
axiosCookieJarSupport(axios);
const cookieJar = new tough.CookieJar();
axios.defaults.jar = cookieJar;
axios.defaults.withCredentials = true;
axios.get('https://google.com')
.then((response) => {
const config = response.config;
// axios.defaults.jar === config.jar
console.log(config.jar.toJSON());
})
.catch((err) => {
console.error(err.stack || err);
});
'use strict';
const axios = require('axios');
const tough = require('tough-cookie');
const axiosCookieJarSupport = require('../');
axiosCookieJarSupport(axios);
const cookieJar = new tough.CookieJar();
axios.get('https://google.com', {
jar: cookieJar,
withCredentials: true
})
.then((response) => {
const config = response.config;
console.log(config.jar.toJSON());
})
.catch((err) => {
console.error(err.stack || err);
});
import { AxiosInstance } from 'axios';
import { CookieJar } from 'tough-cookie';
declare module 'axios' {
export interface AxiosRequestConfig {
jar?: CookieJar;
}
}
declare var axiosCookieJarSupport: (instance: AxiosInstance) => AxiosInstance;
export = axiosCookieJarSupport;
'use strict';
const tough = require('tough-cookie');
const utils = require('axios/lib/utils');
const requestInterceptorWrapper = require('./lib/request-interceptor-wrapper');
const responseInterceptorWrapper = require('./lib/response-interceptor-wrapper');
function axiosCookieJarSupport (instance) {
if (instance.create) {
const createInstance = instance.create.bind(instance);
instance.create = function create (defaultConfig) {
const newInstance = createInstance(defaultConfig);
return axiosCookieJarSupport(newInstance);
};
}
const origRequest = instance.request.bind(instance);
instance.request = function request (config) {
config._COOKIEJAR_SUPPORT_LOCAL =
config._COOKIEJAR_SUPPORT_LOCAL || {};
const local = config._COOKIEJAR_SUPPORT_LOCAL;
if (instance.defaults.jar === true) {
instance.defaults.jar = new tough.CookieJar();
}
if (!local.jar) {
if (config.jar === true) {
local.jar = (instance.defaults.jar || new tough.CookieJar());
} else if (config.jar === false) {
local.jar = false;
} else {
local.jar = (config.jar || instance.defaults.jar);
}
}
return origRequest(config);
};
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData (method) {
instance[method] = function (url, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData (method) {
instance[method] = function (url, data, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url,
data: data
}));
};
});
requestInterceptorWrapper(instance);
responseInterceptorWrapper(instance);
return instance;
}
module.exports = axiosCookieJarSupport;
'use strict';
const pify = require('pify');
function requestInterceptorResolve (config) {
return Promise.resolve(config)
.then(function backupOriginalConfigs (config) {
const local = config._COOKIEJAR_SUPPORT_LOCAL;
local.backupOptions = local.backupOptions || {};
return config;
})
.then(function redirectSetup (config) {
const local = config._COOKIEJAR_SUPPORT_LOCAL;
local.redirectCount =
isFinite(config.maxRedirects) ? config.maxRedirects : 5;
local.backupOptions.maxRedirects =
local.backupOptions.maxRedirects || config.maxRedirects;
local.backupOptions.validateStatus =
local.backupOptions.validateStatus || config.validateStatus;
config.maxRedirects = 0;
config.validateStatus = undefined;
return config;
})
.then(function cookieSetup (config) {
const local = config._COOKIEJAR_SUPPORT_LOCAL;
if (local.jar && config.withCredentials) {
const getCookieString =
pify(local.jar.getCookieString.bind(local.jar));
return getCookieString(config.url)
.then(function (cookieString) {
if (!cookieString) {
return;
}
config.headers['Cookie'] =
(config.headers['Cookie'])
? cookieString + '; ' + config.headers['Cookie']
: cookieString;
}).then(function () { return config; });
}
return config;
});
};
function requestInterceptorReject (error) {
return Promise.reject(error);
};
function requestInterceptorWrapper (instance) {
instance.interceptors.request.use(
requestInterceptorResolve,
requestInterceptorReject
);
return instance;
}
module.exports = requestInterceptorWrapper;
'use strict';
const url = require('url');
const settle = require('axios/lib/core/settle');
const pify = require('pify');
function responseInterceptorResolve (response, instance) {
return Promise.resolve(response)
.then(function setCookies (response) {
const config = response.config;
const local = config._COOKIEJAR_SUPPORT_LOCAL;
if (!local.jar || !response.headers['set-cookie']) {
return response;
}
const setCookie = pify(local.jar.setCookie.bind(local.jar));
const setCookiePromiseList = [];
if (Array.isArray(response.headers['set-cookie'])) {
const cookies = response.headers['set-cookie'];
cookies.forEach(function (cookie) {
setCookiePromiseList.push(setCookie(cookie, config.url));
});
} else {
const cookie = response.headers['set-cookie'];
setCookiePromiseList.push(setCookie(cookie, config.url));
}
return Promise.all(setCookiePromiseList)
.then(function () { return response; });
})
.then(function redirectSetup (response) {
const config = response.config;
const local = config._COOKIEJAR_SUPPORT_LOCAL;
local.backupOptions.baseURL =
local.backupOptions.baseURL || config.baseURL;
local.backupOptions.url =
local.backupOptions.url || config.url;
local.backupOptions.method =
local.backupOptions.method || config.method;
config.baseURL = undefined;
config.url = config.url = url.resolve(response.config.url, response.headers['location'] || '');
local.redirectCount--;
return response;
})
.then(function redirect (response) {
const config = response.config;
const local = config._COOKIEJAR_SUPPORT_LOCAL;
if (local.redirectCount < 0 || !response.headers['location']) {
return response;
}
if (response.status !== 307) {
config.method = 'get';
}
config.maxRedirects = local.redirectCount;
return instance.request(config);
})
.then(function restoreCookieJar (response) {
const config = response.config;
const local = config._COOKIEJAR_SUPPORT_LOCAL;
if (!local || !local.jar) return response;
if (instance.defaults.jar && (!config.jar || config.jar === true)) {
instance.defaults.jar = local.jar;
}
config.jar = local.jar;
return response;
})
.then(function restoreConfigs (response) {
const config = response.config;
const local = config._COOKIEJAR_SUPPORT_LOCAL;
if (!local) return response;
for (let key in local.backupOptions) {
config[key] = local.backupOptions[key];
}
return response;
})
.then(function deleteLocals (response) {
delete response.config._COOKIEJAR_SUPPORT_LOCAL;
return response;
})
.then(function validate (response) {
return new Promise(function (resolve, reject) {
settle(resolve, reject, response);
});
});
}
function responseInterceptorReject (error) {
return Promise.reject(error);
}
function responseInterceptorWrapper (instance) {
instance.interceptors.response.use(
function (response) {
return responseInterceptorResolve(response, instance);
},
responseInterceptorReject
);
return instance;
}
module.exports = responseInterceptorWrapper;
../../../../_@types_tough-cookie@2.3.1@@types/tough-cookie
\ No newline at end of file
'use strict';
function noopEnableCookieJarSupport (instance) {
return instance;
}
module.exports = noopEnableCookieJarSupport;
{
"name": "@3846masa/axios-cookiejar-support",
"description": "Add tough-cookie support to axios.",
"version": "0.1.1",
"author": "3846masa",
"browser": {
"./index.js": "./noop.js"
},
"bugs": {
"url": "https://github.com/3846masa/axios-cookiejar-support/issues"
},
"dependencies": {
"@types/tough-cookie": "^2.3.1",
"pify": "3.0.0",
"tough-cookie": "2.3.2"
},
"devDependencies": {
"axios": "0.16.1",
"cookie": "0.3.1",
"decache": "4.1.0",
"eslint": "4.1.0",
"eslint-config-standard": "10.2.1",
"eslint-plugin-promise": "3.5.0",
"eslint-plugin-standard": "3.0.1",
"intelli-espower-loader": "1.0.1",
"mocha": "3.3.0",
"nock": "9.0.13",
"power-assert": "1.4.3"
},
"directories": {
"example": "example",
"test": "test"
},
"homepage": "https://github.com/3846masa/axios-cookiejar-support#readme",
"keywords": [
"axios",
"cookie",
"cookiejar",
"cookies",
"tough-cookie"
],
"license": "MIT",
"main": "./index.js",
"types": "./index.d.ts",
"peerDependencies": {
"axios": "^0.16.2"
},
"repository": {
"type": "git",
"url": "git+https://github.com/3846masa/axios-cookiejar-support.git"
},
"scripts": {
"postversion": "git commit --amend --allow-empty -m \"[skip ci] `git log -1 --pretty=%s`\"",
"test": "mocha --require intelli-espower-loader"
},
"_from": "@3846masa/axios-cookiejar-support@0.1.1",
"_resolved": "http://registry.npm.taobao.org/@3846masa/axios-cookiejar-support/download/@3846masa/axios-cookiejar-support-0.1.1.tgz"
}
\ No newline at end of file
Mon Aug 07 2017 19:51:45 GMT+0800 (CST)
\ No newline at end of file
MIT License
Copyright (c) Microsoft Corporation. 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
# Installation
> `npm install --save @types/tough-cookie`
# Summary
This package contains type definitions for tough-cookie (https://github.com/salesforce/tough-cookie).
# Details
Files were exported from https://www.github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/tough-cookie
Additional Details
* Last updated: Fri, 14 Jul 2017 14:18:49 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by Leonard Thieu <https://github.com/leonard-thieu>.
// Type definitions for tough-cookie 2.3
// Project: https://github.com/salesforce/tough-cookie
// Definitions by: Leonard Thieu <https://github.com/leonard-thieu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/**
* Parse a cookie date string into a Date.
* Parses according to RFC6265 Section 5.1.1, not Date.parse().
*/
export function parseDate(string: string): Date;
/**
* Format a Date into a RFC1123 string (the RFC6265-recommended format).
*/
export function formatDate(date: Date): string;
/**
* Transforms a domain-name into a canonical domain-name.
* The canonical domain-name is a trimmed, lowercased, stripped-of-leading-dot
* and optionally punycode-encoded domain-name (Section 5.1.2 of RFC6265).
* For the most part, this function is idempotent (can be run again on its output without ill effects).
*/
export function canonicalDomain(str: string): string;
/**
* Answers "does this real domain match the domain in a cookie?".
* The str is the "current" domain-name and the domStr is the "cookie" domain-name.
* Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match".
*
* The canonicalize parameter will run the other two paramters through canonicalDomain or not.
*/
export function domainMatch(str: string, domStr: string, canonicalize?: boolean): boolean;
/**
* Given a current request/response path, gives the Path apropriate for storing in a cookie.
* This is basically the "directory" of a "file" in the path, but is specified by Section 5.1.4 of the RFC.
*
* The path parameter MUST be only the pathname part of a URI (i.e. excludes the hostname, query, fragment, etc.).
* This is the .pathname property of node's uri.parse() output.
*/
export function defaultPath(path: string): string;
/**
* Answers "does the request-path path-match a given cookie-path?" as per RFC6265 Section 5.1.4.
* Returns a boolean.
*
* This is essentially a prefix-match where cookiePath is a prefix of reqPath.
*/
export function pathMatch(reqPath: string, cookiePath: string): boolean;
/**
* alias for Cookie.fromJSON(string)
*/
export function fromJSON(string: string): Cookie;
export function getPublicSuffix(hostname: string): string | null;
export function cookieCompare(a: Cookie, b: Cookie): number;
export function permuteDomain(domain: string): string[];
export function permutePath(path: string): string[];
// region Cookie
export class Cookie {
static parse(cookieString: string, options?: Cookie.ParseOptions): Cookie | undefined;
static fromJSON(strOrObj: string | object): Cookie | null;
constructor(properties?: Cookie.Properties);
// TODO: Some of the following properties might actually be nullable.
key: string;
value: string;
expires: Date;
maxAge: number | 'Infinity' | '-Infinity';
domain: string;
path: string;
secure: boolean;
httpOnly: boolean;
extensions: string[];
creation: Date;
creationIndex: number;
hostOnly: boolean | null;
pathIsDefault: boolean | null;
lastAccessed: Date | null;
toString(): string;
cookieString(): string;
setExpires(String: string): void;
setMaxAge(number: number): void;
expiryTime(now?: number): number | typeof Infinity;
expiryDate(now?: number): Date;
TTL(now?: Date): number | typeof Infinity;
canonicalizedDomain(): string;
cdomain(): string;
toJSON(): { [key: string]: any; };
clone(): Cookie;
validate(): boolean | string;
}
export namespace Cookie {
interface ParseOptions {
loose?: boolean;
}
interface Properties {
key?: string;
value?: string;
expires?: Date;
maxAge?: number | 'Infinity' | '-Infinity';
domain?: string;
path?: string;
secure?: boolean;
httpOnly?: boolean;
extensions?: string[];
creation?: Date;
creationIndex?: number;
hostOnly?: boolean;
pathIsDefault?: boolean;
lastAccessed?: Date;
}
interface Serialized {
[key: string]: any;
}
}
// endregion
// region CookieJar
export class CookieJar {
static deserialize(serialized: CookieJar.Serialized | string, store: Store, cb: (err: Error | null, object: CookieJar) => void): void;
static deserialize(serialized: CookieJar.Serialized | string, cb: (err: Error | null, object: CookieJar) => void): void;
static deserializeSync(serialized: CookieJar.Serialized | string): CookieJar;
static fromJSON(string: string): CookieJar;
constructor(store?: Store, options?: CookieJar.Options);
setCookie(cookieOrString: Cookie | string, currentUrl: string, options: CookieJar.SetCookieOptions, cb: (err: Error | null, cookie: Cookie) => void): void;
setCookie(cookieOrString: Cookie | string, currentUrl: string, cb: (err: Error, cookie: Cookie) => void): void;
setCookieSync(cookieOrString: Cookie | string, currentUrl: string, options: CookieJar.SetCookieOptions): void;
getCookies(currentUrl: string, options: CookieJar.GetCookiesOptions, cb: (err: Error | null, cookies: Cookie[]) => void): void;
getCookies(currentUrl: string, cb: (err: Error | null, cookies: Cookie[]) => void): void;
getCookiesSync(currentUrl: string, options?: CookieJar.GetCookiesOptions): Cookie[];
getCookieString(currentUrl: string, options: CookieJar.GetCookiesOptions, cb: (err: Error | null, cookies: string) => void): void;
getCookieString(currentUrl: string, cb: (err: Error | null, cookies: string) => void): void;
getCookieStringSync(currentUrl: string, options?: CookieJar.GetCookiesOptions): string;
getSetCookieStrings(currentUrl: string, options: CookieJar.GetCookiesOptions, cb: (err: Error | null, cookies: string) => void): void;
getSetCookieStrings(currentUrl: string, cb: (err: Error | null, cookies: string) => void): void;
getSetCookieStringsSync(currentUrl: string, options?: CookieJar.GetCookiesOptions): string;
serialize(cb: (err: Error | null, serializedObject: CookieJar.Serialized) => void): void;
serializeSync(): CookieJar.Serialized;
toJSON(): CookieJar.Serialized;
clone(store: Store, cb: (err: Error | null, newJar: CookieJar) => void): void;
clone(cb: (err: Error | null, newJar: CookieJar) => void): void;
cloneSync(store: Store): CookieJar;
}
export namespace CookieJar {
interface Options {
rejectPublicSuffixes?: boolean;
looseMode?: boolean;
}
interface SetCookieOptions {
http?: boolean;
secure?: boolean;
now?: Date;
ignoreError?: boolean;
}
interface GetCookiesOptions {
http?: boolean;
secure?: boolean;
date?: Date;
expire?: boolean;
allPoints?: boolean;
}
interface Serialized {
version: string;
storeType: string;
rejectPublicSuffixes: boolean;
cookies: Cookie.Serialized[];
}
}
// endregion
// region Store
export abstract class Store {
findCookie(domain: string, path: string, key: string, cb: (err: Error | null, cookie: Cookie | null) => void): void;
findCookies(domain: string, path: string, cb: (err: Error | null, cookie: Cookie[]) => void): void;
putCookie(cookie: Cookie, cb: (err: Error | null) => void): void;
updateCookie(oldCookie: Cookie, newCookie: Cookie, cb: (err: Error | null) => void): void;
removeCookie(domain: string, path: string, key: string, cb: (err: Error | null) => void): void;
removeCookies(domain: string, path: string, cb: (err: Error | null) => void): void;
getAllCookies(cb: (err: Error | null, cookie: Cookie[]) => void): void;
}
export class MemoryCookieStore extends Store { }
// endregion
{
"name": "@types/tough-cookie",
"version": "2.3.1",
"description": "TypeScript definitions for tough-cookie",
"license": "MIT",
"contributors": [
{
"name": "Leonard Thieu",
"url": "https://github.com/leonard-thieu"
}
],
"main": "",
"repository": {
"type": "git",
"url": "https://www.github.com/DefinitelyTyped/DefinitelyTyped.git"
},
"scripts": {},
"dependencies": {},
"peerDependencies": {},
"typesPublisherContentHash": "2a7d2b6b4c215d564939a5afc228cec98bc527bb3743f878b8e5fd6758e332bc",
"typeScriptVersion": "2.2",
"_from": "@types/tough-cookie@2.3.1",
"_resolved": "http://registry.npm.taobao.org/@types/tough-cookie/download/@types/tough-cookie-2.3.1.tgz"
}
\ No newline at end of file
File mode changed from 100644 to 100755
Mon Aug 07 2017 19:51:45 GMT+0800 (CST)
\ No newline at end of file
'use strict';
const processFn = (fn, opts) => function () {
const P = opts.promiseModule;
const args = new Array(arguments.length);
for (let i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
return new P((resolve, reject) => {
if (opts.errorFirst) {
args.push(function (err, result) {
if (opts.multiArgs) {
const results = new Array(arguments.length - 1);
for (let i = 1; i < arguments.length; i++) {
results[i - 1] = arguments[i];
}
if (err) {
results.unshift(err);
reject(results);
} else {
resolve(results);
}
} else if (err) {
reject(err);
} else {
resolve(result);
}
});
} else {
args.push(function (result) {
if (opts.multiArgs) {
const results = new Array(arguments.length - 1);
for (let i = 0; i < arguments.length; i++) {
results[i] = arguments[i];
}
resolve(results);
} else {
resolve(result);
}
});
}
fn.apply(this, args);
});
};
module.exports = (obj, opts) => {
opts = Object.assign({
exclude: [/.+(Sync|Stream)$/],
errorFirst: true,
promiseModule: Promise
}, opts);
const filter = key => {
const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key);
return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
};
let ret;
if (typeof obj === 'function') {
ret = function () {
if (opts.excludeMain) {
return obj.apply(this, arguments);
}
return processFn(obj, opts).apply(this, arguments);
};
} else {
ret = Object.create(Object.getPrototypeOf(obj));
}
for (const key in obj) { // eslint-disable-line guard-for-in
const x = obj[key];
ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x;
}
return ret;
};
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.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.
{
"name": "pify",
"version": "3.0.0",
"description": "Promisify a callback-style function",
"license": "MIT",
"repository": "sindresorhus/pify",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava && npm run optimization-test",
"optimization-test": "node --allow-natives-syntax optimization-test.js"
},
"files": [
"index.js"
],
"keywords": [
"promise",
"promises",
"promisify",
"all",
"denodify",
"denodeify",
"callback",
"cb",
"node",
"then",
"thenify",
"convert",
"transform",
"wrap",
"wrapper",
"bind",
"to",
"async",
"await",
"es2015",
"bluebird"
],
"devDependencies": {
"ava": "*",
"pinkie-promise": "^2.0.0",
"v8-natives": "^1.0.0",
"xo": "*"
},
"_from": "pify@3.0.0",
"_resolved": "http://registry.npm.taobao.org/pify/download/pify-3.0.0.tgz"
}
\ No newline at end of file
# pify [![Build Status](https://travis-ci.org/sindresorhus/pify.svg?branch=master)](https://travis-ci.org/sindresorhus/pify)
> Promisify a callback-style function
## Install
```
$ npm install --save pify
```
## Usage
```js
const fs = require('fs');
const pify = require('pify');
// Promisify a single function
pify(fs.readFile)('package.json', 'utf8').then(data => {
console.log(JSON.parse(data).name);
//=> 'pify'
});
// Promisify all methods in a module
pify(fs).readFile('package.json', 'utf8').then(data => {
console.log(JSON.parse(data).name);
//=> 'pify'
});
```
## API
### pify(input, [options])
Returns a `Promise` wrapped version of the supplied function or module.
#### input
Type: `Function` `Object`
Callback-style function or module whose methods you want to promisify.
#### options
##### multiArgs
Type: `boolean`<br>
Default: `false`
By default, the promisified function will only return the second argument from the callback, which works fine for most APIs. This option can be useful for modules like `request` that return multiple arguments. Turning this on will make it return an array of all arguments from the callback, excluding the error argument, instead of just the second argument. This also applies to rejections, where it returns an array of all the callback arguments, including the error.
```js
const request = require('request');
const pify = require('pify');
pify(request, {multiArgs: true})('https://sindresorhus.com').then(result => {
const [httpResponse, body] = result;
});
```
##### include
Type: `string[]` `RegExp[]`
Methods in a module to promisify. Remaining methods will be left untouched.
##### exclude
Type: `string[]` `RegExp[]`<br>
Default: `[/.+(Sync|Stream)$/]`
Methods in a module **not** to promisify. Methods with names ending with `'Sync'` are excluded by default.
##### excludeMain
Type: `boolean`<br>
Default: `false`
If given module is a function itself, it will be promisified. Turn this option on if you want to promisify only methods of the module.
```js
const pify = require('pify');
function fn() {
return true;
}
fn.method = (data, callback) => {
setImmediate(() => {
callback(null, data);
});
};
// Promisify methods but not `fn()`
const promiseFn = pify(fn, {excludeMain: true});
if (promiseFn()) {
promiseFn.method('hi').then(data => {
console.log(data);
});
}
```
##### errorFirst
Type: `boolean`<br>
Default: `true`
Whether the callback has an error as the first argument. You'll want to set this to `false` if you're dealing with an API that doesn't have an error as the first argument, like `fs.exists()`, some browser APIs, Chrome Extension APIs, etc.
##### promiseModule
Type: `Function`
Custom promise module to use instead of the native one.
Check out [`pinkie-promise`](https://github.com/floatdrop/pinkie-promise) if you need a tiny promise polyfill.
## Related
- [p-event](https://github.com/sindresorhus/p-event) - Promisify an event by waiting for it to be emitted
- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently
- [More…](https://github.com/sindresorhus/promise-fun)
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
/.idea/
/coverage/
/test/
/.editorconfig
/.eslintrc.json
/.gitignore
/.publishrc
/.travis.yml
/gulpfile.js
.DS_Store
npm-debug.log
\ No newline at end of file
Mon Aug 07 2017 15:31:49 GMT+0800 (CST)
\ No newline at end of file
ISC License
Copyright (c) 2016, Nicolai Kamenzky and contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
\ No newline at end of file
<a href="http://promisesaplus.com/">
<img src="https://promises-aplus.github.io/promises-spec/assets/logo-small.png" align="right" alt="Promises/A+ logo" />
</a>
# request-promise-core
[![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square&maxAge=2592000)](https://gitter.im/request/request-promise?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://img.shields.io/travis/request/promise-core/master.svg?style=flat-square&maxAge=2592000)](https://travis-ci.org/request/promise-core)
[![Coverage Status](https://img.shields.io/coveralls/request/promise-core.svg?style=flat-square&maxAge=2592000)](https://coveralls.io/r/request/promise-core)
[![Dependency Status](https://img.shields.io/david/request/promise-core.svg?style=flat-square&maxAge=2592000)](https://david-dm.org/request/promise-core)
[![Known Vulnerabilities](https://snyk.io/test/npm/promise-core/badge.svg?style=flat-square&maxAge=2592000)](https://snyk.io/test/npm/promise-core)
This package is the core for the following packages:
- [`request-promise`](https://github.com/request/request-promise)
- [`request-promise-any`](https://github.com/request/request-promise-any)
- [`request-promise-bluebird`](https://github.com/request/request-promise-bluebird)
- [`request-promise-native`](https://github.com/request/request-promise-native)
`request-promise-core` contains the core logic to add Promise support to [`request`](https://github.com/request/request).
Please use one of the libraries above. It is only recommended to use this library directly, if you have very specific requirements.
## Installation for `request@^2.34`
This module is installed via npm:
```
npm install --save request
npm install --save request-promise-core
```
`request` is defined as a peer-dependency and thus has to be installed separately.
## Usage for `request@^2.34`
``` js
// 1. Load the request library
// Only use a direct require if you are 100% sure that:
// - Your project does not use request directly. That is without the Promise capabilities by calling require('request').
// - Any of the installed libraries use request.
// ...because Request's prototype will be patched in step 2.
/* var request = require('request'); */
// Instead use:
var stealthyRequire = require('stealthy-require');
var request = stealthyRequire(require.cache, function () {
return require('request');
});
// 2. Add Promise support to request
var configure = require('request-promise-core/configure/request2');
configure({
request: request,
// Pass your favorite ES6-compatible promise implementation
PromiseImpl: Promise,
// Expose all methods of the promise instance you want to call on the request(...) call
expose: [
'then', // Allows to use request(...).then(...)
'catch', // Allows to use request(...).catch(...)
'promise' // Allows to use request(...).promise() which returns the promise instance
],
// Optional: Pass a callback that is called within the Promise constructor
constructorMixin: function (resolve, reject) {
// `this` is the request object
// Additional arguments may be passed depending on the PromiseImpl used
}
});
// 3. Use request with its promise capabilities
// E.g. crawl a web page:
request('http://www.google.com')
.then(function (htmlString) {
// Process html...
})
.catch(function (err) {
// Crawling failed...
});
```
## Installation and Usage for `request@next`
[Request Next](https://github.com/request/request/issues/1982) is still in alpha. However, `request-promise-core` is already designed to be compatible and ships with a configuration helper – `require('request-promise-core/configure/request-next')` – that is [used by `request-promise`](https://github.com/request/request-promise/blob/next/lib/rp.js) in its "next" branch.
## Contributing
To set up your development environment:
1. clone the repo to your desktop,
2. in the shell `cd` to the main folder,
3. hit `npm install`,
4. hit `npm install gulp -g` if you haven't installed gulp globally yet, and
5. run `gulp dev`. (Or run `node ./node_modules/.bin/gulp dev` if you don't want to install gulp globally.)
`gulp dev` watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from `./coverage/lcov-report/index.html`.
If you want to debug a test you should use `gulp test-without-coverage` to run all tests without obscuring the code by the test coverage instrumentation.
## Change History
- 1.1.1 (2016-08-08)
- Renamed package to `request-promise-core` because there where [too many issues](https://github.com/request/request-promise/issues/137) with the scoped package name `@request/promise-core`
- 1.1.0 (2016-07-30)
- Added `constructorMixin` option to enable [request/request-promise#123](https://github.com/request/request-promise/pull/123)
- 1.0.0 (2016-07-15)
- All tests green, ready for prime time
- 1.0.0-rc.1 (2016-07-10)
- Reimplementation of core logic based on `request-promise@3.0.0`
- Plus `transform2xxOnly` option (fixes [request/request-promise#131](https://github.com/request/request-promise/issues/131))
## License (ISC)
In case you never heard about the [ISC license](http://en.wikipedia.org/wiki/ISC_license) it is functionally equivalent to the MIT license.
See the [LICENSE file](LICENSE) for details.
\ No newline at end of file
'use strict';
var core = require('../'),
isArray = require('lodash/isArray'),
isFunction = require('lodash/isFunction'),
isObjectLike = require('lodash/isObjectLike');
module.exports = function (options) {
var errorText = 'Please verify options'; // For better minification because this string is repeating
if (!isObjectLike(options)) {
throw new TypeError(errorText);
}
if (!isFunction(options.client)) {
throw new TypeError(errorText + '.client');
}
if (!isArray(options.expose) || options.expose.length === 0) {
throw new TypeError(errorText + '.expose');
}
var thenExposed = false;
for ( var i = 0; i < options.expose.length; i+=1 ) {
if (options.expose[i] === 'then') {
thenExposed = true;
break;
}
}
if (!thenExposed) {
throw new Error('Please expose "then"');
}
var plumbing = core({
PromiseImpl: options.PromiseImpl,
constructorMixin: options.constructorMixin
});
return function (requestOptions) {
var self = {};
plumbing.init.call(self, requestOptions);
var request = options.client(requestOptions);
for ( var k = 0; k < options.expose.length; k+=1 ) {
var method = options.expose[k];
plumbing[ method === 'promise' ? 'exposePromise' : 'exposePromiseMethod' ](
request,
self,
'_rp_promise',
method
);
}
return request;
};
};
'use strict';
var core = require('../'),
isArray = require('lodash/isArray'),
isFunction = require('lodash/isFunction'),
isObjectLike = require('lodash/isObjectLike');
module.exports = function (options) {
var errorText = 'Please verify options'; // For better minification because this string is repeating
if (!isObjectLike(options)) {
throw new TypeError(errorText);
}
if (!isFunction(options.request)) {
throw new TypeError(errorText + '.request');
}
if (!isArray(options.expose) || options.expose.length === 0) {
throw new TypeError(errorText + '.expose');
}
var plumbing = core({
PromiseImpl: options.PromiseImpl,
constructorMixin: options.constructorMixin
});
// Intercepting Request's init method
var originalInit = options.request.Request.prototype.init;
options.request.Request.prototype.init = function RP$initInterceptor(requestOptions) {
// Init may be called again - currently in case of redirects
if (isObjectLike(requestOptions) && !this._callback && !this._rp_promise) {
plumbing.init.call(this, requestOptions);
}
return originalInit.apply(this, arguments);
};
// Exposing the Promise capabilities
var thenExposed = false;
for ( var i = 0; i < options.expose.length; i+=1 ) {
var method = options.expose[i];
plumbing[ method === 'promise' ? 'exposePromise' : 'exposePromiseMethod' ](
options.request.Request.prototype,
null,
'_rp_promise',
method
);
if (method === 'then') {
thenExposed = true;
}
}
if (!thenExposed) {
throw new Error('Please expose "then"');
}
};
'use strict';
module.exports = require('./lib/errors.js');
'use strict';
function RequestError(cause, options, response) {
this.name = 'RequestError';
this.message = String(cause);
this.cause = cause;
this.error = cause; // legacy attribute
this.options = options;
this.response = response;
if (Error.captureStackTrace) { // required for non-V8 environments
Error.captureStackTrace(this);
}
}
RequestError.prototype = Object.create(Error.prototype);
RequestError.prototype.constructor = RequestError;
function StatusCodeError(statusCode, body, options, response) {
this.name = 'StatusCodeError';
this.statusCode = statusCode;
this.message = statusCode + ' - ' + (JSON && JSON.stringify ? JSON.stringify(body) : body);
this.error = body; // legacy attribute
this.options = options;
this.response = response;
if (Error.captureStackTrace) { // required for non-V8 environments
Error.captureStackTrace(this);
}
}
StatusCodeError.prototype = Object.create(Error.prototype);
StatusCodeError.prototype.constructor = StatusCodeError;
function TransformError(cause, options, response) {
this.name = 'TransformError';
this.message = String(cause);
this.cause = cause;
this.error = cause; // legacy attribute
this.options = options;
this.response = response;
if (Error.captureStackTrace) { // required for non-V8 environments
Error.captureStackTrace(this);
}
}
TransformError.prototype = Object.create(Error.prototype);
TransformError.prototype.constructor = TransformError;
module.exports = {
RequestError: RequestError,
StatusCodeError: StatusCodeError,
TransformError: TransformError
};
'use strict';
var errors = require('./errors.js'),
isFunction = require('lodash/isFunction'),
isObjectLike = require('lodash/isObjectLike'),
isString = require('lodash/isString'),
isUndefined = require('lodash/isUndefined');
module.exports = function (options) {
var errorText = 'Please verify options'; // For better minification because this string is repeating
if (!isObjectLike(options)) {
throw new TypeError(errorText);
}
if (!isFunction(options.PromiseImpl)) {
throw new TypeError(errorText + '.PromiseImpl');
}
if (!isUndefined(options.constructorMixin) && !isFunction(options.constructorMixin)) {
throw new TypeError(errorText + '.PromiseImpl');
}
var PromiseImpl = options.PromiseImpl;
var constructorMixin = options.constructorMixin;
var plumbing = {};
plumbing.init = function (requestOptions) {
var self = this;
self._rp_promise = new PromiseImpl(function (resolve, reject) {
self._rp_resolve = resolve;
self._rp_reject = reject;
if (constructorMixin) {
constructorMixin.apply(self, arguments); // Using arguments since specific Promise libraries may pass additional parameters
}
});
self._rp_callbackOrig = requestOptions.callback;
requestOptions.callback = self.callback = function RP$callback(err, response, body) {
plumbing.callback.call(self, err, response, body);
};
if (isString(requestOptions.method)) {
requestOptions.method = requestOptions.method.toUpperCase();
}
requestOptions.transform = requestOptions.transform || plumbing.defaultTransformations[requestOptions.method];
self._rp_options = requestOptions;
self._rp_options.simple = requestOptions.simple !== false;
self._rp_options.resolveWithFullResponse = requestOptions.resolveWithFullResponse === true;
self._rp_options.transform2xxOnly = requestOptions.transform2xxOnly === true;
};
plumbing.defaultTransformations = {
HEAD: function (body, response, resolveWithFullResponse) {
return resolveWithFullResponse ? response : response.headers;
}
};
plumbing.callback = function (err, response, body) {
var self = this;
var origCallbackThrewException = false, thrownException = null;
if (isFunction(self._rp_callbackOrig)) {
try {
self._rp_callbackOrig.apply(self, arguments); // TODO: Apply to self mimics behavior of request@2. Is that also right for request@next?
} catch (e) {
origCallbackThrewException = true;
thrownException = e;
}
}
var is2xx = !err && /^2/.test('' + response.statusCode);
if (err) {
self._rp_reject(new errors.RequestError(err, self._rp_options, response));
} else if (self._rp_options.simple && !is2xx) {
if (isFunction(self._rp_options.transform) && self._rp_options.transform2xxOnly === false) {
(new PromiseImpl(function (resolve) {
resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise
}))
.then(function (transformedResponse) {
self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, transformedResponse));
})
.catch(function (transformErr) {
self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response));
});
} else {
self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, response));
}
} else {
if (isFunction(self._rp_options.transform) && (is2xx || self._rp_options.transform2xxOnly === false)) {
(new PromiseImpl(function (resolve) {
resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise
}))
.then(function (transformedResponse) {
self._rp_resolve(transformedResponse);
})
.catch(function (transformErr) {
self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response));
});
} else if (self._rp_options.resolveWithFullResponse) {
self._rp_resolve(response);
} else {
self._rp_resolve(body);
}
}
if (origCallbackThrewException) {
throw thrownException;
}
};
plumbing.exposePromiseMethod = function (exposeTo, bindTo, promisePropertyKey, methodToExpose, exposeAs) {
exposeAs = exposeAs || methodToExpose;
if (exposeAs in exposeTo) {
throw new Error('Unable to expose method "' + exposeAs + '"');
}
exposeTo[exposeAs] = function RP$exposed() {
var self = bindTo || this;
return self[promisePropertyKey][methodToExpose].apply(self[promisePropertyKey], arguments);
};
};
plumbing.exposePromise = function (exposeTo, bindTo, promisePropertyKey, exposeAs) {
exposeAs = exposeAs || 'promise';
if (exposeAs in exposeTo) {
throw new Error('Unable to expose method "' + exposeAs + '"');
}
exposeTo[exposeAs] = function RP$promise() {
var self = bindTo || this;
return self[promisePropertyKey];
};
};
return plumbing;
};
{
"name": "request-promise-core",
"version": "1.1.1",
"description": "Core Promise support implementation for the simplified HTTP request client 'request'.",
"keywords": [
"xhr",
"http",
"https",
"promise",
"request",
"then",
"thenable",
"core"
],
"main": "./lib/plumbing.js",
"scripts": {
"test": "./node_modules/.bin/gulp ci",
"test-publish": "./node_modules/.bin/gulp ci-no-cov",
"publish-please": "publish-please",
"prepublish": "publish-please guard"
},
"repository": {
"type": "git",
"url": "git+https://github.com/request/promise-core.git"
},
"author": "Nicolai Kamenzky (https://github.com/analog-nico)",
"license": "ISC",
"bugs": {
"url": "https://github.com/request/promise-core/issues"
},
"homepage": "https://github.com/request/promise-core#readme",
"engines": {
"node": ">=0.10.0"
},
"dependencies": {
"lodash": "^4.13.1"
},
"peerDependencies": {
"request": "^2.34"
},
"devDependencies": {
"@request/api": "^0.6.0",
"@request/client": "^0.1.0",
"bluebird": "~3.4.1",
"body-parser": "~1.15.2",
"chai": "~3.5.0",
"chalk": "~1.1.3",
"gulp": "~3.9.1",
"gulp-coveralls": "~0.1.4",
"gulp-eslint": "~2.1.0",
"gulp-istanbul": "~1.0.0",
"gulp-mocha": "~2.2.0",
"node-version": "~1.0.0",
"publish-please": "~2.1.4",
"request": "^2.34.0",
"rimraf": "~2.5.3",
"run-sequence": "~1.2.2",
"stealthy-require": "~1.0.0"
},
"_from": "request-promise-core@1.1.1",
"_resolved": "http://registry.npm.taobao.org/request-promise-core/download/request-promise-core-1.1.1.tgz"
}
\ No newline at end of file
/.idea/
/coverage/
/test/
/.editorconfig
/.eslintrc.json
/.gitignore
/.publishrc
/.travis.yml
/gulpfile.js
/run-request-tests.md
.DS_Store
npm-debug.log
\ No newline at end of file
Mon Aug 07 2017 15:31:47 GMT+0800 (CST)
\ No newline at end of file
ISC License
Copyright (c) 2017, Nicolai Kamenzky, Ty Abonil, and contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
\ No newline at end of file
'use strict';
module.exports = require('request-promise-core/errors');
'use strict';
var Bluebird = require('bluebird').getNewLibraryCopy(),
configure = require('request-promise-core/configure/request2'),
stealthyRequire = require('stealthy-require');
try {
// Load Request freshly - so that users can require an unaltered request instance!
var request = stealthyRequire(require.cache, function () {
return require('request');
},
function () {
require('tough-cookie');
}, module);
} catch (err) {
/* istanbul ignore next */
var EOL = require('os').EOL;
/* istanbul ignore next */
console.error(EOL + '###' + EOL + '### The "request" library is not installed automatically anymore.' + EOL + '### But required by "request-promise".' + EOL + '###' + EOL + '### npm install request --save' + EOL + '###' + EOL);
/* istanbul ignore next */
throw err;
}
Bluebird.config({cancellation: true});
configure({
request: request,
PromiseImpl: Bluebird,
expose: [
'then',
'catch',
'finally',
'cancel',
'promise'
],
constructorMixin: function (resolve, reject, onCancel) {
var self = this;
onCancel(function () {
self.abort();
});
}
});
request.bindCLS = function RP$bindCLS() {
throw new Error('CLS support was dropped. To get it back read: https://github.com/request/request-promise/wiki/Getting-Back-Support-for-Continuation-Local-Storage');
};
module.exports = request;
../../_bluebird@3.5.0@bluebird
\ No newline at end of file
../../_request-promise-core@1.1.1@request-promise-core
\ No newline at end of file
../../_stealthy-require@1.1.1@stealthy-require
\ No newline at end of file
../../_tough-cookie@2.3.2@tough-cookie
\ No newline at end of file
{
"name": "request-promise",
"version": "4.2.1",
"description": "The simplified HTTP request client 'request' with Promise support. Powered by Bluebird.",
"keywords": [
"xhr",
"http",
"https",
"promise",
"request",
"then",
"thenable",
"bluebird"
],
"main": "./lib/rp.js",
"scripts": {
"test": "./node_modules/.bin/gulp ci",
"test-publish": "./node_modules/.bin/gulp ci-no-cov",
"publish-please": "publish-please",
"prepublish": "publish-please guard"
},
"repository": {
"type": "git",
"url": "git+https://github.com/request/request-promise.git"
},
"author": "Nicolai Kamenzky (https://github.com/analog-nico)",
"license": "ISC",
"bugs": {
"url": "https://github.com/request/request-promise/issues"
},
"homepage": "https://github.com/request/request-promise#readme",
"engines": {
"node": ">=0.10.0"
},
"dependencies": {
"request-promise-core": "1.1.1",
"bluebird": "^3.5.0",
"stealthy-require": "^1.1.0",
"tough-cookie": ">=2.3.0"
},
"peerDependencies": {
"request": "^2.34"
},
"devDependencies": {
"body-parser": "~1.15.2",
"chai": "~3.5.0",
"chalk": "~1.1.3",
"gulp": "~3.9.1",
"gulp-coveralls": "~0.1.4",
"gulp-eslint": "~2.1.0",
"gulp-istanbul": "~1.0.0",
"gulp-mocha": "~2.2.0",
"lodash": "~4.13.1",
"publish-please": "~2.1.4",
"request": "^2.34.0",
"rimraf": "~2.5.3",
"run-sequence": "~1.2.2"
},
"_from": "request-promise@4.2.1",
"_resolved": "http://registry.npm.taobao.org/request-promise/download/request-promise-4.2.1.tgz"
}
\ No newline at end of file
/.idea/
/coverage/
/test/
/.editorconfig
/.eslintrc.json
/.gitignore
/.publishrc
/.travis.yml
/gulpfile.js
.DS_Store
npm-debug.log
\ No newline at end of file
Mon Aug 07 2017 15:31:48 GMT+0800 (CST)
\ No newline at end of file
ISC License
Copyright (c) 2017, Nicolai Kamenzky and contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
\ No newline at end of file
# Stealthy-Require
[![Build Status](https://img.shields.io/travis/analog-nico/stealthy-require/master.svg?style=flat-square)](https://travis-ci.org/analog-nico/stealthy-require)
[![Coverage Status](https://img.shields.io/coveralls/analog-nico/stealthy-require.svg?style=flat-square)](https://coveralls.io/r/analog-nico/stealthy-require)
[![Dependency Status](https://img.shields.io/david/analog-nico/stealthy-require.svg?style=flat-square)](https://david-dm.org/analog-nico/stealthy-require)
This is probably the closest you can currently get to require something in node.js with completely bypassing the require cache.
`stealthy-require` works like this:
1. It clears the require cache.
2. It calls a callback in which you require your module(s) without the cache kicking in.
3. It clears the cache again and restores its old state.
The restrictions are:
- [Native modules cannot be required twice.](https://github.com/nodejs/node/issues/5016) Thus this module bypasses the require cache only for non-native (e.g. JS) modules.
- The require cache is only bypassed for all operations that happen synchronously when a module is required. If a module lazy loads another module at a later time that require call will not bypass the cache anymore.
This means you should have a close look at all internal require calls before you decide to use this library.
## Installation
[![NPM Stats](https://nodei.co/npm/stealthy-require.png?downloads=true)](https://npmjs.org/package/stealthy-require)
This is a module for node.js and is installed via npm:
``` bash
npm install stealthy-require --save
```
## Usage
Let's say you want to bypass the require cache for this require call:
``` js
var request = require('request');
```
With `stealthy-require` you can do that like this:
``` js
var stealthyRequire = require('stealthy-require');
var requestFresh = stealthyRequire(require.cache, function () {
return require('request');
});
```
The require cache is bypassed for the module you require (i.e. `request`) as well as all modules the module requires (i.e. `http` and many more).
Sometimes the require cache shall not be bypassed for specific modules. E.g. `request` is required but `tough-cookie` – on which `request` depends on – shall be required using the regular cache. For that you can pass two extra arguments to `stealthyRequire(...)`:
- A callback that requires the modules that shall be required without bypassing the cache
- The `module` variable
``` js
var stealthyRequire = require('stealthy-require');
var requestFresh = stealthyRequire(require.cache, function () {
return require('request');
},
function () {
require('tough-cookie'); // No return needed
// You can require multiple modules here
}, module);
```
## Usage with Module Bundlers
- [Webpack](https://webpack.github.io) works out-of-the-box like described in the [Usage section](#usage) above.
- [Browserify](http://browserify.org) does not expose `require.cache`. However, as of `browserify@13.0.1` the cache is passed as the 6th argument to CommonJS modules. Thus you can pass this argument instead:
``` js
// Tweak for Browserify - using arguments[5] instead of require.cache
var requestFresh = stealthyRequire(arguments[5], function () {
return require('request');
});
```
## Preventing a Memory Leak When Repeatedly Requiring Fresh Module Instances in Node.js
If you are using `stealthy-require` in node.js and repeatedly require fresh module instances the `module.children` array will hold all module instances which prevents unneeded instances to be garbage collected.
Assume your code calls `doSomething()` repeatedly.
``` js
var stealthyRequire = require('stealthy-require');
function doSomething() {
var freshInstance = stealthyRequire(require.cache, function () {
return require('some-module');
});
return freshInstance.calc();
}
```
After `doSomething()` returns `freshInstance` is not used anymore but won’t be garbage collected because `module.children` still holds a reference. The solution is to truncate `module.children` accordingly:
``` js
var stealthyRequire = require('stealthy-require');
function doSomething() {
var initialChildren = module.children.slice(); // Creates a shallow copy of the array
var freshInstance = stealthyRequire(require.cache, function () {
return require('some-module');
});
module.children = initialChildren;
return freshInstance.calc();
}
```
The `slice` operation removes all new `module.children` entries created during the `stealthyRequire(...)` call and thus `freshInstance` gets garbage collected after `doSomething()` returns.
## Technical Walkthrough
``` js
// 1. Load stealthy-require
var stealthyRequire = require('stealthy-require');
// This does nothing but loading the code.
// It has no side-effects like patching the module loader or anything.
// Any regular require works as always.
var request1 = require('request');
// 2. Call stealthyRequire with passing the require cache and a callback.
var requestFresh = stealthyRequire(require.cache, function () {
// 2a. Before this callback gets called the require cache is cleared.
// 2b. Any require taking place here takes place on a clean require cache.
// Since the require call is part of the user's code it also works with module bundlers.
return require('request');
// Anything returned here will be returned by stealthyRequire(...).
// 2c. After this callback gets called the require cache is
// - cleared again and
// - restored to its old state before step 2.
});
// Any regular require again works as always.
// In this case require returns the cached request module instance.
var request2 = require('request');
// And voilà:
request1 === request2 // -> true
request1 === requestFresh // -> false
```
## Contributing
To set up your development environment for `stealthy-require`:
1. Clone this repo to your desktop,
2. in the shell `cd` to the main folder,
3. hit `npm install`,
4. hit `npm install gulp -g` if you haven't installed gulp globally yet, and
5. run `gulp dev`. (Or run `node ./node_modules/.bin/gulp dev` if you don't want to install gulp globally.)
`gulp dev` watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from `./coverage/lcov-report/index.html`.
If you want to debug a test you should use `gulp test-without-coverage` to run all tests without obscuring the code by the test coverage instrumentation.
## Change History
- v1.1.1 (2017-05-08)
- Fix that stops `undefined` entries from appearing in `require.cache` *(Thanks to @jasperjn from reporting this in [issue #4](https://github.com/analog-nico/stealthy-require/issues/4))*
- v1.1.0 (2017-04-25)
- Added ability to disable bypassing the cache for certain modules *(Thanks to @novemberborn for suggesting this in [issue #3](https://github.com/analog-nico/stealthy-require/issues/3))*
- Added section in README about a [potential memory leak](#preventing-a-memory-leak-when-repeatedly-requiring-fresh-module-instances-in-nodejs) *(Thanks to @Flarna and @novemberborn for bringing that up in [issue #2](https://github.com/analog-nico/stealthy-require/issues/2))*
- Performance optimizations *(Thanks to @jcready for [pull request #1](https://github.com/analog-nico/stealthy-require/pull/1))*
- v1.0.0 (2016-07-18)
- **Breaking Change:** API completely changed. Please read the [Usage section](#usage) again.
- Redesigned library to support module bundlers like [Webpack](https://webpack.github.io) and [Browserify](http://browserify.org)
- v0.1.0 (2016-05-26)
- Initial version
## License (ISC)
In case you never heard about the [ISC license](http://en.wikipedia.org/wiki/ISC_license) it is functionally equivalent to the MIT license.
See the [LICENSE file](LICENSE) for details.
'use strict';
var isNative = /\.node$/;
function forEach(obj, callback) {
for ( var key in obj ) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) {
continue;
}
callback(key);
}
}
function assign(target, source) {
forEach(source, function (key) {
target[key] = source[key];
});
return target;
}
function clearCache(requireCache) {
forEach(requireCache, function (resolvedPath) {
if (!isNative.test(resolvedPath)) {
delete requireCache[resolvedPath];
}
});
}
module.exports = function (requireCache, callback, callbackForModulesToKeep, module) {
var originalCache = assign({}, requireCache);
clearCache(requireCache);
if (callbackForModulesToKeep) {
var originalModuleChildren = module.children ? module.children.slice() : false; // Creates a shallow copy of module.children
callbackForModulesToKeep();
// Lists the cache entries made by callbackForModulesToKeep()
var modulesToKeep = [];
forEach(requireCache, function (key) {
modulesToKeep.push(key);
});
// Discards the modules required in callbackForModulesToKeep()
clearCache(requireCache);
if (module.children) { // Only true for node.js
module.children = originalModuleChildren; // Removes last references to modules required in callbackForModulesToKeep() -> No memory leak
}
// Takes the cache entries of the original cache in case the modules where required before
for ( var i = 0; i < modulesToKeep.length; i+=1 ) {
if (originalCache[modulesToKeep[i]]) {
requireCache[modulesToKeep[i]] = originalCache[modulesToKeep[i]];
}
}
}
var freshModule = callback();
var stealthCache = callbackForModulesToKeep ? assign({}, requireCache) : false;
clearCache(requireCache);
if (callbackForModulesToKeep) {
// In case modules to keep were required inside the stealthy require for the first time, copy them to the restored cache
for ( var k = 0; k < modulesToKeep.length; k+=1 ) {
if (stealthCache[modulesToKeep[k]]) {
requireCache[modulesToKeep[k]] = stealthCache[modulesToKeep[k]];
}
}
}
assign(requireCache, originalCache);
return freshModule;
};
{
"name": "stealthy-require",
"version": "1.1.1",
"description": "The closest you can get to require something with bypassing the require cache",
"keywords": [
"require",
"bypass",
"no",
"cache",
"fresh"
],
"main": "./lib/index.js",
"scripts": {
"test": "./node_modules/.bin/gulp ci",
"test-publish": "./node_modules/.bin/gulp ci-no-cov",
"publish-please": "publish-please",
"prepublish": "publish-please guard"
},
"repository": {
"type": "git",
"url": "git+https://github.com/analog-nico/stealthy-require.git"
},
"author": "Nicolai Kamenzky (https://github.com/analog-nico)",
"license": "ISC",
"bugs": {
"url": "https://github.com/analog-nico/stealthy-require/issues"
},
"homepage": "https://github.com/analog-nico/stealthy-require#readme",
"engines": {
"node": ">=0.10.0"
},
"dependencies": {},
"devDependencies": {
"bcrypt": "~1.0.2",
"browserify": "~14.3.0",
"chai": "~3.5.0",
"chalk": "~1.1.3",
"gulp": "~3.9.1",
"gulp-coveralls": "~0.1.4",
"gulp-eslint": "~2.1.0",
"gulp-istanbul": "~1.1.1",
"gulp-mocha": "~3.0.1",
"mkdirp": "~0.5.1",
"publish-please": "~2.3.1",
"rimraf": "~2.6.1",
"run-sequence": "~1.2.2",
"webpack": "~1.15.0"
},
"_from": "stealthy-require@1.1.1",
"_resolved": "http://registry.npm.taobao.org/stealthy-require/download/stealthy-require-1.1.1.tgz"
}
\ No newline at end of file
_pify@3.0.0@pify
\ No newline at end of file
_request-promise@4.2.1@request-promise
\ No newline at end of file
_request-promise-core@1.1.1@request-promise-core
\ No newline at end of file
_stealthy-require@1.1.1@stealthy-require
\ No newline at end of file
......@@ -7,6 +7,7 @@
"phantom": "^4.0.5",
"redis": "^2.7.1",
"request": "^2.81.0",
"request-promise": "^4.2.1",
"toml": "^2.3.2"
}
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
try.png

269 KB

try2.png

104 KB

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 sign in to comment