Socket
Socket
Sign inDemoInstall

popsicle

Package Overview
Dependencies
Maintainers
1
Versions
99
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

popsicle - npm Package Compare versions

Comparing version 8.2.0 to 9.0.0

dist/support.d.ts

6

dist/base.d.ts

@@ -15,3 +15,3 @@ import { Url } from 'url';

}
export default class Base {
export declare class Base {
Url: Url;

@@ -26,4 +26,4 @@ rawHeaders: RawHeaders;

append(name: string, value?: string | string[]): this;
name(name: string): string;
get(name: string): string;
name(name: string): string | undefined;
get(name: string): string | undefined;
getAll(name: string): string[];

@@ -30,0 +30,0 @@ remove(name: string): this;

"use strict";
var url_1 = require('url');
var querystring_1 = require('querystring');
var extend = require('xtend');
var url_1 = require("url");
var querystring_1 = require("querystring");
var support_1 = require("./support");
function lowerHeader(key) {

@@ -30,3 +30,3 @@ var lower = key.toLowerCase();

if (query != null) {
this.query = extend(this.query, typeof query === 'string' ? querystring_1.parse(query) : query);
this.query = Object.assign(this.query, typeof query === 'string' ? querystring_1.parse(query) : query);
}

@@ -118,9 +118,8 @@ if (rawHeaders) {

var lowered = lowerHeader(name);
var headerName;
for (var i = 0; i < this.rawHeaders.length; i += 2) {
if (lowerHeader(this.rawHeaders[i]) === lowered) {
headerName = this.rawHeaders[i];
return this.rawHeaders[i];
}
}
return headerName;
return undefined;
};

@@ -134,2 +133,3 @@ Base.prototype.get = function (name) {

}
return undefined;
};

@@ -148,6 +148,5 @@ Base.prototype.getAll = function (name) {

var lowered = lowerHeader(name);
var len = this.rawHeaders.length;
while ((len -= 2) >= 0) {
if (lowerHeader(this.rawHeaders[len]) === lowered) {
this.rawHeaders.splice(len, 2);
for (var i = 0; i < this.rawHeaders.length; i += 2) {
if (lowerHeader(this.rawHeaders[i]) === lowered) {
support_1.splice(this.rawHeaders, i, 2);
}

@@ -165,4 +164,3 @@ }

}());
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Base;
exports.Base = Base;
//# sourceMappingURL=base.js.map

@@ -1,4 +0,3 @@

import Promise = require('any-promise');
import Request from './request';
import Response from './response';
import { Request } from './request';
import { Response } from './response';
export declare type Types = 'text' | 'document' | 'blob' | 'arraybuffer' | 'json' | string;

@@ -11,5 +10,5 @@ export interface Options {

export declare function createTransport(options: Options): {
use: ((request: Request, next: () => Promise<Response>) => Promise<Response>)[];
use: ((request: Request, next: () => Promise<Response>) => Promise<never>)[];
abort: (request: Request) => void;
open(request: Request): Promise<Response>;
};
"use strict";
var Promise = require('any-promise');
var response_1 = require('./response');
var index_1 = require('./plugins/index');
var response_1 = require("./response");
var index_1 = require("./plugins/index");
function createTransport(options) {

@@ -26,3 +25,3 @@ return {

return new Promise(function (resolve) {
return resolve(new response_1.default({
return resolve(new response_1.Response({
status: xhr.status === 1223 ? 204 : xhr.status,

@@ -29,0 +28,0 @@ statusText: xhr.statusText,

import FormData = require('form-data');
import Request, { RequestOptions, DefaultsOptions } from './request';
import Response from './response';
import { Request, RequestOptions, DefaultsOptions } from './request';
import * as plugins from './plugins/index';

@@ -9,11 +8,14 @@ import form from './form';

import { createTransport } from './index';
export declare function defaults(defaultsOptions: DefaultsOptions): (options: RequestOptions | string) => Request;
export declare const request: (options: RequestOptions | string) => Request;
export declare const get: (options: RequestOptions | string) => Request;
export declare const post: (options: RequestOptions | string) => Request;
export declare const put: (options: RequestOptions | string) => Request;
export declare const patch: (options: RequestOptions | string) => Request;
export declare const del: (options: RequestOptions | string) => Request;
export declare const head: (options: RequestOptions | string) => Request;
export { Request, Response, PopsicleError, FormData, plugins, form, jar, createTransport };
export declare function defaults(defaultsOptions: DefaultsOptions): (options: string | RequestOptions) => Request;
export declare const request: (options: string | RequestOptions) => Request;
export declare const get: (options: string | RequestOptions) => Request;
export declare const post: (options: string | RequestOptions) => Request;
export declare const put: (options: string | RequestOptions) => Request;
export declare const patch: (options: string | RequestOptions) => Request;
export declare const del: (options: string | RequestOptions) => Request;
export declare const head: (options: string | RequestOptions) => Request;
export { PopsicleError, FormData, plugins, form, jar, createTransport };
export * from './base';
export * from './request';
export * from './response';
export default request;
"use strict";
var FormData = require('form-data');
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
var FormData = require("form-data");
exports.FormData = FormData;
var extend = require('xtend');
var request_1 = require('./request');
exports.Request = request_1.default;
var response_1 = require('./response');
exports.Response = response_1.default;
var plugins = require('./plugins/index');
var request_1 = require("./request");
var plugins = require("./plugins/index");
exports.plugins = plugins;
var form_1 = require('./form');
var form_1 = require("./form");
exports.form = form_1.default;
var jar_1 = require('./jar');
var jar_1 = require("./jar");
exports.jar = jar_1.default;
var error_1 = require('./error');
var error_1 = require("./error");
exports.PopsicleError = error_1.default;
var index_1 = require('./index');
var index_1 = require("./index");
exports.createTransport = index_1.createTransport;
function defaults(defaultsOptions) {
var transport = index_1.createTransport({ type: 'text' });
var defaults = extend({ transport: transport }, defaultsOptions);
var defaults = Object.assign({}, { transport: transport }, defaultsOptions);
return function popsicle(options) {
var opts;
if (typeof options === 'string') {
opts = extend(defaults, { url: options });
}
else {
opts = extend(defaults, options);
}
var opts = Object.assign({}, defaults, typeof options === 'string' ? { url: options } : options);
if (typeof opts.url !== 'string') {
throw new TypeError('The URL must be a string');
}
return new request_1.default(opts);
return new request_1.Request(opts);
};

@@ -44,4 +37,7 @@ }

exports.head = defaults({ method: 'head' });
__export(require("./base"));
__export(require("./request"));
__export(require("./response"));
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = exports.request;
//# sourceMappingURL=common.js.map
import makeErrorCause = require('make-error-cause');
import Request from './request';
import { Request } from './request';
export default class PopsicleError extends makeErrorCause.BaseError {

@@ -4,0 +4,0 @@ code: string;

@@ -7,10 +7,11 @@ "use strict";

};
var makeErrorCause = require('make-error-cause');
var makeErrorCause = require("make-error-cause");
var PopsicleError = (function (_super) {
__extends(PopsicleError, _super);
function PopsicleError(message, code, original, popsicle) {
_super.call(this, message, original);
this.name = 'PopsicleError';
this.code = code;
this.popsicle = popsicle;
var _this = _super.call(this, message, original) || this;
_this.name = 'PopsicleError';
_this.code = code;
_this.popsicle = popsicle;
return _this;
}

@@ -17,0 +18,0 @@ return PopsicleError;

"use strict";
var FormData = require('form-data');
var FormData = require("form-data");
function form(obj) {

@@ -4,0 +4,0 @@ var form = new FormData();

import { IncomingMessage, ClientRequest } from 'http';
import Promise = require('any-promise');
import Request from './request';
import Response from './response';
import { CookieJar } from 'tough-cookie';
import { Request } from './request';
import { Response } from './response';
export declare type Types = 'text' | 'buffer' | 'array' | 'uint8array' | 'stream' | string;

@@ -9,3 +9,3 @@ export interface Options {

unzip?: boolean;
jar?: any;
jar?: CookieJar;
agent?: any;

@@ -22,5 +22,5 @@ maxRedirects?: number;

export declare function createTransport(options: Options): {
use: ((request: Request, next: () => Promise<Response>) => Promise<Response>)[];
use: ((request: Request, next: () => Promise<Response>) => Promise<never>)[];
abort: (request: Request) => void;
open(request: Request): Promise<{}>;
open(request: Request): Promise<any>;
};
"use strict";
var http_1 = require('http');
var https_1 = require('https');
var stream_1 = require('stream');
var urlLib = require('url');
var arrify = require('arrify');
var concat = require('concat-stream');
var Promise = require('any-promise');
var zlib_1 = require('zlib');
var response_1 = require('./response');
var index_1 = require('./plugins/index');
var http_1 = require("http");
var https_1 = require("https");
var stream_1 = require("stream");
var urlLib = require("url");
var concat = require("concat-stream");
var zlib_1 = require("zlib");
var response_1 = require("./response");
var index_1 = require("./plugins/index");
var validTypes = ['text', 'buffer', 'array', 'uint8array', 'stream'];

@@ -43,3 +41,3 @@ function createTransport(options) {

var maxBufferSize = num(options.maxBufferSize, type === 'stream' ? Infinity : 2 * 1000 * 1000);
var storeCookies = getStoreCookies(request, options);
var storeCookies = getStoreCookies(options);
var attachCookies = getAttachCookies(request, options);

@@ -115,5 +113,5 @@ var confirmRedirect = options.confirmRedirect || falsey;

incomingMessage.pipe(responseStream);
return handleResponse(request, responseStream, headers, options)
return handleResponse(responseStream, headers, options)
.then(function (body) {
return new response_1.default({
return new response_1.Response({
status: status,

@@ -172,5 +170,4 @@ headers: headers,

function getAttachCookies(request, options) {
var jar = options.jar;
var cookie = request.getAll('Cookie');
if (!jar) {
var requestCookieString = request.getAll('Cookie').join('; ');
if (!options.jar) {
return function () { return Promise.resolve(); };

@@ -180,10 +177,13 @@ }

return new Promise(function (resolve, reject) {
request.set('Cookie', cookie);
options.jar.getCookies(url, function (err, cookies) {
var cookieString = requestCookieString;
options.jar.getCookieString(url, function (err, jarCookieString) {
if (err) {
return reject(err);
}
if (cookies.length) {
request.append('Cookie', cookies.join('; '));
if (jarCookieString) {
cookieString = cookieString ? cookieString + "; " + jarCookieString : jarCookieString;
}
if (cookieString) {
request.set('Cookie', cookieString);
}
return resolve();

@@ -194,3 +194,3 @@ });

}
function getStoreCookies(request, options) {
function getStoreCookies(options) {
var jar = options.jar;

@@ -201,7 +201,7 @@ if (!jar) {

return function (url, headers) {
var cookies = arrify(headers['set-cookie']);
if (!cookies.length) {
var cookies = headers['set-cookie'];
if (!cookies) {
return Promise.resolve();
}
var storeCookies = cookies.map(function (cookie) {
var storeCookies = (Array.isArray(cookies) ? cookies : [cookies]).map(function (cookie) {
return new Promise(function (resolve, reject) {

@@ -216,3 +216,3 @@ jar.setCookie(cookie, url, { ignoreError: true }, function (err) {

}
function handleResponse(request, stream, headers, options) {
function handleResponse(stream, headers, options) {
var type = options.type || 'text';

@@ -219,0 +219,0 @@ var unzip = options.unzip !== false;

"use strict";
var tough_cookie_1 = require('tough-cookie');
var tough_cookie_1 = require("tough-cookie");
function cookieJar(store) {

@@ -4,0 +4,0 @@ return new tough_cookie_1.CookieJar(store);

@@ -5,3 +5,3 @@ "use strict";

}
__export(require('./common'));
__export(require("./common"));
//# sourceMappingURL=browser.js.map

@@ -1,8 +0,7 @@

import Promise = require('any-promise');
import Request from '../request';
import Response from '../response';
import { Request } from '../request';
import { Response } from '../response';
export declare function wrap<T>(value: T): () => T;
export declare const headers: () => (request: Request, next: () => Promise<Response>) => Promise<Response>;
export declare const stringify: () => (request: Request, next: () => Promise<Response>) => Promise<Response>;
export declare const stringify: () => (request: Request, next: () => Promise<Response>) => Promise<never>;
export declare type ParseType = 'json' | 'urlencoded';
export declare function parse(type: ParseType | ParseType[], strict?: boolean): (request: Request, next: () => Promise<Response>) => Promise<Response>;
"use strict";
var Promise = require('any-promise');
var FormData = require('form-data');
var arrify = require('arrify');
var querystring_1 = require('querystring');
var index_1 = require('./is-host/index');
var form_1 = require('../form');
var FormData = require("form-data");
var querystring_1 = require("querystring");
var index_1 = require("./is-host/index");
var form_1 = require("../form");
var JSON_MIME_REGEXP = /^application\/(?:[\w!#\$%&\*`\-\.\^~]*\+)?json$/i;

@@ -57,3 +55,3 @@ var URL_ENCODED_MIME_REGEXP = /^application\/x-www-form-urlencoded$/i;

function parse(type, strict) {
var types = arrify(type);
var types = Array.isArray(type) ? type : [type];
for (var _i = 0, types_1 = types; _i < types_1.length; _i++) {

@@ -75,3 +73,3 @@ var type_1 = types_1[_i];

if (responseType == null) {
throw request.error("Unable to parse invalid response content type", 'EPARSE');
throw request.error("Unable to parse empty response content type", 'EPARSE');
}

@@ -78,0 +76,0 @@ if (typeof body !== 'string') {

@@ -1,5 +0,4 @@

import Promise = require('any-promise');
import Request from '../request';
import Response from '../response';
import { Request } from '../request';
import { Response } from '../response';
export * from './common';
export declare function headers(): (request: Request, next: () => Promise<Response>) => Promise<Response>;

@@ -5,6 +5,5 @@ "use strict";

}
var FormData = require('form-data');
var Promise = require('any-promise');
var common_1 = require('./common');
__export(require('./common'));
var FormData = require("form-data");
var common_1 = require("./common");
__export(require("./common"));
function headers() {

@@ -19,3 +18,3 @@ var common = common_1.headers();

request.set('Content-Type', 'multipart/form-data; boundary=' + request.body.getBoundary());
return new Promise(function (resolve, reject) {
return new Promise(function (resolve) {
request.body.getLength(function (err, length) {

@@ -22,0 +21,0 @@ if (err) {

@@ -1,7 +0,5 @@

import Promise = require('any-promise');
import Base, { BaseOptions, Headers } from './base';
import Response, { ResponseJSON } from './response';
import { Base, BaseOptions, Headers } from './base';
import { Response } from './response';
import PopsicleError from './error';
export interface DefaultsOptions extends BaseOptions {
url?: string;
method?: string;

@@ -11,3 +9,2 @@ timeout?: number;

use?: Middleware[];
progress?: ProgressFunction[];
transport?: TransportOptions;

@@ -17,2 +14,3 @@ }

url: string;
events?: Events;
}

@@ -25,4 +23,7 @@ export interface RequestJSON {

method: string;
response: ResponseJSON;
}
export interface Events {
abort: EventList<(this: Request) => void>;
progress: EventList<(this: Request) => void>;
}
export interface TransportOptions {

@@ -33,5 +34,8 @@ open: (request: Request) => Promise<Response>;

}
export declare type EventList<T extends (...args: any[]) => void> = Array<EventFn<T>>;
export declare type EventFn<T extends (...args: any[]) => void> = T & {
listener?: T;
};
export declare type Middleware = (request: Request, next: () => Promise<Response>) => Response | Promise<Response>;
export declare type ProgressFunction = (request: Request) => any;
export default class Request extends Base implements Promise<Response> {
export declare class Request extends Base {
method: string;

@@ -41,3 +45,3 @@ timeout: number;

transport: TransportOptions;
response: Response;
events: Events;
middleware: Middleware[];

@@ -53,24 +57,23 @@ opened: boolean;

_raw: any;
_progress: ProgressFunction[];
private _promise;
private _resolve;
private _reject;
_promise: Promise<Response>;
constructor(options: RequestOptions);
error(message: string, code: string, original?: Error): PopsicleError;
then(onFulfilled: (response: Response) => any, onRejected?: (error: PopsicleError) => any): Promise<any>;
catch(onRejected: (error: PopsicleError) => any): Promise<any>;
exec(cb: (error: PopsicleError | void, response?: Response) => void): void;
then<T>(onFulfilled?: (response: Response) => T | PromiseLike<T>, onRejected?: (error: PopsicleError) => T | PromiseLike<T>): Promise<T>;
catch<T>(onRejected: (error: PopsicleError) => T): Promise<T>;
exec(cb: (error: PopsicleError | null, response?: Response) => void): void;
toOptions(): RequestOptions;
toJSON(): RequestJSON;
clone(): Request;
use(fns: Middleware | Middleware[]): this;
progress(fns: ProgressFunction | ProgressFunction[]): this;
use(fn: Middleware | Middleware[]): this;
on(event: keyof Events, fn: (this: this, ...args: any[]) => void): this;
off(event: keyof Events, fn: (this: this, ...args: any[]) => void): this;
once(event: keyof Events, fn: (this: this, ...args: any[]) => void): this;
emit(event: keyof Events, ...args: any[]): this;
abort(): this;
private _emit();
private _handle();
completed: number;
completedBytes: number;
totalBytes: number;
handle(): Promise<never>;
readonly completed: number;
readonly completedBytes: number;
readonly totalBytes: number;
_setUploadedBytes(bytes: number, uploaded?: number): void;
_setDownloadedBytes(bytes: number, downloaded?: number): void;
}

@@ -7,38 +7,28 @@ "use strict";

};
var arrify = require('arrify');
var extend = require('xtend');
var Promise = require('any-promise');
var throwback_1 = require('throwback');
var base_1 = require('./base');
var error_1 = require('./error');
var base_1 = require("./base");
var support_1 = require("./support");
var error_1 = require("./error");
var Request = (function (_super) {
__extends(Request, _super);
function Request(options) {
var _this = this;
_super.call(this, options);
this.middleware = [];
this.opened = false;
this.aborted = false;
this.uploaded = 0;
this.downloaded = 0;
this._progress = [];
this.timeout = (options.timeout | 0);
this.method = (options.method || 'GET').toUpperCase();
this.body = options.body;
var $promise = new Promise(function (resolve, reject) {
_this._resolve = resolve;
_this._reject = reject;
var _this = _super.call(this, options) || this;
_this.middleware = [];
_this.opened = false;
_this.aborted = false;
_this.uploaded = 0;
_this.downloaded = 0;
_this.timeout = (options.timeout | 0);
_this.method = (options.method || 'GET').toUpperCase();
_this.body = options.body;
_this.events = options.events || Object.create(null);
_this.transport = Object.assign({}, options.transport);
_this.use(options.use || _this.transport.use);
_this._promise = Promise.resolve().then(function () { return exec(_this); });
_this.once('abort', function () {
if (_this.completed === 1) {
return;
}
_this.aborted = true;
});
this.transport = extend(options.transport);
this.use(options.use || this.transport.use);
this.progress(options.progress);
this._promise = Promise.resolve()
.then(function () {
var run = throwback_1.compose(_this.middleware);
var cb = function () {
_this._handle();
return $promise;
};
return run(_this, cb);
});
return _this;
}

@@ -55,5 +45,3 @@ Request.prototype.error = function (message, code, original) {

Request.prototype.exec = function (cb) {
this.then(function (response) {
cb(null, response);
}, cb);
this.then(function (res) { return cb(null, res); }, cb);
};

@@ -69,3 +57,3 @@ Request.prototype.toOptions = function () {

use: this.middleware,
progress: this._progress
events: this.events
};

@@ -79,4 +67,3 @@ };

body: this.body,
timeout: this.timeout,
response: this.response ? this.response.toJSON() : null
timeout: this.timeout
};

@@ -87,66 +74,96 @@ };

};
Request.prototype.use = function (fns) {
for (var _i = 0, _a = arrify(fns); _i < _a.length; _i++) {
var fn = _a[_i];
Request.prototype.use = function (fn) {
if (Array.isArray(fn)) {
(_a = this.middleware).push.apply(_a, fn);
}
else {
this.middleware.push(fn);
}
return this;
var _a;
};
Request.prototype.progress = function (fns) {
for (var _i = 0, _a = arrify(fns); _i < _a.length; _i++) {
var fn = _a[_i];
this._progress.push(fn);
Request.prototype.on = function (event, fn) {
if (Object.prototype.hasOwnProperty.call(this.events, event)) {
this.events[event].push(fn);
}
else {
this.events[event] = [fn];
}
return this;
};
Request.prototype.abort = function () {
if (this.completed === 1 || this.aborted) {
return;
}
this.aborted = true;
if (this.opened) {
this._emit();
if (this.transport.abort) {
this.transport.abort(this);
Request.prototype.off = function (event, fn) {
if (Object.prototype.hasOwnProperty.call(this.events, event)) {
var list = this.events[event];
var index = -1;
for (var i = 0; i < list.length; i++) {
if (list[i] === fn || list[i].listener === fn) {
index = i;
break;
}
}
if (index > -1) {
if (list.length === 1) {
delete this.events[event];
}
else {
support_1.splice(this.events[event], index);
}
}
}
this._reject(this.error('Request aborted', 'EABORT'));
return this;
};
Request.prototype._emit = function () {
var fns = this._progress;
try {
for (var _i = 0, fns_1 = fns; _i < fns_1.length; _i++) {
var fn = fns_1[_i];
fn(this);
Request.prototype.once = function (event, fn) {
return this.on(event, wrapOnce(this, event, fn));
};
Request.prototype.emit = function (event) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (!Object.prototype.hasOwnProperty.call(this.events, event)) {
return this;
}
var listeners = this.events[event];
if (listeners.length === 1) {
args.length === 0 ? listeners[0].call(this) : listeners[0].apply(this, args);
}
else {
for (var _a = 0, _b = listeners.slice(); _a < _b.length; _a++) {
var listener = _b[_a];
args.length === 0 ? listener.call(this) : listener.apply(this, args);
}
}
catch (err) {
this._reject(err);
this.abort();
}
return this;
};
Request.prototype._handle = function () {
Request.prototype.abort = function () {
return this.emit('abort');
};
Request.prototype.handle = function () {
var _this = this;
var _a = this, timeout = _a.timeout, url = _a.url;
var timer;
if (this.aborted) {
return;
}
this.opened = true;
if (/^https?\:\/*(?:[~#\\\?;\:]|$)/.test(url)) {
this._reject(this.error("Refused to connect to invalid URL \"" + url + "\"", 'EINVALID'));
return;
if (/^https?\:\/*(?:[~#\\\?;\:]|$)/.test(this.url)) {
return Promise.reject(this.error("Refused to connect to invalid URL \"" + this.url + "\"", 'EINVALID'));
}
var timeout = this.timeout;
var timer;
var result = new Promise(function (resolve, reject) {
if (timeout > 0) {
timer = setTimeout(function () {
reject(_this.error("Timeout of " + timeout + "ms exceeded", 'ETIMEOUT'));
_this.abort();
}, timeout);
}
_this.once('abort', function () {
_this.emit('progress');
reject(_this.error('Request aborted', 'EABORT'));
if (_this.transport.abort) {
_this.transport.abort(_this);
}
});
Promise.resolve(_this.transport.open(_this)).then(function (res) { return resolve(res); }, function (err) { return reject(err); });
});
if (timeout > 0) {
timer = setTimeout(function () {
_this._reject(_this.error("Timeout of " + timeout + "ms exceeded", 'ETIMEOUT'));
_this.abort();
}, timeout);
result.then(function () { return clearTimeout(timer); }, function () { return clearTimeout(timer); });
}
return this.transport.open(this)
.then(function (response) {
_this.response = response;
_this._resolve(response);
}, function (err) { return _this._reject(err); });
return result;
};

@@ -178,3 +195,3 @@ Object.defineProperty(Request.prototype, "completed", {

this.uploadedBytes = bytes;
this._emit();
this.emit('progress');
}

@@ -186,9 +203,43 @@ };

this.downloadedBytes = bytes;
this._emit();
this.emit('progress');
}
};
return Request;
}(base_1.default));
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Request;
}(base_1.Base));
exports.Request = Request;
function wrapOnce(target, event, fn) {
var fired = false;
var g = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!fired) {
fired = true;
target.off(event, fn);
args.length === 0 ? fn.call(target) : fn.apply(target, args);
}
};
g.listener = fn;
return g;
}
function exec(req) {
var index = -1;
function dispatch(pos) {
if (pos <= index) {
throw new TypeError('`next()` called multiple times');
}
if (req.aborted) {
return Promise.reject(req.error('Request aborted', 'EABORT'));
}
index = pos;
var fn = req.middleware[pos] || (function () { return req.handle(); });
return new Promise(function (resolve) {
return resolve(fn(req, function next() {
return dispatch(pos + 1);
}));
});
}
return dispatch(0);
}
//# sourceMappingURL=request.js.map

@@ -1,2 +0,2 @@

import Base, { BaseOptions, Headers } from './base';
import { Base, BaseOptions, Headers } from './base';
export interface ResponseOptions extends BaseOptions {

@@ -14,3 +14,3 @@ body: any;

}
export default class Response extends Base {
export declare class Response extends Base {
status: number;

@@ -17,0 +17,0 @@ statusText: string;

@@ -7,10 +7,11 @@ "use strict";

};
var base_1 = require('./base');
var base_1 = require("./base");
var Response = (function (_super) {
__extends(Response, _super);
function Response(options) {
_super.call(this, options);
this.body = options.body;
this.status = options.status;
this.statusText = options.statusText;
var _this = _super.call(this, options) || this;
_this.body = options.body;
_this.status = options.status;
_this.statusText = options.statusText;
return _this;
}

@@ -30,5 +31,4 @@ Response.prototype.statusType = function () {

return Response;
}(base_1.default));
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Response;
}(base_1.Base));
exports.Response = Response;
//# sourceMappingURL=response.js.map
"use strict";
var test = require('blue-tape');
var methods = require('methods');
var FormData = require('form-data');
var Promise = require('any-promise');
var fs_1 = require('fs');
var path_1 = require('path');
var popsicle = require('../common');
var test = require("blue-tape");
var methods = require("methods");
var FormData = require("form-data");
var fs_1 = require("fs");
var path_1 = require("path");
var popsicle = require("../common");
var SHORTHAND_METHODS = [

@@ -51,11 +50,14 @@ 'get',

t.ok(req instanceof popsicle.Request);
return req.then(null, function () { });
req.set('Test', 'Test');
t.equal(req.rawHeaders.length, 2);
req.remove('Test');
t.equal(req.rawHeaders.length, 0);
return req.then(null, function () { return undefined; });
});
test('use the same response in promise chains', function (t) {
var req = popsicle.get(REMOTE_URL + '/echo');
t.plan(14);
t.plan(13);
return req
.then(function (res) {
t.ok(res instanceof popsicle.Response);
t.equal(req.response, res);
t.ok(typeof res.url === 'string' || res.url == null);

@@ -70,3 +72,3 @@ t.ok(Array.isArray(res.rawHeaders));

t.equal(typeof res.toJSON, 'function');
t.deepEqual(Object.keys(req.toJSON()), ['url', 'method', 'headers', 'body', 'timeout', 'response']);
t.deepEqual(Object.keys(req.toJSON()), ['url', 'method', 'headers', 'body', 'timeout']);
t.deepEqual(Object.keys(res.toJSON()), ['url', 'headers', 'body', 'status', 'statusText']);

@@ -98,3 +100,3 @@ return req

t.ok(res instanceof popsicle.Response);
t.end();
t.end(err);
});

@@ -245,2 +247,3 @@ });

t.deepEqual(res.body, EXAMPLE_BODY);
t.equal(res.name('Content-Type'), 'content-type');
t.equal(res.type(), 'application/x-www-form-urlencoded');

@@ -275,3 +278,3 @@ });

});
t.test('should stringify to form data when set as multipart', function (t) {
t.test('should stringify to form data when set as multipart', function () {
return popsicle.request({

@@ -365,5 +368,3 @@ url: REMOTE_URL + '/echo',

t.plan(1);
setTimeout(function () {
req.abort();
}, 100);
setTimeout(function () { return req.abort(); }, 100);
return req

@@ -386,2 +387,12 @@ .catch(function (err) {

});
t.test('abort cloned requests', function (t) {
var req = popsicle.request(REMOTE_URL + '/download');
var req2 = req.clone();
t.plan(2);
req.abort();
return Promise.all([
req.catch(function (err) { return t.equal(err.code, 'EABORT'); }),
req2.catch(function (err) { return t.equal(err.code, 'EABORT'); })
]);
});
});

@@ -413,7 +424,6 @@ test('progress', function (t) {

t.plan(3);
var asserted = 0;
var expected = 0;
req.progress(function (e) {
req.on('progress', function () {
expected += 0.5;
t.equal(e.completed, expected);
t.equal(this.completed, expected);
});

@@ -426,14 +436,2 @@ return req

});
t.test('error when the progress callback errors', function (t) {
var req = popsicle.request(REMOTE_URL + '/echo');
t.plan(2);
req.progress(function () {
throw new Error('Testing');
});
return req
.catch(function (err) {
t.equal(err.message, 'Testing');
t.notOk(err.popsicle, 'popsicle should not be set');
});
});
});

@@ -545,3 +543,3 @@ });

.then(function (res) {
var boundary = BOUNDARY_REGEXP.exec(res.headers['content-type'])[1];
var boundary = BOUNDARY_REGEXP.exec(res.get('content-type'))[1];
t.equal(res.body, [

@@ -712,3 +710,3 @@ '--' + boundary,

t.plan(1);
req.use(function (self, next) {
req.use(function (_, next) {
return next()

@@ -737,7 +735,7 @@ .then(function (res) {

t.ok(res.get('Set-Cookie'));
cookie = res.get('Set-Cookie');
cookie = res.get('Set-Cookie').split(/ *; */, 1)[0];
return instance(REMOTE_URL + '/echo');
})
.then(function (res) {
t.equal(res.get('Cookie').toLowerCase(), cookie.toLowerCase());
t.equal(res.get('Cookie'), cookie);
t.notOk(res.get('Set-Cookie'));

@@ -763,3 +761,3 @@ });

transport: {
open: function (request) {
open: function () {
return Promise.resolve({

@@ -766,0 +764,0 @@ url: '/foo',

{
"name": "popsicle",
"version": "8.2.0",
"version": "9.0.0",
"description": "Simple HTTP requests for node and the browser",

@@ -21,3 +21,3 @@ "main": "dist/common.js",

"scripts": {
"lint": "# TODO",
"lint": "tslint \"src/**/*.ts\"",
"check-size": "browserify . -s popsicle --external bluebird > popsicle.js && du -h popsicle.js",

@@ -61,3 +61,3 @@ "build": "rm -rf dist/ && tsc && npm run check-size",

"browserify": "^13.0.0",
"envify": "^3.4.0",
"envify": "^4.0.0",
"express": "^4.10.2",

@@ -68,15 +68,13 @@ "istanbul": "^0.4.0",

"tape-run": "2.1.0",
"typescript": "^1.8.9",
"typings": "^1.0.2"
"tslint": "^4.0.2",
"tslint-config-standard": "^2.0.0",
"typescript": "^2.1.4",
"typings": "^2.0.0"
},
"dependencies": {
"any-promise": "^1.3.0",
"arrify": "^1.0.0",
"concat-stream": "^1.4.7",
"form-data": "^2.0.0",
"make-error-cause": "^1.2.1",
"throwback": "^1.1.0",
"tough-cookie": "^2.0.0",
"xtend": "^4.0.0"
"tough-cookie": "^2.0.0"
}
}

@@ -8,3 +8,3 @@ # ![Popsicle](https://cdn.rawgit.com/blakeembrey/popsicle/master/logo.svg)

> **Popsicle** is the easiest way to make HTTP requests - a consistent, intuitive and tiny API that works on node and the browser. 9.64 kB in browsers, after minification and gzipping.
> **Popsicle** is the easiest way to make HTTP requests - a consistent, intuitive and tiny API that works on node and the browser. 9.37 kB in browsers, after minification and gzipping, including dependencies (with `url` being the bulk of it).

@@ -29,3 +29,3 @@ ```js

```js
var popsicle = require('popsicle')
const popsicle = require('popsicle')

@@ -51,12 +51,6 @@ popsicle.request({

**Popsicle** is ES6-ready and aliases `request` to the default export. Try using `import popsicle from 'popsicle'` or import specific methods using `import { get, defaults } from 'popsicle'`. Exports:
**Popsicle** is a promise-based HTTP request library designed for extensibility. Here's the functions you can import from `popsicle`:
* **request(options)** Default request handler - `defaults({})`
* **get(options)** Alias of `request` (GET is the default method)
* **del(options)** Alias of `defaults({ method: 'delete' })`
* **head(options)** Alias of `defaults({ method: 'head' })`
* **patch(options)** Alias of `defaults({ method: 'patch' })`
* **post(options)** Alias of `defaults({ method: 'post' })`
* **put(options)** Alias of `defaults({ method: 'put' })`
* **defaults(options)** Create a new Popsicle instance using `defaults`
* **request(options)** The default request handler (also `get`)
* **defaults(options)** Create a new Popsicle instance with `defaults`
* **form(obj?)** Cross-platform form data object

@@ -69,27 +63,26 @@ * **plugins** Exposes the default plugins (Object)

### Handling Requests
### Request Options
* **url** The resource location
* **method** The HTTP request method (default: `"GET"`)
* **headers** An object with HTTP headers, header name to value (default: `{}`)
* **query** An object or string to be appended to the URL as the query string
* **body** An object, string, form data, stream (node), etc to pass with the request
* **timeout** The number of milliseconds to wait before aborting the request (default: `Infinity`)
* **use** The array of plugins to be used (default: `[stringify(), headers()]`)
* **options** Raw options used by the transport layer (default: `{}`)
* **transport** Set the transport layer (default: `text`)
* **url** _(string)_ The resource location.
* **method** _(string)_ The HTTP request method (default: `"GET"`).
* **headers** _(object)_ A map of header key to value (default: `{}`).
* **query** _(object | string)_ A map or string to be appended to the URL as the query string.
* **body** _(any)_ An object, string, form data, stream (node) or other to pass with the request.
* **timeout** _(number)_ The number of milliseconds to wait before aborting the request (default: `Infinity`)
* **use** _(array)_ An array of plugins to override the defaults (default: `[stringify(), headers()]`)
* **transport** _(object)_ Set the transport layer (default: `createTransport({ type: 'text' })`)
#### Middleware
### Built-in Plugins
##### `stringify`
#### `stringify` (default)
Automatically serialize the request body into a string (E.g. JSON, URL-encoded or multipart).
##### `headers`
#### `headers` (default)
Sets up default headers for environments. For example, `Content-Length`, `User-Agent`, `Accept`, etc.
##### `parse`
#### `parse`
Automatically parses the response body by allowed type(s).
Automatically parses allowed response type(s).

@@ -105,5 +98,5 @@ * **json** Parse response as JSON

#### Transports
### Built-in Transports
Popsicle comes with two built-in transports, one for node (using `{http,https}.request`) and one for browsers (using `XMLHttpRequest`). These transports have a number of "types" built-in for handling the response body.
Popsicle provides two transports, one for node (using `{http,https}.request`) and one for browsers (using `XMLHttpRequest`). These transports have a number of "types" built-in for handling the response body.

@@ -124,3 +117,3 @@ * **text** Handle response as a string (default)

* **jar** An instance of a cookie jar (`popsicle.jar()`) (default: `null`)
* **agent** Custom HTTP pooling agent (default: [infinity-agent](https://github.com/floatdrop/infinity-agent))
* **agent** Custom HTTP pooling agent
* **maxRedirects** Override the number of redirects allowed (default: `5`)

@@ -140,3 +133,3 @@ * **maxBufferSize** The maximum size of the buffered response body (default: `2000000`)

#### Short-hand Methods
### Short-hand Methods

@@ -153,8 +146,8 @@ Common methods have a short hand exported (created using `defaults({ method })`).

#### Extending with Defaults
### Default Instances
Create a new request function with defaults pre-populated. Handy for a common cookie jar or transport to be used.
Create a new Popsicle instance with defaults pre-populated. Handy for a common cookie jar or transport to be used.
```js
var cookiePopsicle = popsicle.defaults({
const cookiePopsicle = popsicle.defaults({
transport: popsicle.createTransport({

@@ -166,3 +159,3 @@ jar: popsicle.jar()

#### Automatically Stringify Request Body
### Automatically Stringify Request Body

@@ -183,8 +176,8 @@ Popsicle will automatically serialize the request body using the `stringify` plugin. If an object is supplied, it will automatically be stringified as JSON unless the `Content-Type` was set otherwise. If the `Content-Type` is `application/json`, `multipart/form-data` or `application/x-www-form-urlencoded`, it will be automatically serialized accordingly.

#### Multipart Request Bodies
### Multipart Request Bodies
You can manually create form data by calling `popsicle.form`. When you pass a form data instance as the body, it'll automatically set the correct `Content-Type` - complete with boundary.
You can manually create a `FormData` instance by calling `popsicle.form`. When you pass a form data instance as the body, it'll automatically set the correct `Content-Type` - complete with boundary.
```js
var form = popsicle.form({
const form = popsicle.form({
username: 'blakeembrey',

@@ -194,2 +187,4 @@ profileImage: fs.createReadStream('image.png')

form.append('x', 'y')
popsicle.post({

@@ -201,53 +196,8 @@ url: '/users',

#### Aborting Requests
### Cookie Jar (Node only)
All requests can be aborted before or during execution by calling `Request#abort`.
```js
var request = popsicle.get('http://example.com')
setTimeout(function () {
request.abort()
}, 100)
request.catch(function (err) {
console.log(err) //=> { message: 'Request aborted', code: 'EABORTED' }
})
```
#### Progress
The request object can be used to check progress at any time.
* **request.uploadedBytes** Current upload size in bytes
* **request.uploadLength** Total upload size in bytes
* **request.uploaded** Total uploaded as a percentage
* **request.downloadedBytes** Current download size in bytes
* **request.downloadLength** Total download size in bytes
* **request.downloaded** Total downloaded as a percentage
* **request.completed** Total uploaded and downloaded as a percentage
All percentage properties (`request.uploaded`, `request.downloaded`, `request.completed`) are a number between `0` and `1`. Aborting the request will emit a progress event, if the request had started.
```js
var request = popsicle.get('http://example.com')
request.uploaded //=> 0
request.downloaded //=> 0
request.progress(function () {
console.log(request) //=> { uploaded: 1, downloaded: 0, completed: 0.5, aborted: false }
})
request.then(function (response) {
console.log(request.downloaded) //=> 1
})
```
#### Cookie Jar (Node only)
You can create a reusable cookie jar instance for requests by calling `popsicle.jar`.
```js
var jar = popsicle.jar()
const jar = popsicle.jar()

@@ -263,6 +213,36 @@ popsicle.request({

### Handling Responses
### Request Class
Promises and node-style callbacks are supported.
Calling any of the request functions will return an instance of `Request`.
* **method** _(string)_ The request method.
* **timeout** _(number)_ Configured request timeout.
* **body** _(any)_ The request payload.
* **transport** _(object)_ The transportation layer.
* **events** _(object)_ A map of configured event listeners.
* **middleware** _(array)_ The list of configured middleware.
* **opened** _(boolean)_ A flag indicating the transport was started.
* **aborted** _(boolean)_ A flag indicating the request was aborted before finishing.
* **uploaded** _(number)_ The percentage of upload complete (between 0 and 1).
* **downloaded** _(number)_ The percentage of download complete (between 0 and 1).
* **uploadedBytes** (number)_ Number of bytes uploaded.
* **downloadedBytes** _(number)_ Number of bytes downloaded.
* **uploadLength** _(number)_ Known size of total upload bytes.
* **downloadLength** _(number)_ Known size of total download bytes.
* **error(message, code, original?)** Create a `PopsicleError` instance.
* **then(onFulfilled?, onRejected?)** Promise interface.
* **catch(onRejected)** Promise interface.
* **exec(cb)** Callback interface.
* **toOptions()** Return a new object representing the request options.
* **toJSON()** A JSON friendly representation of the request.
* **clone()** Return a new instance of `Request` from `toOptions()`.
* **use(middleware)** Append middleware to the current request.
* **on(event, fn)** Attach an event listener.
* **off(event, fn)** Detach an event listener.
* **once(event, fn)** Attach an event listener that automatically detaches after the first execution.
* **emit(event, ...args)** Emit an event (mostly internal use).
* **abort()** Abort the current request by emitting the `abort` event.
**P.S.** When cloning a request instance, the current middleware and events are copied. This allows event tricks like `abort()` to also abort cloned request instances (e.g. in the case where working with request retries, and aborting should still work on re-attempts).
#### Promises

@@ -309,19 +289,51 @@

### Response Objects
### Aborting
Every response will give a `Response` object on success. The object provides an intuitive interface for accessing common properties.
All requests can be aborted before or during execution by calling `Request#abort`.
* **status** The HTTP response status code
* **body** An object (if parsed using a plugin), string (if using concat) or stream that is the HTTP response body
* **headers** An object of lower-cased keys to header values
* **url** The final response URL (after redirects)
* **statusType()** Return an integer with the HTTP status type (E.g. `200 -> 2`)
* **get(key)** Retrieve a HTTP header using a case-insensitive key
* **name(key)** Retrieve the original HTTP header name using a case-insensitive key
* **type()** Return the response type (E.g. `application/json`)
```js
const request = popsicle.get('http://example.com')
### Error Handling
setTimeout(function () {
request.abort()
}, 100)
All response handling methods can return an error. Errors have a `popsicle` property set to the request object and a `code` string. The built-in codes are documented below, but custom errors can be created using `request.error(message, code, cause)`.
request.catch(function (err) {
console.log(err) //=> { message: 'Request aborted', code: 'EABORTED' }
})
```
#### Progress
The request object can be used to check progress at any time.
* **request.uploadedBytes** Current upload size in bytes
* **request.uploadLength** Total upload size in bytes
* **request.uploaded** Total uploaded as a percentage
* **request.downloadedBytes** Current download size in bytes
* **request.downloadLength** Total download size in bytes
* **request.downloaded** Total downloaded as a percentage
* **request.completed** Total uploaded and downloaded as a percentage
All percentage properties (`request.uploaded`, `request.downloaded`, `request.completed`) are a number between `0` and `1`. Aborting the request will emit a progress event, if the request had started.
```js
const request = popsicle.get('http://example.com')
request.uploaded //=> 0
request.downloaded //=> 0
request.on('progress', function () {
console.log(request) //=> { uploaded: 1, downloaded: 0, completed: 0.5, aborted: false }
})
request.then(function (response) {
console.log(request.downloaded) //=> 1
})
```
#### Errors
All response methods can return an error. Errors have a `popsicle` property set to the request object and a `code` string. The built-in codes are documented below, but custom errors can be created using `request.error(message, code, cause)`.
* **EABORT** Request has been aborted by user

@@ -339,5 +351,18 @@ * **EUNAVAILABLE** Unable to connect to the remote URL

### Response Class
Every response will give a `Response` instance on success. T
* **status** The HTTP response status code
* **body** The response body from the transport layer (usually text or a stream)
* **headers** An object of lower-cased keys to header values
* **url** The final response URL (after redirects)
* **statusType()** Return an integer with the HTTP status type (E.g. `200 -> 2`)
* **get(key)** Retrieve a HTTP header using a case-insensitive key
* **name(key)** Retrieve the original HTTP header name using a case-insensitive key
* **type()** Return the response type (E.g. `application/json`)
### Plugins
Plugins can be passed in as an array with the initial options (which overrides default plugins), or they can be used via `Request#use`.
Plugins can be set as an array with the initial options (which overrides default plugins), or they can be used via `Request#use`.

@@ -356,2 +381,4 @@ #### External Plugins

* [Retry](https://github.com/blakeembrey/popsicle-retry) - Retry a HTTP request on network error or server error
* [Rewrite](https://github.com/lbovet/popsicle-rewrite) - Rewrite request URLs dynamically
* [Cache](https://github.com/blakeembrey/popsicle-cache) - Enable caching for HTTP requests into a store (E.g. filesystem)

@@ -362,2 +389,3 @@ #### Helpful Utilities

* [`is-browser`](https://github.com/ForbesLindesay/is-browser) - Check if your in a browser environment (E.g. Browserify, Webpack)
* [`parse-link-header`](https://github.com/thlorenz/parse-link-header) - Handy for parsing HTTP link headers

@@ -385,5 +413,5 @@ #### Creating Plugins

**P.S.** The middleware array is exposed on `request.middleware`, which allows you to clone requests and omit middleware - for example, using `request.middleware.slice(request.middleware.indexOf(currentFn))`. This is useful, as the pre and post steps of previous middleware attach before `currentFn` is executed.
**P.S.** The middleware array is exposed on `request.middleware`, which allows you to clone requests and tweak middleware - for example, using `request.middleware.slice(request.middleware.indexOf(currentFn))`. This is useful, as the pre and post steps of previous middleware attach before `currentFn` is executed.
#### Transportation Layers
### Transportation Layers

@@ -400,2 +428,10 @@ Creating a custom transportation layer is just a matter creating an object with `open`, `abort` and `use` options set. The open method should set any request information required between called as `request._raw`. Abort must abort the current request instance, while `open` must **always** resolve to a promise. You can set `use` to an empty array if no plugins should be used by default. However, it's recommended you keep `use` set to the defaults, or as close as possible using your transport layer.

Note that for a brand new project you might need to add the definition for node via the following command:
```
typings install env~node --save --global
```
Make sure you add `typings/index.d.ts` to your TypeScript project (using `files` or `includes` in `tsconfig.json`) if it isn't already.
## Development

@@ -402,0 +438,0 @@

{
"resolution": {
"main": "lib/typings"
},
"devDependencies": {

@@ -13,8 +10,6 @@ "blue-tape": "registry:npm/blue-tape#0.2.0+20160623043621",

"dependencies": {
"arrify": "registry:npm/arrify#1.0.0+20160508201941",
"concat-stream": "registry:npm/concat-stream#1.0.0+20160211003958",
"form-data": "registry:npm/form-data#1.0.0+20160211003958",
"tough-cookie": "registry:npm/tough-cookie#2.2.0+20160428222547",
"xtend": "registry:npm/xtend#4.0.0+20160211003958"
"tough-cookie": "registry:npm/tough-cookie#2.2.0+20160428222547"
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc