diff --git a/.gitignore b/.gitignore index fe5397c..841623a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,6 @@ complexity coverage.html dist.js -dist/ node_modules npm-debug.log .DS_Store diff --git a/dist/jsonapi-client.js b/dist/jsonapi-client.js new file mode 100644 index 0000000..1a513f1 --- /dev/null +++ b/dist/jsonapi-client.js @@ -0,0 +1,3771 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o", err, payload); + if (err) { + // console.log(err.response.text); + if (err.status === 401) { + return callback(new Error("401 Unauthorized")); + } + + var response; + try { + response = JSON.parse(err.response.text); + } catch(e) { + console.error("Transport Error: " + JSON.stringify(err)); + return callback(Transport._defaultError(response)); + } + + if (!Array.isArray(response.errors)) { + console.error("Invalid Error payload!", response); + return callback(Transport._defaultError(response)); + } + + var realErrors = response.errors.map(function(apiError) { + var someError = new Error(JSON.stringify(apiError.detail)); + someError.name = apiError.title; + // $FlowFixMe: Technically "status" isn't a field on Error + someError.status = apiError.status; + // $FlowFixMe: Technically "code" isn't a field on Error + someError.code = apiError.code; + + return someError; + }); + + return callback(realErrors[0]); + } + + if (!payload.body) { + try { + payload.body = JSON.parse(payload.text); + } catch(e) { + return callback(Transport._defaultError(payload)); + } + } + + if (!payload.body) { + return callback(Transport._defaultError(payload)); + } + + return callback(null, payload.body, payload.body.data, payload.body.included); + }); +}; + +Transport.prototype.search = function(type, options, callback) { + var url = this._path + "/" + type; + this._action("get", url, options, callback); +}; + +Transport.prototype.find = function(type, id, options, callback) { + var url = this._path + "/" + type + "/" + id; + this._action("get", url, options, callback); +}; + +Transport.prototype.fetch = function(resource, relation, options, callback) { + var url = resource._getPathFor(relation); + this._action("get", url, options, callback); +}; + +Transport.prototype.create = function(resource, callback) { + var url = this._path + "/" + resource._getBase().type; + var postData = resource._getRaw(); + delete postData.id; + this._action("post", url, { + data: resource._getRaw() + }, callback); +}; + +Transport.prototype.update = function(resource, callback) { + var url = this._path + "/" + resource._getBase().type + "/" + resource._getBase().id; + this._action("patch", url, { + data: resource._getDelta() + }, callback); +}; + +Transport.prototype.delete = function(resource, callback) { + var url = this._path + "/" + resource._getBase().type + "/" + resource._getBase().id; + this._action("del", url, null, callback); +}; + +},{"qs":17,"superagent":21}],4:[function(require,module,exports){ +/* @flow weak */ +"use strict"; +module.exports = function createResourceCache(options) { + options = options || { }; + var resourceCache = {}; + + resourceCache._cacheDuration = options.cacheDuration || 5000; + + if (typeof module === undefined) { + resourceCache._cacheDuration = null; + } + resourceCache._cache = { }; + resourceCache._cacheList = [ ]; + + resourceCache.get = function(someResource) { + var key = someResource._getUidString(); + return resourceCache._cache[key]; + }; + + resourceCache.set = function(someResource) { + someResource._associateWithAll(resourceCache._cacheList); + + var key = someResource._getUidString(); + resourceCache._cache[key] = someResource; + resourceCache._cacheList.push(someResource); + + if (!resourceCache._cacheDuration) return; + + setTimeout(function() { + resourceCache.removeFromCache(someResource); + }, resourceCache._cacheDuration); + }; + + resourceCache.removeFromCache = function(someResource) { + var key = someResource._getUidString(); + resourceCache._cache[key] = undefined; + var i = resourceCache._cacheList.indexOf(someResource); + resourceCache._cacheList.splice(i, 1); + }; + + return resourceCache; +}; + +},{}],5:[function(require,module,exports){ +'use strict'; +/* eslint-disable no-unused-vars */ +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (e) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (Object.getOwnPropertySymbols) { + symbols = Object.getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],6:[function(require,module,exports){ +'use strict'; + +module.exports = require('./lib') + +},{"./lib":11}],7:[function(require,module,exports){ +'use strict'; + +var asap = require('asap/raw'); + +function noop() {} + +// States: +// +// 0 - pending +// 1 - fulfilled with _value +// 2 - rejected with _value +// 3 - adopted the state of another promise, _value +// +// once the state is no longer pending (0) it is immutable + +// All `_` prefixed properties will be reduced to `_{random number}` +// at build time to obfuscate them and discourage their use. +// We don't use symbols or Object.defineProperty to fully hide them +// because the performance isn't good enough. + + +// to avoid using try/catch inside critical functions, we +// extract them to here. +var LAST_ERROR = null; +var IS_ERROR = {}; +function getThen(obj) { + try { + return obj.then; + } catch (ex) { + LAST_ERROR = ex; + return IS_ERROR; + } +} + +function tryCallOne(fn, a) { + try { + return fn(a); + } catch (ex) { + LAST_ERROR = ex; + return IS_ERROR; + } +} +function tryCallTwo(fn, a, b) { + try { + fn(a, b); + } catch (ex) { + LAST_ERROR = ex; + return IS_ERROR; + } +} + +module.exports = Promise; + +function Promise(fn) { + if (typeof this !== 'object') { + throw new TypeError('Promises must be constructed via new'); + } + if (typeof fn !== 'function') { + throw new TypeError('not a function'); + } + this._45 = 0; + this._81 = 0; + this._65 = null; + this._54 = null; + if (fn === noop) return; + doResolve(fn, this); +} +Promise._10 = null; +Promise._97 = null; +Promise._61 = noop; + +Promise.prototype.then = function(onFulfilled, onRejected) { + if (this.constructor !== Promise) { + return safeThen(this, onFulfilled, onRejected); + } + var res = new Promise(noop); + handle(this, new Handler(onFulfilled, onRejected, res)); + return res; +}; + +function safeThen(self, onFulfilled, onRejected) { + return new self.constructor(function (resolve, reject) { + var res = new Promise(noop); + res.then(resolve, reject); + handle(self, new Handler(onFulfilled, onRejected, res)); + }); +}; +function handle(self, deferred) { + while (self._81 === 3) { + self = self._65; + } + if (Promise._10) { + Promise._10(self); + } + if (self._81 === 0) { + if (self._45 === 0) { + self._45 = 1; + self._54 = deferred; + return; + } + if (self._45 === 1) { + self._45 = 2; + self._54 = [self._54, deferred]; + return; + } + self._54.push(deferred); + return; + } + handleResolved(self, deferred); +} + +function handleResolved(self, deferred) { + asap(function() { + var cb = self._81 === 1 ? deferred.onFulfilled : deferred.onRejected; + if (cb === null) { + if (self._81 === 1) { + resolve(deferred.promise, self._65); + } else { + reject(deferred.promise, self._65); + } + return; + } + var ret = tryCallOne(cb, self._65); + if (ret === IS_ERROR) { + reject(deferred.promise, LAST_ERROR); + } else { + resolve(deferred.promise, ret); + } + }); +} +function resolve(self, newValue) { + // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure + if (newValue === self) { + return reject( + self, + new TypeError('A promise cannot be resolved with itself.') + ); + } + if ( + newValue && + (typeof newValue === 'object' || typeof newValue === 'function') + ) { + var then = getThen(newValue); + if (then === IS_ERROR) { + return reject(self, LAST_ERROR); + } + if ( + then === self.then && + newValue instanceof Promise + ) { + self._81 = 3; + self._65 = newValue; + finale(self); + return; + } else if (typeof then === 'function') { + doResolve(then.bind(newValue), self); + return; + } + } + self._81 = 1; + self._65 = newValue; + finale(self); +} + +function reject(self, newValue) { + self._81 = 2; + self._65 = newValue; + if (Promise._97) { + Promise._97(self, newValue); + } + finale(self); +} +function finale(self) { + if (self._45 === 1) { + handle(self, self._54); + self._54 = null; + } + if (self._45 === 2) { + for (var i = 0; i < self._54.length; i++) { + handle(self, self._54[i]); + } + self._54 = null; + } +} + +function Handler(onFulfilled, onRejected, promise){ + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.promise = promise; +} + +/** + * Take a potentially misbehaving resolver function and make sure + * onFulfilled and onRejected are only called once. + * + * Makes no guarantees about asynchrony. + */ +function doResolve(fn, promise) { + var done = false; + var res = tryCallTwo(fn, function (value) { + if (done) return; + done = true; + resolve(promise, value); + }, function (reason) { + if (done) return; + done = true; + reject(promise, reason); + }) + if (!done && res === IS_ERROR) { + done = true; + reject(promise, LAST_ERROR); + } +} + +},{"asap/raw":15}],8:[function(require,module,exports){ +'use strict'; + +var Promise = require('./core.js'); + +module.exports = Promise; +Promise.prototype.done = function (onFulfilled, onRejected) { + var self = arguments.length ? this.then.apply(this, arguments) : this; + self.then(null, function (err) { + setTimeout(function () { + throw err; + }, 0); + }); +}; + +},{"./core.js":7}],9:[function(require,module,exports){ +'use strict'; + +//This file contains the ES6 extensions to the core Promises/A+ API + +var Promise = require('./core.js'); + +module.exports = Promise; + +/* Static Functions */ + +var TRUE = valuePromise(true); +var FALSE = valuePromise(false); +var NULL = valuePromise(null); +var UNDEFINED = valuePromise(undefined); +var ZERO = valuePromise(0); +var EMPTYSTRING = valuePromise(''); + +function valuePromise(value) { + var p = new Promise(Promise._61); + p._81 = 1; + p._65 = value; + return p; +} +Promise.resolve = function (value) { + if (value instanceof Promise) return value; + + if (value === null) return NULL; + if (value === undefined) return UNDEFINED; + if (value === true) return TRUE; + if (value === false) return FALSE; + if (value === 0) return ZERO; + if (value === '') return EMPTYSTRING; + + if (typeof value === 'object' || typeof value === 'function') { + try { + var then = value.then; + if (typeof then === 'function') { + return new Promise(then.bind(value)); + } + } catch (ex) { + return new Promise(function (resolve, reject) { + reject(ex); + }); + } + } + return valuePromise(value); +}; + +Promise.all = function (arr) { + var args = Array.prototype.slice.call(arr); + + return new Promise(function (resolve, reject) { + if (args.length === 0) return resolve([]); + var remaining = args.length; + function res(i, val) { + if (val && (typeof val === 'object' || typeof val === 'function')) { + if (val instanceof Promise && val.then === Promise.prototype.then) { + while (val._81 === 3) { + val = val._65; + } + if (val._81 === 1) return res(i, val._65); + if (val._81 === 2) reject(val._65); + val.then(function (val) { + res(i, val); + }, reject); + return; + } else { + var then = val.then; + if (typeof then === 'function') { + var p = new Promise(then.bind(val)); + p.then(function (val) { + res(i, val); + }, reject); + return; + } + } + } + args[i] = val; + if (--remaining === 0) { + resolve(args); + } + } + for (var i = 0; i < args.length; i++) { + res(i, args[i]); + } + }); +}; + +Promise.reject = function (value) { + return new Promise(function (resolve, reject) { + reject(value); + }); +}; + +Promise.race = function (values) { + return new Promise(function (resolve, reject) { + values.forEach(function(value){ + Promise.resolve(value).then(resolve, reject); + }); + }); +}; + +/* Prototype Methods */ + +Promise.prototype['catch'] = function (onRejected) { + return this.then(null, onRejected); +}; + +},{"./core.js":7}],10:[function(require,module,exports){ +'use strict'; + +var Promise = require('./core.js'); + +module.exports = Promise; +Promise.prototype['finally'] = function (f) { + return this.then(function (value) { + return Promise.resolve(f()).then(function () { + return value; + }); + }, function (err) { + return Promise.resolve(f()).then(function () { + throw err; + }); + }); +}; + +},{"./core.js":7}],11:[function(require,module,exports){ +'use strict'; + +module.exports = require('./core.js'); +require('./done.js'); +require('./finally.js'); +require('./es6-extensions.js'); +require('./node-extensions.js'); +require('./synchronous.js'); + +},{"./core.js":7,"./done.js":8,"./es6-extensions.js":9,"./finally.js":10,"./node-extensions.js":12,"./synchronous.js":13}],12:[function(require,module,exports){ +'use strict'; + +// This file contains then/promise specific extensions that are only useful +// for node.js interop + +var Promise = require('./core.js'); +var asap = require('asap'); + +module.exports = Promise; + +/* Static Functions */ + +Promise.denodeify = function (fn, argumentCount) { + if ( + typeof argumentCount === 'number' && argumentCount !== Infinity + ) { + return denodeifyWithCount(fn, argumentCount); + } else { + return denodeifyWithoutCount(fn); + } +} + +var callbackFn = ( + 'function (err, res) {' + + 'if (err) { rj(err); } else { rs(res); }' + + '}' +); +function denodeifyWithCount(fn, argumentCount) { + var args = []; + for (var i = 0; i < argumentCount; i++) { + args.push('a' + i); + } + var body = [ + 'return function (' + args.join(',') + ') {', + 'var self = this;', + 'return new Promise(function (rs, rj) {', + 'var res = fn.call(', + ['self'].concat(args).concat([callbackFn]).join(','), + ');', + 'if (res &&', + '(typeof res === "object" || typeof res === "function") &&', + 'typeof res.then === "function"', + ') {rs(res);}', + '});', + '};' + ].join(''); + return Function(['Promise', 'fn'], body)(Promise, fn); +} +function denodeifyWithoutCount(fn) { + var fnLength = Math.max(fn.length - 1, 3); + var args = []; + for (var i = 0; i < fnLength; i++) { + args.push('a' + i); + } + var body = [ + 'return function (' + args.join(',') + ') {', + 'var self = this;', + 'var args;', + 'var argLength = arguments.length;', + 'if (arguments.length > ' + fnLength + ') {', + 'args = new Array(arguments.length + 1);', + 'for (var i = 0; i < arguments.length; i++) {', + 'args[i] = arguments[i];', + '}', + '}', + 'return new Promise(function (rs, rj) {', + 'var cb = ' + callbackFn + ';', + 'var res;', + 'switch (argLength) {', + args.concat(['extra']).map(function (_, index) { + return ( + 'case ' + (index) + ':' + + 'res = fn.call(' + ['self'].concat(args.slice(0, index)).concat('cb').join(',') + ');' + + 'break;' + ); + }).join(''), + 'default:', + 'args[argLength] = cb;', + 'res = fn.apply(self, args);', + '}', + + 'if (res &&', + '(typeof res === "object" || typeof res === "function") &&', + 'typeof res.then === "function"', + ') {rs(res);}', + '});', + '};' + ].join(''); + + return Function( + ['Promise', 'fn'], + body + )(Promise, fn); +} + +Promise.nodeify = function (fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + var callback = + typeof args[args.length - 1] === 'function' ? args.pop() : null; + var ctx = this; + try { + return fn.apply(this, arguments).nodeify(callback, ctx); + } catch (ex) { + if (callback === null || typeof callback == 'undefined') { + return new Promise(function (resolve, reject) { + reject(ex); + }); + } else { + asap(function () { + callback.call(ctx, ex); + }) + } + } + } +} + +Promise.prototype.nodeify = function (callback, ctx) { + if (typeof callback != 'function') return this; + + this.then(function (value) { + asap(function () { + callback.call(ctx, null, value); + }); + }, function (err) { + asap(function () { + callback.call(ctx, err); + }); + }); +} + +},{"./core.js":7,"asap":14}],13:[function(require,module,exports){ +'use strict'; + +var Promise = require('./core.js'); + +module.exports = Promise; +Promise.enableSynchronous = function () { + Promise.prototype.isPending = function() { + return this.getState() == 0; + }; + + Promise.prototype.isFulfilled = function() { + return this.getState() == 1; + }; + + Promise.prototype.isRejected = function() { + return this.getState() == 2; + }; + + Promise.prototype.getValue = function () { + if (this._81 === 3) { + return this._65.getValue(); + } + + if (!this.isFulfilled()) { + throw new Error('Cannot get a value of an unfulfilled promise.'); + } + + return this._65; + }; + + Promise.prototype.getReason = function () { + if (this._81 === 3) { + return this._65.getReason(); + } + + if (!this.isRejected()) { + throw new Error('Cannot get a rejection reason of a non-rejected promise.'); + } + + return this._65; + }; + + Promise.prototype.getState = function () { + if (this._81 === 3) { + return this._65.getState(); + } + if (this._81 === -1 || this._81 === -2) { + return 0; + } + + return this._81; + }; +}; + +Promise.disableSynchronous = function() { + Promise.prototype.isPending = undefined; + Promise.prototype.isFulfilled = undefined; + Promise.prototype.isRejected = undefined; + Promise.prototype.getValue = undefined; + Promise.prototype.getReason = undefined; + Promise.prototype.getState = undefined; +}; + +},{"./core.js":7}],14:[function(require,module,exports){ +"use strict"; + +// rawAsap provides everything we need except exception management. +var rawAsap = require("./raw"); +// RawTasks are recycled to reduce GC churn. +var freeTasks = []; +// We queue errors to ensure they are thrown in right order (FIFO). +// Array-as-queue is good enough here, since we are just dealing with exceptions. +var pendingErrors = []; +var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError); + +function throwFirstError() { + if (pendingErrors.length) { + throw pendingErrors.shift(); + } +} + +/** + * Calls a task as soon as possible after returning, in its own event, with priority + * over other events like animation, reflow, and repaint. An error thrown from an + * event will not interrupt, nor even substantially slow down the processing of + * other events, but will be rather postponed to a lower priority event. + * @param {{call}} task A callable object, typically a function that takes no + * arguments. + */ +module.exports = asap; +function asap(task) { + var rawTask; + if (freeTasks.length) { + rawTask = freeTasks.pop(); + } else { + rawTask = new RawTask(); + } + rawTask.task = task; + rawAsap(rawTask); +} + +// We wrap tasks with recyclable task objects. A task object implements +// `call`, just like a function. +function RawTask() { + this.task = null; +} + +// The sole purpose of wrapping the task is to catch the exception and recycle +// the task object after its single use. +RawTask.prototype.call = function () { + try { + this.task.call(); + } catch (error) { + if (asap.onerror) { + // This hook exists purely for testing purposes. + // Its name will be periodically randomized to break any code that + // depends on its existence. + asap.onerror(error); + } else { + // In a web browser, exceptions are not fatal. However, to avoid + // slowing down the queue of pending tasks, we rethrow the error in a + // lower priority turn. + pendingErrors.push(error); + requestErrorThrow(); + } + } finally { + this.task = null; + freeTasks[freeTasks.length] = this; + } +}; + +},{"./raw":15}],15:[function(require,module,exports){ +(function (global){ +"use strict"; + +// Use the fastest means possible to execute a task in its own turn, with +// priority over other events including IO, animation, reflow, and redraw +// events in browsers. +// +// An exception thrown by a task will permanently interrupt the processing of +// subsequent tasks. The higher level `asap` function ensures that if an +// exception is thrown by a task, that the task queue will continue flushing as +// soon as possible, but if you use `rawAsap` directly, you are responsible to +// either ensure that no exceptions are thrown from your task, or to manually +// call `rawAsap.requestFlush` if an exception is thrown. +module.exports = rawAsap; +function rawAsap(task) { + if (!queue.length) { + requestFlush(); + flushing = true; + } + // Equivalent to push, but avoids a function call. + queue[queue.length] = task; +} + +var queue = []; +// Once a flush has been requested, no further calls to `requestFlush` are +// necessary until the next `flush` completes. +var flushing = false; +// `requestFlush` is an implementation-specific method that attempts to kick +// off a `flush` event as quickly as possible. `flush` will attempt to exhaust +// the event queue before yielding to the browser's own event loop. +var requestFlush; +// The position of the next task to execute in the task queue. This is +// preserved between calls to `flush` so that it can be resumed if +// a task throws an exception. +var index = 0; +// If a task schedules additional tasks recursively, the task queue can grow +// unbounded. To prevent memory exhaustion, the task queue will periodically +// truncate already-completed tasks. +var capacity = 1024; + +// The flush function processes all tasks that have been scheduled with +// `rawAsap` unless and until one of those tasks throws an exception. +// If a task throws an exception, `flush` ensures that its state will remain +// consistent and will resume where it left off when called again. +// However, `flush` does not make any arrangements to be called again if an +// exception is thrown. +function flush() { + while (index < queue.length) { + var currentIndex = index; + // Advance the index before calling the task. This ensures that we will + // begin flushing on the next task the task throws an error. + index = index + 1; + queue[currentIndex].call(); + // Prevent leaking memory for long chains of recursive calls to `asap`. + // If we call `asap` within tasks scheduled by `asap`, the queue will + // grow, but to avoid an O(n) walk for every task we execute, we don't + // shift tasks off the queue after they have been executed. + // Instead, we periodically shift 1024 tasks off the queue. + if (index > capacity) { + // Manually shift all values starting at the index back to the + // beginning of the queue. + for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { + queue[scan] = queue[scan + index]; + } + queue.length -= index; + index = 0; + } + } + queue.length = 0; + index = 0; + flushing = false; +} + +// `requestFlush` is implemented using a strategy based on data collected from +// every available SauceLabs Selenium web driver worker at time of writing. +// https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593 + +// Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that +// have WebKitMutationObserver but not un-prefixed MutationObserver. +// Must use `global` or `self` instead of `window` to work in both frames and web +// workers. `global` is a provision of Browserify, Mr, Mrs, or Mop. + +/* globals self */ +var scope = typeof global !== "undefined" ? global : self; +var BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver; + +// MutationObservers are desirable because they have high priority and work +// reliably everywhere they are implemented. +// They are implemented in all modern browsers. +// +// - Android 4-4.3 +// - Chrome 26-34 +// - Firefox 14-29 +// - Internet Explorer 11 +// - iPad Safari 6-7.1 +// - iPhone Safari 7-7.1 +// - Safari 6-7 +if (typeof BrowserMutationObserver === "function") { + requestFlush = makeRequestCallFromMutationObserver(flush); + +// MessageChannels are desirable because they give direct access to the HTML +// task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera +// 11-12, and in web workers in many engines. +// Although message channels yield to any queued rendering and IO tasks, they +// would be better than imposing the 4ms delay of timers. +// However, they do not work reliably in Internet Explorer or Safari. + +// Internet Explorer 10 is the only browser that has setImmediate but does +// not have MutationObservers. +// Although setImmediate yields to the browser's renderer, it would be +// preferrable to falling back to setTimeout since it does not have +// the minimum 4ms penalty. +// Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and +// Desktop to a lesser extent) that renders both setImmediate and +// MessageChannel useless for the purposes of ASAP. +// https://github.com/kriskowal/q/issues/396 + +// Timers are implemented universally. +// We fall back to timers in workers in most engines, and in foreground +// contexts in the following browsers. +// However, note that even this simple case requires nuances to operate in a +// broad spectrum of browsers. +// +// - Firefox 3-13 +// - Internet Explorer 6-9 +// - iPad Safari 4.3 +// - Lynx 2.8.7 +} else { + requestFlush = makeRequestCallFromTimer(flush); +} + +// `requestFlush` requests that the high priority event queue be flushed as +// soon as possible. +// This is useful to prevent an error thrown in a task from stalling the event +// queue if the exception handled by Node.js’s +// `process.on("uncaughtException")` or by a domain. +rawAsap.requestFlush = requestFlush; + +// To request a high priority event, we induce a mutation observer by toggling +// the text of a text node between "1" and "-1". +function makeRequestCallFromMutationObserver(callback) { + var toggle = 1; + var observer = new BrowserMutationObserver(callback); + var node = document.createTextNode(""); + observer.observe(node, {characterData: true}); + return function requestCall() { + toggle = -toggle; + node.data = toggle; + }; +} + +// The message channel technique was discovered by Malte Ubl and was the +// original foundation for this library. +// http://www.nonblocking.io/2011/06/windownexttick.html + +// Safari 6.0.5 (at least) intermittently fails to create message ports on a +// page's first load. Thankfully, this version of Safari supports +// MutationObservers, so we don't need to fall back in that case. + +// function makeRequestCallFromMessageChannel(callback) { +// var channel = new MessageChannel(); +// channel.port1.onmessage = callback; +// return function requestCall() { +// channel.port2.postMessage(0); +// }; +// } + +// For reasons explained above, we are also unable to use `setImmediate` +// under any circumstances. +// Even if we were, there is another bug in Internet Explorer 10. +// It is not sufficient to assign `setImmediate` to `requestFlush` because +// `setImmediate` must be called *by name* and therefore must be wrapped in a +// closure. +// Never forget. + +// function makeRequestCallFromSetImmediate(callback) { +// return function requestCall() { +// setImmediate(callback); +// }; +// } + +// Safari 6.0 has a problem where timers will get lost while the user is +// scrolling. This problem does not impact ASAP because Safari 6.0 supports +// mutation observers, so that implementation is used instead. +// However, if we ever elect to use timers in Safari, the prevalent work-around +// is to add a scroll event listener that calls for a flush. + +// `setTimeout` does not call the passed callback if the delay is less than +// approximately 7 in web workers in Firefox 8 through 18, and sometimes not +// even then. + +function makeRequestCallFromTimer(callback) { + return function requestCall() { + // We dispatch a timeout with a specified delay of 0 for engines that + // can reliably accommodate that request. This will usually be snapped + // to a 4 milisecond delay, but once we're flushing, there's no delay + // between events. + var timeoutHandle = setTimeout(handleTimer, 0); + // However, since this timer gets frequently dropped in Firefox + // workers, we enlist an interval handle that will try to fire + // an event 20 times per second until it succeeds. + var intervalHandle = setInterval(handleTimer, 50); + + function handleTimer() { + // Whichever timer succeeds will cancel both timers and + // execute the callback. + clearTimeout(timeoutHandle); + clearInterval(intervalHandle); + callback(); + } + }; +} + +// This is for `asap.js` only. +// Its name will be periodically randomized to break any code that depends on +// its existence. +rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer; + +// ASAP was originally a nextTick shim included in Q. This was factored out +// into this ASAP package. It was later adapted to RSVP which made further +// amendments. These decisions, particularly to marginalize MessageChannel and +// to capture the MutationObserver implementation in a closure, were integrated +// back into ASAP proper. +// https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],16:[function(require,module,exports){ +'use strict'; + +var replace = String.prototype.replace; +var percentTwenties = /%20/g; + +module.exports = { + 'default': 'RFC3986', + formatters: { + RFC1738: function (value) { + return replace.call(value, percentTwenties, '+'); + }, + RFC3986: function (value) { + return value; + } + }, + RFC1738: 'RFC1738', + RFC3986: 'RFC3986' +}; + +},{}],17:[function(require,module,exports){ +'use strict'; + +var stringify = require('./stringify'); +var parse = require('./parse'); +var formats = require('./formats'); + +module.exports = { + formats: formats, + parse: parse, + stringify: stringify +}; + +},{"./formats":16,"./parse":18,"./stringify":19}],18:[function(require,module,exports){ +'use strict'; + +var utils = require('./utils'); + +var has = Object.prototype.hasOwnProperty; + +var defaults = { + allowDots: false, + allowPrototypes: false, + arrayLimit: 20, + decoder: utils.decode, + delimiter: '&', + depth: 5, + parameterLimit: 1000, + plainObjects: false, + strictNullHandling: false +}; + +var parseValues = function parseQueryStringValues(str, options) { + var obj = {}; + var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); + + for (var i = 0; i < parts.length; ++i) { + var part = parts[i]; + var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; + + var key, val; + if (pos === -1) { + key = options.decoder(part); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos)); + val = options.decoder(part.slice(pos + 1)); + } + if (has.call(obj, key)) { + obj[key] = [].concat(obj[key]).concat(val); + } else { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function parseObjectRecursive(chain, val, options) { + if (!chain.length) { + return val; + } + + var root = chain.shift(); + + var obj; + if (root === '[]') { + obj = []; + obj = obj.concat(parseObject(chain, val, options)); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if ( + !isNaN(index) && + root !== cleanRoot && + String(index) === cleanRoot && + index >= 0 && + (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = parseObject(chain, val, options); + } else { + obj[cleanRoot] = parseObject(chain, val, options); + } + } + + return obj; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys + // that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options); +}; + +module.exports = function (str, opts) { + var options = opts || {}; + + if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; + options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; + options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; + options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options); + obj = utils.merge(obj, newObj, options); + } + + return utils.compact(obj); +}; + +},{"./utils":20}],19:[function(require,module,exports){ +'use strict'; + +var utils = require('./utils'); +var formats = require('./formats'); + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { // eslint-disable-line func-name-matching + return prefix + '[]'; + }, + indices: function indices(prefix, key) { // eslint-disable-line func-name-matching + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { // eslint-disable-line func-name-matching + return prefix; + } +}; + +var toISO = Date.prototype.toISOString; + +var defaults = { + delimiter: '&', + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var stringify = function stringify( // eslint-disable-line func-name-matching + object, + prefix, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly +) { + var obj = object; + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix) : prefix; + } + + obj = ''; + } + + if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix); + return [formatter(keyValue) + '=' + formatter(encoder(obj))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (Array.isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (skipNulls && obj[key] === null) { + continue; + } + + if (Array.isArray(obj)) { + values = values.concat(stringify( + obj[key], + generateArrayPrefix(prefix, key), + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly + )); + } else { + values = values.concat(stringify( + obj[key], + prefix + (allowDots ? '.' + key : '[' + key + ']'), + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly + )); + } + } + + return values; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = opts || {}; + + if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; + var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; + var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; + var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder; + var sort = typeof options.sort === 'function' ? options.sort : null; + var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; + var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; + var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly; + if (typeof options.format === 'undefined') { + options.format = formats.default; + } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { + throw new TypeError('Unknown format option provided.'); + } + var formatter = formats.formatters[options.format]; + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (Array.isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var arrayFormat; + if (options.arrayFormat in arrayPrefixGenerators) { + arrayFormat = options.arrayFormat; + } else if ('indices' in options) { + arrayFormat = options.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (sort) { + objKeys.sort(sort); + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (skipNulls && obj[key] === null) { + continue; + } + + keys = keys.concat(stringify( + obj[key], + key, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encode ? encoder : null, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly + )); + } + + return keys.join(delimiter); +}; + +},{"./formats":16,"./utils":20}],20:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +exports.arrayToObject = function (source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +exports.merge = function (target, source, options) { + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } else if (typeof target === 'object') { + if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (Array.isArray(target) && !Array.isArray(source)) { + mergeTarget = exports.arrayToObject(target, options); + } + + if (Array.isArray(target) && Array.isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + if (target[i] && typeof target[i] === 'object') { + target[i] = exports.merge(target[i], item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (Object.prototype.hasOwnProperty.call(acc, key)) { + acc[key] = exports.merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +exports.decode = function (str) { + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + +exports.encode = function (str) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = typeof str === 'string' ? str : String(str); + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D || // - + c === 0x2E || // . + c === 0x5F || // _ + c === 0x7E || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5A) || // a-z + (c >= 0x61 && c <= 0x7A) // A-Z + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; // eslint-disable-line max-len + } + + return out; +}; + +exports.compact = function (obj, references) { + if (typeof obj !== 'object' || obj === null) { + return obj; + } + + var refs = references || []; + var lookup = refs.indexOf(obj); + if (lookup !== -1) { + return refs[lookup]; + } + + refs.push(obj); + + if (Array.isArray(obj)) { + var compacted = []; + + for (var i = 0; i < obj.length; ++i) { + if (obj[i] && typeof obj[i] === 'object') { + compacted.push(exports.compact(obj[i], refs)); + } else if (typeof obj[i] !== 'undefined') { + compacted.push(obj[i]); + } + } + + return compacted; + } + + var keys = Object.keys(obj); + keys.forEach(function (key) { + obj[key] = exports.compact(obj[key], refs); + }); + + return obj; +}; + +exports.isRegExp = function (obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +exports.isBuffer = function (obj) { + if (obj === null || typeof obj === 'undefined') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +},{}],21:[function(require,module,exports){ +/** + * Module dependencies. + */ + +var Emitter = require('emitter'); +var reduce = require('reduce'); +var requestBase = require('./request-base'); +var isObject = require('./is-object'); + +/** + * Root reference for iframes. + */ + +var root; +if (typeof window !== 'undefined') { // Browser window + root = window; +} else if (typeof self !== 'undefined') { // Web Worker + root = self; +} else { // Other environments + root = this; +} + +/** + * Noop. + */ + +function noop(){}; + +/** + * Expose `request`. + */ + +var request = module.exports = require('./request').bind(null, Request); + +/** + * Determine XHR. + */ + +request.getXHR = function () { + if (root.XMLHttpRequest + && (!root.location || 'file:' != root.location.protocol + || !root.ActiveXObject)) { + return new XMLHttpRequest; + } else { + try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} + try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} + } + return false; +}; + +/** + * Removes leading and trailing whitespace, added to support IE. + * + * @param {String} s + * @return {String} + * @api private + */ + +var trim = ''.trim + ? function(s) { return s.trim(); } + : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; + +/** + * Serialize the given `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +function serialize(obj) { + if (!isObject(obj)) return obj; + var pairs = []; + for (var key in obj) { + if (null != obj[key]) { + pushEncodedKeyValuePair(pairs, key, obj[key]); + } + } + return pairs.join('&'); +} + +/** + * Helps 'serialize' with serializing arrays. + * Mutates the pairs array. + * + * @param {Array} pairs + * @param {String} key + * @param {Mixed} val + */ + +function pushEncodedKeyValuePair(pairs, key, val) { + if (Array.isArray(val)) { + return val.forEach(function(v) { + pushEncodedKeyValuePair(pairs, key, v); + }); + } else if (isObject(val)) { + for(var subkey in val) { + pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]); + } + return; + } + pairs.push(encodeURIComponent(key) + + '=' + encodeURIComponent(val)); +} + +/** + * Expose serialization method. + */ + + request.serializeObject = serialize; + + /** + * Parse the given x-www-form-urlencoded `str`. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseString(str) { + var obj = {}; + var pairs = str.split('&'); + var pair; + var pos; + + for (var i = 0, len = pairs.length; i < len; ++i) { + pair = pairs[i]; + pos = pair.indexOf('='); + if (pos == -1) { + obj[decodeURIComponent(pair)] = ''; + } else { + obj[decodeURIComponent(pair.slice(0, pos))] = + decodeURIComponent(pair.slice(pos + 1)); + } + } + + return obj; +} + +/** + * Expose parser. + */ + +request.parseString = parseString; + +/** + * Default MIME type map. + * + * superagent.types.xml = 'application/xml'; + * + */ + +request.types = { + html: 'text/html', + json: 'application/json', + xml: 'application/xml', + urlencoded: 'application/x-www-form-urlencoded', + 'form': 'application/x-www-form-urlencoded', + 'form-data': 'application/x-www-form-urlencoded' +}; + +/** + * Default serialization map. + * + * superagent.serialize['application/xml'] = function(obj){ + * return 'generated xml here'; + * }; + * + */ + + request.serialize = { + 'application/x-www-form-urlencoded': serialize, + 'application/json': JSON.stringify + }; + + /** + * Default parsers. + * + * superagent.parse['application/xml'] = function(str){ + * return { object parsed from str }; + * }; + * + */ + +request.parse = { + 'application/x-www-form-urlencoded': parseString, + 'application/json': JSON.parse +}; + +/** + * Parse the given header `str` into + * an object containing the mapped fields. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function parseHeader(str) { + var lines = str.split(/\r?\n/); + var fields = {}; + var index; + var line; + var field; + var val; + + lines.pop(); // trailing CRLF + + for (var i = 0, len = lines.length; i < len; ++i) { + line = lines[i]; + index = line.indexOf(':'); + field = line.slice(0, index).toLowerCase(); + val = trim(line.slice(index + 1)); + fields[field] = val; + } + + return fields; +} + +/** + * Check if `mime` is json or has +json structured syntax suffix. + * + * @param {String} mime + * @return {Boolean} + * @api private + */ + +function isJSON(mime) { + return /[\/+]json\b/.test(mime); +} + +/** + * Return the mime type for the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +function type(str){ + return str.split(/ *; */).shift(); +}; + +/** + * Return header field parameters. + * + * @param {String} str + * @return {Object} + * @api private + */ + +function params(str){ + return reduce(str.split(/ *; */), function(obj, str){ + var parts = str.split(/ *= */) + , key = parts.shift() + , val = parts.shift(); + + if (key && val) obj[key] = val; + return obj; + }, {}); +}; + +/** + * Initialize a new `Response` with the given `xhr`. + * + * - set flags (.ok, .error, etc) + * - parse header + * + * Examples: + * + * Aliasing `superagent` as `request` is nice: + * + * request = superagent; + * + * We can use the promise-like API, or pass callbacks: + * + * request.get('/').end(function(res){}); + * request.get('/', function(res){}); + * + * Sending data can be chained: + * + * request + * .post('/user') + * .send({ name: 'tj' }) + * .end(function(res){}); + * + * Or passed to `.send()`: + * + * request + * .post('/user') + * .send({ name: 'tj' }, function(res){}); + * + * Or passed to `.post()`: + * + * request + * .post('/user', { name: 'tj' }) + * .end(function(res){}); + * + * Or further reduced to a single call for simple cases: + * + * request + * .post('/user', { name: 'tj' }, function(res){}); + * + * @param {XMLHTTPRequest} xhr + * @param {Object} options + * @api private + */ + +function Response(req, options) { + options = options || {}; + this.req = req; + this.xhr = this.req.xhr; + // responseText is accessible only if responseType is '' or 'text' and on older browsers + this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') + ? this.xhr.responseText + : null; + this.statusText = this.req.xhr.statusText; + this._setStatusProperties(this.xhr.status); + this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); + // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but + // getResponseHeader still works. so we get content-type even if getting + // other headers fails. + this.header['content-type'] = this.xhr.getResponseHeader('content-type'); + this._setHeaderProperties(this.header); + this.body = this.req.method != 'HEAD' + ? this._parseBody(this.text ? this.text : this.xhr.response) + : null; +} + +/** + * Get case-insensitive `field` value. + * + * @param {String} field + * @return {String} + * @api public + */ + +Response.prototype.get = function(field){ + return this.header[field.toLowerCase()]; +}; + +/** + * Set header related properties: + * + * - `.type` the content type without params + * + * A response of "Content-Type: text/plain; charset=utf-8" + * will provide you with a `.type` of "text/plain". + * + * @param {Object} header + * @api private + */ + +Response.prototype._setHeaderProperties = function(header){ + // content-type + var ct = this.header['content-type'] || ''; + this.type = type(ct); + + // params + var obj = params(ct); + for (var key in obj) this[key] = obj[key]; +}; + +/** + * Parse the given body `str`. + * + * Used for auto-parsing of bodies. Parsers + * are defined on the `superagent.parse` object. + * + * @param {String} str + * @return {Mixed} + * @api private + */ + +Response.prototype._parseBody = function(str){ + var parse = request.parse[this.type]; + if (!parse && isJSON(this.type)) { + parse = request.parse['application/json']; + } + return parse && str && (str.length || str instanceof Object) + ? parse(str) + : null; +}; + +/** + * Set flags such as `.ok` based on `status`. + * + * For example a 2xx response will give you a `.ok` of __true__ + * whereas 5xx will be __false__ and `.error` will be __true__. The + * `.clientError` and `.serverError` are also available to be more + * specific, and `.statusType` is the class of error ranging from 1..5 + * sometimes useful for mapping respond colors etc. + * + * "sugar" properties are also defined for common cases. Currently providing: + * + * - .noContent + * - .badRequest + * - .unauthorized + * - .notAcceptable + * - .notFound + * + * @param {Number} status + * @api private + */ + +Response.prototype._setStatusProperties = function(status){ + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + if (status === 1223) { + status = 204; + } + + var type = status / 100 | 0; + + // status / class + this.status = this.statusCode = status; + this.statusType = type; + + // basics + this.info = 1 == type; + this.ok = 2 == type; + this.clientError = 4 == type; + this.serverError = 5 == type; + this.error = (4 == type || 5 == type) + ? this.toError() + : false; + + // sugar + this.accepted = 202 == status; + this.noContent = 204 == status; + this.badRequest = 400 == status; + this.unauthorized = 401 == status; + this.notAcceptable = 406 == status; + this.notFound = 404 == status; + this.forbidden = 403 == status; +}; + +/** + * Return an `Error` representative of this response. + * + * @return {Error} + * @api public + */ + +Response.prototype.toError = function(){ + var req = this.req; + var method = req.method; + var url = req.url; + + var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; + var err = new Error(msg); + err.status = this.status; + err.method = method; + err.url = url; + + return err; +}; + +/** + * Expose `Response`. + */ + +request.Response = Response; + +/** + * Initialize a new `Request` with the given `method` and `url`. + * + * @param {String} method + * @param {String} url + * @api public + */ + +function Request(method, url) { + var self = this; + this._query = this._query || []; + this.method = method; + this.url = url; + this.header = {}; // preserves header name case + this._header = {}; // coerces header names to lowercase + this.on('end', function(){ + var err = null; + var res = null; + + try { + res = new Response(self); + } catch(e) { + err = new Error('Parser is unable to parse the response'); + err.parse = true; + err.original = e; + // issue #675: return the raw response if the response parsing fails + err.rawResponse = self.xhr && self.xhr.responseText ? self.xhr.responseText : null; + // issue #876: return the http status code if the response parsing fails + err.statusCode = self.xhr && self.xhr.status ? self.xhr.status : null; + return self.callback(err); + } + + self.emit('response', res); + + if (err) { + return self.callback(err, res); + } + + try { + if (res.status >= 200 && res.status < 300) { + return self.callback(err, res); + } + + var new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); + new_err.original = err; + new_err.response = res; + new_err.status = res.status; + + self.callback(new_err, res); + } catch(e) { + self.callback(e); // #985 touching res may cause INVALID_STATE_ERR on old Android + } + }); +} + +/** + * Mixin `Emitter` and `requestBase`. + */ + +Emitter(Request.prototype); +for (var key in requestBase) { + Request.prototype[key] = requestBase[key]; +} + +/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */ + +Request.prototype.type = function(type){ + this.set('Content-Type', request.types[type] || type); + return this; +}; + +/** + * Set responseType to `val`. Presently valid responseTypes are 'blob' and + * 'arraybuffer'. + * + * Examples: + * + * req.get('/') + * .responseType('blob') + * .end(callback); + * + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +Request.prototype.responseType = function(val){ + this._responseType = val; + return this; +}; + +/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */ + +Request.prototype.accept = function(type){ + this.set('Accept', request.types[type] || type); + return this; +}; + +/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} pass + * @param {Object} options with 'type' property 'auto' or 'basic' (default 'basic') + * @return {Request} for chaining + * @api public + */ + +Request.prototype.auth = function(user, pass, options){ + if (!options) { + options = { + type: 'basic' + } + } + + switch (options.type) { + case 'basic': + var str = btoa(user + ':' + pass); + this.set('Authorization', 'Basic ' + str); + break; + + case 'auto': + this.username = user; + this.password = pass; + break; + } + return this; +}; + +/** +* Add query-string `val`. +* +* Examples: +* +* request.get('/shoes') +* .query('size=10') +* .query({ color: 'blue' }) +* +* @param {Object|String} val +* @return {Request} for chaining +* @api public +*/ + +Request.prototype.query = function(val){ + if ('string' != typeof val) val = serialize(val); + if (val) this._query.push(val); + return this; +}; + +/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `filename`. + * + * ``` js + * request.post('/upload') + * .attach('content', new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String} filename + * @return {Request} for chaining + * @api public + */ + +Request.prototype.attach = function(field, file, filename){ + this._getFormData().append(field, file, filename || file.name); + return this; +}; + +Request.prototype._getFormData = function(){ + if (!this._formData) { + this._formData = new root.FormData(); + } + return this._formData; +}; + +/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */ + +Request.prototype.callback = function(err, res){ + var fn = this._callback; + this.clearTimeout(); + fn(err, res); +}; + +/** + * Invoke callback with x-domain error. + * + * @api private + */ + +Request.prototype.crossDomainError = function(){ + var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); + err.crossDomain = true; + + err.status = this.status; + err.method = this.method; + err.url = this.url; + + this.callback(err); +}; + +/** + * Invoke callback with timeout error. + * + * @api private + */ + +Request.prototype._timeoutError = function(){ + var timeout = this._timeout; + var err = new Error('timeout of ' + timeout + 'ms exceeded'); + err.timeout = timeout; + this.callback(err); +}; + +/** + * Compose querystring to append to req.url + * + * @api private + */ + +Request.prototype._appendQueryString = function(){ + var query = this._query.join('&'); + if (query) { + this.url += ~this.url.indexOf('?') + ? '&' + query + : '?' + query; + } +}; + +/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */ + +Request.prototype.end = function(fn){ + var self = this; + var xhr = this.xhr = request.getXHR(); + var timeout = this._timeout; + var data = this._formData || this._data; + + // store callback + this._callback = fn || noop; + + // state change + xhr.onreadystatechange = function(){ + if (4 != xhr.readyState) return; + + // In IE9, reads to any property (e.g. status) off of an aborted XHR will + // result in the error "Could not complete the operation due to error c00c023f" + var status; + try { status = xhr.status } catch(e) { status = 0; } + + if (0 == status) { + if (self.timedout) return self._timeoutError(); + if (self._aborted) return; + return self.crossDomainError(); + } + self.emit('end'); + }; + + // progress + var handleProgress = function(e){ + if (e.total > 0) { + e.percent = e.loaded / e.total * 100; + } + e.direction = 'download'; + self.emit('progress', e); + }; + if (this.hasListeners('progress')) { + xhr.onprogress = handleProgress; + } + try { + if (xhr.upload && this.hasListeners('progress')) { + xhr.upload.onprogress = handleProgress; + } + } catch(e) { + // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. + // Reported here: + // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context + } + + // timeout + if (timeout && !this._timer) { + this._timer = setTimeout(function(){ + self.timedout = true; + self.abort(); + }, timeout); + } + + // querystring + this._appendQueryString(); + + // initiate request + if (this.username && this.password) { + xhr.open(this.method, this.url, true, this.username, this.password); + } else { + xhr.open(this.method, this.url, true); + } + + // CORS + if (this._withCredentials) xhr.withCredentials = true; + + // body + if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) { + // serialize stuff + var contentType = this._header['content-type']; + var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; + if (!serialize && isJSON(contentType)) serialize = request.serialize['application/json']; + if (serialize) data = serialize(data); + } + + // set header fields + for (var field in this.header) { + if (null == this.header[field]) continue; + xhr.setRequestHeader(field, this.header[field]); + } + + if (this._responseType) { + xhr.responseType = this._responseType; + } + + // send stuff + this.emit('request', this); + + // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) + // We need null here if data is undefined + xhr.send(typeof data !== 'undefined' ? data : null); + return this; +}; + + +/** + * Expose `Request`. + */ + +request.Request = Request; + +/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ + +request.get = function(url, data, fn){ + var req = request('GET', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.query(data); + if (fn) req.end(fn); + return req; +}; + +/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ + +request.head = function(url, data, fn){ + var req = request('HEAD', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * OPTIONS query to `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ + +request.options = function(url, data, fn){ + var req = request('OPTIONS', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * DELETE `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Function} fn + * @return {Request} + * @api public + */ + +function del(url, fn){ + var req = request('DELETE', url); + if (fn) req.end(fn); + return req; +}; + +request['del'] = del; +request['delete'] = del; + +/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} data + * @param {Function} fn + * @return {Request} + * @api public + */ + +request.patch = function(url, data, fn){ + var req = request('PATCH', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} data + * @param {Function} fn + * @return {Request} + * @api public + */ + +request.post = function(url, data, fn){ + var req = request('POST', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */ + +request.put = function(url, data, fn){ + var req = request('PUT', url); + if ('function' == typeof data) fn = data, data = null; + if (data) req.send(data); + if (fn) req.end(fn); + return req; +}; + +},{"./is-object":22,"./request":24,"./request-base":23,"emitter":25,"reduce":26}],22:[function(require,module,exports){ +/** + * Check if `obj` is an object. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ + +function isObject(obj) { + return null !== obj && 'object' === typeof obj; +} + +module.exports = isObject; + +},{}],23:[function(require,module,exports){ +/** + * Module of mixed-in functions shared between node and client code + */ +var isObject = require('./is-object'); + +/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */ + +exports.clearTimeout = function _clearTimeout(){ + this._timeout = 0; + clearTimeout(this._timer); + return this; +}; + +/** + * Override default response body parser + * + * This function will be called to convert incoming data into request.body + * + * @param {Function} + * @api public + */ + +exports.parse = function parse(fn){ + this._parser = fn; + return this; +}; + +/** + * Override default request body serializer + * + * This function will be called to convert data set via .send or .attach into payload to send + * + * @param {Function} + * @api public + */ + +exports.serialize = function serialize(fn){ + this._serializer = fn; + return this; +}; + +/** + * Set timeout to `ms`. + * + * @param {Number} ms + * @return {Request} for chaining + * @api public + */ + +exports.timeout = function timeout(ms){ + this._timeout = ms; + return this; +}; + +/** + * Promise support + * + * @param {Function} resolve + * @param {Function} reject + * @return {Request} + */ + +exports.then = function then(resolve, reject) { + if (!this._fullfilledPromise) { + var self = this; + this._fullfilledPromise = new Promise(function(innerResolve, innerReject){ + self.end(function(err, res){ + if (err) innerReject(err); else innerResolve(res); + }); + }); + } + return this._fullfilledPromise.then(resolve, reject); +} + +/** + * Allow for extension + */ + +exports.use = function use(fn) { + fn(this); + return this; +} + + +/** + * Get request header `field`. + * Case-insensitive. + * + * @param {String} field + * @return {String} + * @api public + */ + +exports.get = function(field){ + return this._header[field.toLowerCase()]; +}; + +/** + * Get case-insensitive header `field` value. + * This is a deprecated internal API. Use `.get(field)` instead. + * + * (getHeader is no longer used internally by the superagent code base) + * + * @param {String} field + * @return {String} + * @api private + * @deprecated + */ + +exports.getHeader = exports.get; + +/** + * Set header `field` to `val`, or multiple fields with one object. + * Case-insensitive. + * + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public + */ + +exports.set = function(field, val){ + if (isObject(field)) { + for (var key in field) { + this.set(key, field[key]); + } + return this; + } + this._header[field.toLowerCase()] = val; + this.header[field] = val; + return this; +}; + +/** + * Remove header `field`. + * Case-insensitive. + * + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field + */ +exports.unset = function(field){ + delete this._header[field.toLowerCase()]; + delete this.header[field]; + return this; +}; + +/** + * Write the field `name` and `val` for "multipart/form-data" + * request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * ``` + * + * @param {String} name + * @param {String|Blob|File|Buffer|fs.ReadStream} val + * @return {Request} for chaining + * @api public + */ +exports.field = function(name, val) { + this._getFormData().append(name, val); + return this; +}; + +/** + * Abort the request, and clear potential timeout. + * + * @return {Request} + * @api public + */ +exports.abort = function(){ + if (this._aborted) { + return this; + } + this._aborted = true; + this.xhr && this.xhr.abort(); // browser + this.req && this.req.abort(); // node + this.clearTimeout(); + this.emit('abort'); + return this; +}; + +/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * + * @api public + */ + +exports.withCredentials = function(){ + // This is browser-only functionality. Node side is no-op. + this._withCredentials = true; + return this; +}; + +/** + * Set the max redirects to `n`. Does noting in browser XHR implementation. + * + * @param {Number} n + * @return {Request} for chaining + * @api public + */ + +exports.redirects = function(n){ + this._maxRedirects = n; + return this; +}; + +/** + * Convert to a plain javascript object (not JSON string) of scalar properties. + * Note as this method is designed to return a useful non-this value, + * it cannot be chained. + * + * @return {Object} describing method, url, and data of this request + * @api public + */ + +exports.toJSON = function(){ + return { + method: this.method, + url: this.url, + data: this._data + }; +}; + +/** + * Check if `obj` is a host object, + * we don't want to serialize these :) + * + * TODO: future proof, move to compoent land + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ + +exports._isHost = function _isHost(obj) { + var str = {}.toString.call(obj); + + switch (str) { + case '[object File]': + case '[object Blob]': + case '[object FormData]': + return true; + default: + return false; + } +} + +/** + * Send `data` as the request body, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * // manual json + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}') + * .end(callback) + * + * // auto json + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * // manual x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * // auto x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * // defaults to x-www-form-urlencoded + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */ + +exports.send = function(data){ + var obj = isObject(data); + var type = this._header['content-type']; + + // merge + if (obj && isObject(this._data)) { + for (var key in data) { + this._data[key] = data[key]; + } + } else if ('string' == typeof data) { + // default to x-www-form-urlencoded + if (!type) this.type('form'); + type = this._header['content-type']; + if ('application/x-www-form-urlencoded' == type) { + this._data = this._data + ? this._data + '&' + data + : data; + } else { + this._data = (this._data || '') + data; + } + } else { + this._data = data; + } + + if (!obj || this._isHost(data)) return this; + + // default to json + if (!type) this.type('json'); + return this; +}; + +},{"./is-object":22}],24:[function(require,module,exports){ +// The node and browser modules expose versions of this with the +// appropriate constructor function bound as first argument +/** + * Issue a request: + * + * Examples: + * + * request('GET', '/users').end(callback) + * request('/users').end(callback) + * request('/users', callback) + * + * @param {String} method + * @param {String|Function} url or callback + * @return {Request} + * @api public + */ + +function request(RequestConstructor, method, url) { + // callback + if ('function' == typeof url) { + return new RequestConstructor('GET', method).end(url); + } + + // url first + if (2 == arguments.length) { + return new RequestConstructor('GET', method); + } + + return new RequestConstructor(method, url); +} + +module.exports = request; + +},{}],25:[function(require,module,exports){ + +/** + * Expose `Emitter`. + */ + +if (typeof module !== 'undefined') { + module.exports = Emitter; +} + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +}; + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks['$' + event]; + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; + +},{}],26:[function(require,module,exports){ + +/** + * Reduce `arr` with `fn`. + * + * @param {Array} arr + * @param {Function} fn + * @param {Mixed} initial + * + * TODO: combatible error handling? + */ + +module.exports = function(arr, fn, initial){ + var idx = 0; + var len = arr.length; + var curr = arguments.length == 3 + ? initial + : arr[idx++]; + + while (idx < len) { + curr = fn.call(null, curr, arr[idx], ++idx, arr); + } + + return curr; +}; +},{}]},{},[1]); diff --git a/dist/jsonapi-client.min.js b/dist/jsonapi-client.min.js new file mode 100644 index 0000000..5c72c57 --- /dev/null +++ b/dist/jsonapi-client.min.js @@ -0,0 +1,2 @@ +!function t(e,r,n){function o(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(i)return i(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var f=r[s]={exports:{}};e[s][0].call(f.exports,function(t){var r=e[s][1][t];return o(r?r:t)},f,f.exports,t,e,r,n)}return r[s].exports}for(var i="function"==typeof require&&require,s=0;sr;r++)e["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(e).map(function(t){return e[t]});if("0123456789"!==n.join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(t){o[t]=t}),"abcdefghijklmnopqrst"!==Object.keys(Object.assign({},o)).join("")?!1:!0}catch(i){return!1}}var o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;e.exports=n()?Object.assign:function(t){for(var e,n,s=r(t),a=1;an;n++)r.push("a"+n);var i=["return function ("+r.join(",")+") {","var self = this;","return new Promise(function (rs, rj) {","var res = fn.call(",["self"].concat(r).concat([s]).join(","),");","if (res &&",'(typeof res === "object" || typeof res === "function") &&','typeof res.then === "function"',") {rs(res);}","});","};"].join("");return Function(["Promise","fn"],i)(o,t)}function n(t){for(var e=Math.max(t.length-1,3),r=[],n=0;e>n;n++)r.push("a"+n);var i=["return function ("+r.join(",")+") {","var self = this;","var args;","var argLength = arguments.length;","if (arguments.length > "+e+") {","args = new Array(arguments.length + 1);","for (var i = 0; i < arguments.length; i++) {","args[i] = arguments[i];","}","}","return new Promise(function (rs, rj) {","var cb = "+s+";","var res;","switch (argLength) {",r.concat(["extra"]).map(function(t,e){return"case "+e+":res = fn.call("+["self"].concat(r.slice(0,e)).concat("cb").join(",")+");break;"}).join(""),"default:","args[argLength] = cb;","res = fn.apply(self, args);","}","if (res &&",'(typeof res === "object" || typeof res === "function") &&','typeof res.then === "function"',") {rs(res);}","});","};"].join("");return Function(["Promise","fn"],i)(o,t)}var o=t("./core.js"),i=t("asap");e.exports=o,o.denodeify=function(t,e){return"number"==typeof e&&e!==1/0?r(t,e):n(t)};var s="function (err, res) {if (err) { rj(err); } else { rs(res); }}";o.nodeify=function(t){return function(){var e=Array.prototype.slice.call(arguments),r="function"==typeof e[e.length-1]?e.pop():null,n=this;try{return t.apply(this,arguments).nodeify(r,n)}catch(s){if(null===r||"undefined"==typeof r)return new o(function(t,e){e(s)});i(function(){r.call(n,s)})}}},o.prototype.nodeify=function(t,e){return"function"!=typeof t?this:void this.then(function(r){i(function(){t.call(e,null,r)})},function(r){i(function(){t.call(e,r)})})}},{"./core.js":7,asap:14}],13:[function(t,e){"use strict";var r=t("./core.js");e.exports=r,r.enableSynchronous=function(){r.prototype.isPending=function(){return 0==this.getState()},r.prototype.isFulfilled=function(){return 1==this.getState()},r.prototype.isRejected=function(){return 2==this.getState()},r.prototype.getValue=function(){if(3===this._81)return this._65.getValue();if(!this.isFulfilled())throw new Error("Cannot get a value of an unfulfilled promise.");return this._65},r.prototype.getReason=function(){if(3===this._81)return this._65.getReason();if(!this.isRejected())throw new Error("Cannot get a rejection reason of a non-rejected promise.");return this._65},r.prototype.getState=function(){return 3===this._81?this._65.getState():-1===this._81||-2===this._81?0:this._81}},r.disableSynchronous=function(){r.prototype.isPending=void 0,r.prototype.isFulfilled=void 0,r.prototype.isRejected=void 0,r.prototype.getValue=void 0,r.prototype.getReason=void 0,r.prototype.getState=void 0}},{"./core.js":7}],14:[function(t,e){"use strict";function r(){if(a.length)throw a.shift()}function n(t){var e;e=s.length?s.pop():new o,e.task=t,i(e)}function o(){this.task=null}var i=t("./raw"),s=[],a=[],u=i.makeRequestCallFromTimer(r);e.exports=n,o.prototype.call=function(){try{this.task.call()}catch(t){n.onerror?n.onerror(t):(a.push(t),u())}finally{this.task=null,s[s.length]=this}}},{"./raw":15}],15:[function(t,e){(function(t){"use strict";function r(t){a.length||(s(),u=!0),a[a.length]=t}function n(){for(;cf){for(var e=0,r=a.length-c;r>e;e++)a[e]=a[e+c];a.length-=c,c=0}}a.length=0,c=0,u=!1}function o(t){var e=1,r=new h(t),n=document.createTextNode("");return r.observe(n,{characterData:!0}),function(){e=-e,n.data=e}}function i(t){return function(){function e(){clearTimeout(r),clearInterval(n),t()}var r=setTimeout(e,0),n=setInterval(e,50)}}e.exports=r;var s,a=[],u=!1,c=0,f=1024,l="undefined"!=typeof t?t:self,h=l.MutationObserver||l.WebKitMutationObserver;s="function"==typeof h?o(n):i(n),r.requestFlush=s,r.makeRequestCallFromTimer=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],16:[function(t,e){"use strict";var r=String.prototype.replace,n=/%20/g;e.exports={"default":"RFC3986",formatters:{RFC1738:function(t){return r.call(t,n,"+")},RFC3986:function(t){return t}},RFC1738:"RFC1738",RFC3986:"RFC3986"}},{}],17:[function(t,e){"use strict";var r=t("./stringify"),n=t("./parse"),o=t("./formats");e.exports={formats:o,parse:n,stringify:r}},{"./formats":16,"./parse":18,"./stringify":19}],18:[function(t,e){"use strict";var r=t("./utils"),n=Object.prototype.hasOwnProperty,o={allowDots:!1,allowPrototypes:!1,arrayLimit:20,decoder:r.decode,delimiter:"&",depth:5,parameterLimit:1e3,plainObjects:!1,strictNullHandling:!1},i=function(t,e){for(var r={},o=t.split(e.delimiter,e.parameterLimit===1/0?void 0:e.parameterLimit),i=0;i=0&&r.parseArrays&&a<=r.arrayLimit?(n=[],n[a]=s(t,e,r)):n[i]=s(t,e,r)}return n},a=function(t,e,r){if(t){var o=r.allowDots?t.replace(/\.([^.[]+)/g,"[$1]"):t,i=/(\[[^[\]]*])/,a=/(\[[^[\]]*])/g,u=i.exec(o),c=u?o.slice(0,u.index):o,f=[];if(c){if(!r.plainObjects&&n.call(Object.prototype,c)&&!r.allowPrototypes)return;f.push(c)}for(var l=0;null!==(u=a.exec(o))&&le;++e)t.push("%"+((16>e?"0":"")+e.toString(16)).toUpperCase());return t}();r.arrayToObject=function(t,e){for(var r=e&&e.plainObjects?Object.create(null):{},n=0;n=48&&57>=i||i>=65&&90>=i||i>=97&&122>=i?r+=e.charAt(n):128>i?r+=o[i]:2048>i?r+=o[192|i>>6]+o[128|63&i]:55296>i||i>=57344?r+=o[224|i>>12]+o[128|i>>6&63]+o[128|63&i]:(n+=1,i=65536+((1023&i)<<10|1023&e.charCodeAt(n)),r+=o[240|i>>18]+o[128|i>>12&63]+o[128|i>>6&63]+o[128|63&i])}return r},r.compact=function(t,e){if("object"!=typeof t||null===t)return t;var n=e||[],o=n.indexOf(t);if(-1!==o)return n[o];if(n.push(t),Array.isArray(t)){for(var i=[],s=0;si;++i)e=o[i],r=e.indexOf("="),-1==r?n[decodeURIComponent(e)]="":n[decodeURIComponent(e.slice(0,r))]=decodeURIComponent(e.slice(r+1));return n}function s(t){var e,r,n,o,i=t.split(/\r?\n/),s={};i.pop();for(var a=0,u=i.length;u>a;++a)r=i[a],e=r.indexOf(":"),n=r.slice(0,e).toLowerCase(),o=g(r.slice(e+1)),s[n]=o;return s}function a(t){return/[\/+]json\b/.test(t)}function u(t){return t.split(/ *; */).shift()}function c(t){return y(t.split(/ *; */),function(t,e){var r=e.split(/ *= */),n=r.shift(),o=r.shift();return n&&o&&(t[n]=o),t},{})}function f(t,e){e=e||{},this.req=t,this.xhr=this.req.xhr,this.text="HEAD"!=this.req.method&&(""===this.xhr.responseType||"text"===this.xhr.responseType)||"undefined"==typeof this.xhr.responseType?this.xhr.responseText:null,this.statusText=this.req.xhr.statusText,this._setStatusProperties(this.xhr.status),this.header=this.headers=s(this.xhr.getAllResponseHeaders()),this.header["content-type"]=this.xhr.getResponseHeader("content-type"),this._setHeaderProperties(this.header),this.body="HEAD"!=this.req.method?this._parseBody(this.text?this.text:this.xhr.response):null}function l(t,e){var r=this;this._query=this._query||[],this.method=t,this.url=e,this.header={},this._header={},this.on("end",function(){var t=null,e=null;try{e=new f(r)}catch(n){return t=new Error("Parser is unable to parse the response"),t.parse=!0,t.original=n,t.rawResponse=r.xhr&&r.xhr.responseText?r.xhr.responseText:null,t.statusCode=r.xhr&&r.xhr.status?r.xhr.status:null,r.callback(t)}if(r.emit("response",e),t)return r.callback(t,e);try{if(e.status>=200&&e.status<300)return r.callback(t,e);var o=new Error(e.statusText||"Unsuccessful HTTP response");o.original=t,o.response=e,o.status=e.status,r.callback(o,e)}catch(n){r.callback(n)}})}function h(t,e){var r=m("DELETE",t);return e&&r.end(e),r}var p,d=t("emitter"),y=t("reduce"),_=t("./request-base"),v=t("./is-object");p="undefined"!=typeof window?window:"undefined"!=typeof self?self:this;var m=e.exports=t("./request").bind(null,l);m.getXHR=function(){if(!(!p.XMLHttpRequest||p.location&&"file:"==p.location.protocol&&p.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(t){}return!1};var g="".trim?function(t){return t.trim()}:function(t){return t.replace(/(^\s*|\s*$)/g,"")};m.serializeObject=n,m.parseString=i,m.types={html:"text/html",json:"application/json",xml:"application/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},m.serialize={"application/x-www-form-urlencoded":n,"application/json":JSON.stringify},m.parse={"application/x-www-form-urlencoded":i,"application/json":JSON.parse},f.prototype.get=function(t){return this.header[t.toLowerCase()]},f.prototype._setHeaderProperties=function(){var t=this.header["content-type"]||"";this.type=u(t);var e=c(t);for(var r in e)this[r]=e[r]},f.prototype._parseBody=function(t){var e=m.parse[this.type];return!e&&a(this.type)&&(e=m.parse["application/json"]),e&&t&&(t.length||t instanceof Object)?e(t):null},f.prototype._setStatusProperties=function(t){1223===t&&(t=204);var e=t/100|0;this.status=this.statusCode=t,this.statusType=e,this.info=1==e,this.ok=2==e,this.clientError=4==e,this.serverError=5==e,this.error=4==e||5==e?this.toError():!1,this.accepted=202==t,this.noContent=204==t,this.badRequest=400==t,this.unauthorized=401==t,this.notAcceptable=406==t,this.notFound=404==t,this.forbidden=403==t},f.prototype.toError=function(){var t=this.req,e=t.method,r=t.url,n="cannot "+e+" "+r+" ("+this.status+")",o=new Error(n);return o.status=this.status,o.method=e,o.url=r,o},m.Response=f,d(l.prototype);for(var b in _)l.prototype[b]=_[b];l.prototype.type=function(t){return this.set("Content-Type",m.types[t]||t),this},l.prototype.responseType=function(t){return this._responseType=t,this},l.prototype.accept=function(t){return this.set("Accept",m.types[t]||t),this},l.prototype.auth=function(t,e,r){switch(r||(r={type:"basic"}),r.type){case"basic":var n=btoa(t+":"+e);this.set("Authorization","Basic "+n);break;case"auto":this.username=t,this.password=e}return this},l.prototype.query=function(t){return"string"!=typeof t&&(t=n(t)),t&&this._query.push(t),this},l.prototype.attach=function(t,e,r){return this._getFormData().append(t,e,r||e.name),this},l.prototype._getFormData=function(){return this._formData||(this._formData=new p.FormData),this._formData},l.prototype.callback=function(t,e){var r=this._callback;this.clearTimeout(),r(t,e)},l.prototype.crossDomainError=function(){var t=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");t.crossDomain=!0,t.status=this.status,t.method=this.method,t.url=this.url,this.callback(t)},l.prototype._timeoutError=function(){ +var t=this._timeout,e=new Error("timeout of "+t+"ms exceeded");e.timeout=t,this.callback(e)},l.prototype._appendQueryString=function(){var t=this._query.join("&");t&&(this.url+=~this.url.indexOf("?")?"&"+t:"?"+t)},l.prototype.end=function(t){var e=this,n=this.xhr=m.getXHR(),o=this._timeout,i=this._formData||this._data;this._callback=t||r,n.onreadystatechange=function(){if(4==n.readyState){var t;try{t=n.status}catch(r){t=0}if(0==t){if(e.timedout)return e._timeoutError();if(e._aborted)return;return e.crossDomainError()}e.emit("end")}};var s=function(t){t.total>0&&(t.percent=t.loaded/t.total*100),t.direction="download",e.emit("progress",t)};this.hasListeners("progress")&&(n.onprogress=s);try{n.upload&&this.hasListeners("progress")&&(n.upload.onprogress=s)}catch(u){}if(o&&!this._timer&&(this._timer=setTimeout(function(){e.timedout=!0,e.abort()},o)),this._appendQueryString(),this.username&&this.password?n.open(this.method,this.url,!0,this.username,this.password):n.open(this.method,this.url,!0),this._withCredentials&&(n.withCredentials=!0),"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof i&&!this._isHost(i)){var c=this._header["content-type"],f=this._serializer||m.serialize[c?c.split(";")[0]:""];!f&&a(c)&&(f=m.serialize["application/json"]),f&&(i=f(i))}for(var l in this.header)null!=this.header[l]&&n.setRequestHeader(l,this.header[l]);return this._responseType&&(n.responseType=this._responseType),this.emit("request",this),n.send("undefined"!=typeof i?i:null),this},m.Request=l,m.get=function(t,e,r){var n=m("GET",t);return"function"==typeof e&&(r=e,e=null),e&&n.query(e),r&&n.end(r),n},m.head=function(t,e,r){var n=m("HEAD",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},m.options=function(t,e,r){var n=m("OPTIONS",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},m.del=h,m["delete"]=h,m.patch=function(t,e,r){var n=m("PATCH",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},m.post=function(t,e,r){var n=m("POST",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n},m.put=function(t,e,r){var n=m("PUT",t);return"function"==typeof e&&(r=e,e=null),e&&n.send(e),r&&n.end(r),n}},{"./is-object":22,"./request":24,"./request-base":23,emitter:25,reduce:26}],22:[function(t,e){function r(t){return null!==t&&"object"==typeof t}e.exports=r},{}],23:[function(t,e,r){var n=t("./is-object");r.clearTimeout=function(){return this._timeout=0,clearTimeout(this._timer),this},r.parse=function(t){return this._parser=t,this},r.serialize=function(t){return this._serializer=t,this},r.timeout=function(t){return this._timeout=t,this},r.then=function(t,e){if(!this._fullfilledPromise){var r=this;this._fullfilledPromise=new Promise(function(t,e){r.end(function(r,n){r?e(r):t(n)})})}return this._fullfilledPromise.then(t,e)},r.use=function(t){return t(this),this},r.get=function(t){return this._header[t.toLowerCase()]},r.getHeader=r.get,r.set=function(t,e){if(n(t)){for(var r in t)this.set(r,t[r]);return this}return this._header[t.toLowerCase()]=e,this.header[t]=e,this},r.unset=function(t){return delete this._header[t.toLowerCase()],delete this.header[t],this},r.field=function(t,e){return this._getFormData().append(t,e),this},r.abort=function(){return this._aborted?this:(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req&&this.req.abort(),this.clearTimeout(),this.emit("abort"),this)},r.withCredentials=function(){return this._withCredentials=!0,this},r.redirects=function(t){return this._maxRedirects=t,this},r.toJSON=function(){return{method:this.method,url:this.url,data:this._data}},r._isHost=function(t){var e={}.toString.call(t);switch(e){case"[object File]":case"[object Blob]":case"[object FormData]":return!0;default:return!1}},r.send=function(t){var e=n(t),r=this._header["content-type"];if(e&&n(this._data))for(var o in t)this._data[o]=t[o];else"string"==typeof t?(r||this.type("form"),r=this._header["content-type"],this._data="application/x-www-form-urlencoded"==r?this._data?this._data+"&"+t:t:(this._data||"")+t):this._data=t;return!e||this._isHost(t)?this:(r||this.type("json"),this)}},{"./is-object":22}],24:[function(t,e){function r(t,e,r){return"function"==typeof r?new t("GET",e).end(r):2==arguments.length?new t("GET",e):new t(e,r)}e.exports=r},{}],25:[function(t,e){function r(t){return t?n(t):void 0}function n(t){for(var e in r.prototype)t[e]=r.prototype[e];return t}"undefined"!=typeof e&&(e.exports=r),r.prototype.on=r.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},r.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var n,o=0;on;++n)r[n].apply(this,e)}return this},r.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},r.prototype.hasListeners=function(t){return!!this.listeners(t).length}},{}],26:[function(t,e){e.exports=function(t,e,r){for(var n=0,o=t.length,i=3==arguments.length?r:t[n++];o>n;)i=e.call(null,i,t[n],++n,t);return i}},{}]},{},[1]); \ No newline at end of file diff --git a/lib/Resource.js b/lib/Resource.js index 838f18a..b1e1e40 100644 --- a/lib/Resource.js +++ b/lib/Resource.js @@ -55,7 +55,7 @@ Resource.prototype._getRaw = function() { Resource.prototype._getDelta = function() { var primaryRelations = { }; - var relationships = this._getRaw().relationships; + var relationships = this._getRaw().relationships || { }; Object.keys(relationships).forEach(function(i) { if (getMeta(relationships[i]).relation === "foreign") return; primaryRelations[i] = relationships[i]; @@ -78,7 +78,8 @@ Resource.prototype._getUidString = function() { }; Resource.prototype._getPathFor = function(relation) { - return this._getRaw().relationships[relation].links.related; + var url = this._getRaw().relationships[relation].links.related; + return url.href || url; }; Resource.prototype._matches = function(other) { diff --git a/lib/Transport.js b/lib/Transport.js index 68de5d8..0af9523 100644 --- a/lib/Transport.js +++ b/lib/Transport.js @@ -56,6 +56,7 @@ Transport.prototype._action = function(method, url, data, callback) { } var response; + try { response = JSON.parse(err.response.text); } catch(e) { @@ -82,6 +83,11 @@ Transport.prototype._action = function(method, url, data, callback) { return callback(realErrors[0]); } + // HTTP STATUS 204 = no content + if (payload.statusCode == 204) { + return callback(null, payload.req, payload.req._data.data, payload.req._data.included); + } + if (!payload.body) { try { payload.body = JSON.parse(payload.text);