vue-resource.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. /*!
  2. * vue-resource v0.9.3
  3. * https://github.com/vuejs/vue-resource
  4. * Released under the MIT License.
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  8. typeof define === 'function' && define.amd ? define(factory) :
  9. (global.VueResource = factory());
  10. }(this, function () { 'use strict';
  11. /**
  12. * Promises/A+ polyfill v1.1.4 (https://github.com/bramstein/promis)
  13. */
  14. var RESOLVED = 0;
  15. var REJECTED = 1;
  16. var PENDING = 2;
  17. function Promise$2(executor) {
  18. this.state = PENDING;
  19. this.value = undefined;
  20. this.deferred = [];
  21. var promise = this;
  22. try {
  23. executor(function (x) {
  24. promise.resolve(x);
  25. }, function (r) {
  26. promise.reject(r);
  27. });
  28. } catch (e) {
  29. promise.reject(e);
  30. }
  31. }
  32. Promise$2.reject = function (r) {
  33. return new Promise$2(function (resolve, reject) {
  34. reject(r);
  35. });
  36. };
  37. Promise$2.resolve = function (x) {
  38. return new Promise$2(function (resolve, reject) {
  39. resolve(x);
  40. });
  41. };
  42. Promise$2.all = function all(iterable) {
  43. return new Promise$2(function (resolve, reject) {
  44. var count = 0,
  45. result = [];
  46. if (iterable.length === 0) {
  47. resolve(result);
  48. }
  49. function resolver(i) {
  50. return function (x) {
  51. result[i] = x;
  52. count += 1;
  53. if (count === iterable.length) {
  54. resolve(result);
  55. }
  56. };
  57. }
  58. for (var i = 0; i < iterable.length; i += 1) {
  59. Promise$2.resolve(iterable[i]).then(resolver(i), reject);
  60. }
  61. });
  62. };
  63. Promise$2.race = function race(iterable) {
  64. return new Promise$2(function (resolve, reject) {
  65. for (var i = 0; i < iterable.length; i += 1) {
  66. Promise$2.resolve(iterable[i]).then(resolve, reject);
  67. }
  68. });
  69. };
  70. var p$1 = Promise$2.prototype;
  71. p$1.resolve = function resolve(x) {
  72. var promise = this;
  73. if (promise.state === PENDING) {
  74. if (x === promise) {
  75. throw new TypeError('Promise settled with itself.');
  76. }
  77. var called = false;
  78. try {
  79. var then = x && x['then'];
  80. if (x !== null && typeof x === 'object' && typeof then === 'function') {
  81. then.call(x, function (x) {
  82. if (!called) {
  83. promise.resolve(x);
  84. }
  85. called = true;
  86. }, function (r) {
  87. if (!called) {
  88. promise.reject(r);
  89. }
  90. called = true;
  91. });
  92. return;
  93. }
  94. } catch (e) {
  95. if (!called) {
  96. promise.reject(e);
  97. }
  98. return;
  99. }
  100. promise.state = RESOLVED;
  101. promise.value = x;
  102. promise.notify();
  103. }
  104. };
  105. p$1.reject = function reject(reason) {
  106. var promise = this;
  107. if (promise.state === PENDING) {
  108. if (reason === promise) {
  109. throw new TypeError('Promise settled with itself.');
  110. }
  111. promise.state = REJECTED;
  112. promise.value = reason;
  113. promise.notify();
  114. }
  115. };
  116. p$1.notify = function notify() {
  117. var promise = this;
  118. nextTick(function () {
  119. if (promise.state !== PENDING) {
  120. while (promise.deferred.length) {
  121. var deferred = promise.deferred.shift(),
  122. onResolved = deferred[0],
  123. onRejected = deferred[1],
  124. resolve = deferred[2],
  125. reject = deferred[3];
  126. try {
  127. if (promise.state === RESOLVED) {
  128. if (typeof onResolved === 'function') {
  129. resolve(onResolved.call(undefined, promise.value));
  130. } else {
  131. resolve(promise.value);
  132. }
  133. } else if (promise.state === REJECTED) {
  134. if (typeof onRejected === 'function') {
  135. resolve(onRejected.call(undefined, promise.value));
  136. } else {
  137. reject(promise.value);
  138. }
  139. }
  140. } catch (e) {
  141. reject(e);
  142. }
  143. }
  144. }
  145. });
  146. };
  147. p$1.then = function then(onResolved, onRejected) {
  148. var promise = this;
  149. return new Promise$2(function (resolve, reject) {
  150. promise.deferred.push([onResolved, onRejected, resolve, reject]);
  151. promise.notify();
  152. });
  153. };
  154. p$1.catch = function (onRejected) {
  155. return this.then(undefined, onRejected);
  156. };
  157. var PromiseObj = window.Promise || Promise$2;
  158. function Promise$1(executor, context) {
  159. if (executor instanceof PromiseObj) {
  160. this.promise = executor;
  161. } else {
  162. this.promise = new PromiseObj(executor.bind(context));
  163. }
  164. this.context = context;
  165. }
  166. Promise$1.all = function (iterable, context) {
  167. return new Promise$1(PromiseObj.all(iterable), context);
  168. };
  169. Promise$1.resolve = function (value, context) {
  170. return new Promise$1(PromiseObj.resolve(value), context);
  171. };
  172. Promise$1.reject = function (reason, context) {
  173. return new Promise$1(PromiseObj.reject(reason), context);
  174. };
  175. Promise$1.race = function (iterable, context) {
  176. return new Promise$1(PromiseObj.race(iterable), context);
  177. };
  178. var p = Promise$1.prototype;
  179. p.bind = function (context) {
  180. this.context = context;
  181. return this;
  182. };
  183. p.then = function (fulfilled, rejected) {
  184. if (fulfilled && fulfilled.bind && this.context) {
  185. fulfilled = fulfilled.bind(this.context);
  186. }
  187. if (rejected && rejected.bind && this.context) {
  188. rejected = rejected.bind(this.context);
  189. }
  190. return new Promise$1(this.promise.then(fulfilled, rejected), this.context);
  191. };
  192. p.catch = function (rejected) {
  193. if (rejected && rejected.bind && this.context) {
  194. rejected = rejected.bind(this.context);
  195. }
  196. return new Promise$1(this.promise.catch(rejected), this.context);
  197. };
  198. p.finally = function (callback) {
  199. return this.then(function (value) {
  200. callback.call(this);
  201. return value;
  202. }, function (reason) {
  203. callback.call(this);
  204. return PromiseObj.reject(reason);
  205. });
  206. };
  207. var debug = false;
  208. var util = {};
  209. var array = [];
  210. function Util (Vue) {
  211. util = Vue.util;
  212. debug = Vue.config.debug || !Vue.config.silent;
  213. }
  214. function warn(msg) {
  215. if (typeof console !== 'undefined' && debug) {
  216. console.warn('[VueResource warn]: ' + msg);
  217. }
  218. }
  219. function error(msg) {
  220. if (typeof console !== 'undefined') {
  221. console.error(msg);
  222. }
  223. }
  224. function nextTick(cb, ctx) {
  225. return util.nextTick(cb, ctx);
  226. }
  227. function trim(str) {
  228. return str.replace(/^\s*|\s*$/g, '');
  229. }
  230. var isArray = Array.isArray;
  231. function isString(val) {
  232. return typeof val === 'string';
  233. }
  234. function isBoolean(val) {
  235. return val === true || val === false;
  236. }
  237. function isFunction(val) {
  238. return typeof val === 'function';
  239. }
  240. function isObject(obj) {
  241. return obj !== null && typeof obj === 'object';
  242. }
  243. function isPlainObject(obj) {
  244. return isObject(obj) && Object.getPrototypeOf(obj) == Object.prototype;
  245. }
  246. function isFormData(obj) {
  247. return typeof FormData !== 'undefined' && obj instanceof FormData;
  248. }
  249. function when(value, fulfilled, rejected) {
  250. var promise = Promise$1.resolve(value);
  251. if (arguments.length < 2) {
  252. return promise;
  253. }
  254. return promise.then(fulfilled, rejected);
  255. }
  256. function options(fn, obj, opts) {
  257. opts = opts || {};
  258. if (isFunction(opts)) {
  259. opts = opts.call(obj);
  260. }
  261. return merge(fn.bind({ $vm: obj, $options: opts }), fn, { $options: opts });
  262. }
  263. function each(obj, iterator) {
  264. var i, key;
  265. if (typeof obj.length == 'number') {
  266. for (i = 0; i < obj.length; i++) {
  267. iterator.call(obj[i], obj[i], i);
  268. }
  269. } else if (isObject(obj)) {
  270. for (key in obj) {
  271. if (obj.hasOwnProperty(key)) {
  272. iterator.call(obj[key], obj[key], key);
  273. }
  274. }
  275. }
  276. return obj;
  277. }
  278. var assign = Object.assign || _assign;
  279. function merge(target) {
  280. var args = array.slice.call(arguments, 1);
  281. args.forEach(function (source) {
  282. _merge(target, source, true);
  283. });
  284. return target;
  285. }
  286. function defaults(target) {
  287. var args = array.slice.call(arguments, 1);
  288. args.forEach(function (source) {
  289. for (var key in source) {
  290. if (target[key] === undefined) {
  291. target[key] = source[key];
  292. }
  293. }
  294. });
  295. return target;
  296. }
  297. function _assign(target) {
  298. var args = array.slice.call(arguments, 1);
  299. args.forEach(function (source) {
  300. _merge(target, source);
  301. });
  302. return target;
  303. }
  304. function _merge(target, source, deep) {
  305. for (var key in source) {
  306. if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
  307. if (isPlainObject(source[key]) && !isPlainObject(target[key])) {
  308. target[key] = {};
  309. }
  310. if (isArray(source[key]) && !isArray(target[key])) {
  311. target[key] = [];
  312. }
  313. _merge(target[key], source[key], deep);
  314. } else if (source[key] !== undefined) {
  315. target[key] = source[key];
  316. }
  317. }
  318. }
  319. function root (options, next) {
  320. var url = next(options);
  321. if (isString(options.root) && !url.match(/^(https?:)?\//)) {
  322. url = options.root + '/' + url;
  323. }
  324. return url;
  325. }
  326. function query (options, next) {
  327. var urlParams = Object.keys(Url.options.params),
  328. query = {},
  329. url = next(options);
  330. each(options.params, function (value, key) {
  331. if (urlParams.indexOf(key) === -1) {
  332. query[key] = value;
  333. }
  334. });
  335. query = Url.params(query);
  336. if (query) {
  337. url += (url.indexOf('?') == -1 ? '?' : '&') + query;
  338. }
  339. return url;
  340. }
  341. /**
  342. * URL Template v2.0.6 (https://github.com/bramstein/url-template)
  343. */
  344. function expand(url, params, variables) {
  345. var tmpl = parse(url),
  346. expanded = tmpl.expand(params);
  347. if (variables) {
  348. variables.push.apply(variables, tmpl.vars);
  349. }
  350. return expanded;
  351. }
  352. function parse(template) {
  353. var operators = ['+', '#', '.', '/', ';', '?', '&'],
  354. variables = [];
  355. return {
  356. vars: variables,
  357. expand: function (context) {
  358. return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
  359. if (expression) {
  360. var operator = null,
  361. values = [];
  362. if (operators.indexOf(expression.charAt(0)) !== -1) {
  363. operator = expression.charAt(0);
  364. expression = expression.substr(1);
  365. }
  366. expression.split(/,/g).forEach(function (variable) {
  367. var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
  368. values.push.apply(values, getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
  369. variables.push(tmp[1]);
  370. });
  371. if (operator && operator !== '+') {
  372. var separator = ',';
  373. if (operator === '?') {
  374. separator = '&';
  375. } else if (operator !== '#') {
  376. separator = operator;
  377. }
  378. return (values.length !== 0 ? operator : '') + values.join(separator);
  379. } else {
  380. return values.join(',');
  381. }
  382. } else {
  383. return encodeReserved(literal);
  384. }
  385. });
  386. }
  387. };
  388. }
  389. function getValues(context, operator, key, modifier) {
  390. var value = context[key],
  391. result = [];
  392. if (isDefined(value) && value !== '') {
  393. if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  394. value = value.toString();
  395. if (modifier && modifier !== '*') {
  396. value = value.substring(0, parseInt(modifier, 10));
  397. }
  398. result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
  399. } else {
  400. if (modifier === '*') {
  401. if (Array.isArray(value)) {
  402. value.filter(isDefined).forEach(function (value) {
  403. result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null));
  404. });
  405. } else {
  406. Object.keys(value).forEach(function (k) {
  407. if (isDefined(value[k])) {
  408. result.push(encodeValue(operator, value[k], k));
  409. }
  410. });
  411. }
  412. } else {
  413. var tmp = [];
  414. if (Array.isArray(value)) {
  415. value.filter(isDefined).forEach(function (value) {
  416. tmp.push(encodeValue(operator, value));
  417. });
  418. } else {
  419. Object.keys(value).forEach(function (k) {
  420. if (isDefined(value[k])) {
  421. tmp.push(encodeURIComponent(k));
  422. tmp.push(encodeValue(operator, value[k].toString()));
  423. }
  424. });
  425. }
  426. if (isKeyOperator(operator)) {
  427. result.push(encodeURIComponent(key) + '=' + tmp.join(','));
  428. } else if (tmp.length !== 0) {
  429. result.push(tmp.join(','));
  430. }
  431. }
  432. }
  433. } else {
  434. if (operator === ';') {
  435. result.push(encodeURIComponent(key));
  436. } else if (value === '' && (operator === '&' || operator === '?')) {
  437. result.push(encodeURIComponent(key) + '=');
  438. } else if (value === '') {
  439. result.push('');
  440. }
  441. }
  442. return result;
  443. }
  444. function isDefined(value) {
  445. return value !== undefined && value !== null;
  446. }
  447. function isKeyOperator(operator) {
  448. return operator === ';' || operator === '&' || operator === '?';
  449. }
  450. function encodeValue(operator, value, key) {
  451. value = operator === '+' || operator === '#' ? encodeReserved(value) : encodeURIComponent(value);
  452. if (key) {
  453. return encodeURIComponent(key) + '=' + value;
  454. } else {
  455. return value;
  456. }
  457. }
  458. function encodeReserved(str) {
  459. return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
  460. if (!/%[0-9A-Fa-f]/.test(part)) {
  461. part = encodeURI(part);
  462. }
  463. return part;
  464. }).join('');
  465. }
  466. function template (options) {
  467. var variables = [],
  468. url = expand(options.url, options.params, variables);
  469. variables.forEach(function (key) {
  470. delete options.params[key];
  471. });
  472. return url;
  473. }
  474. /**
  475. * Service for URL templating.
  476. */
  477. var ie = document.documentMode;
  478. var el = document.createElement('a');
  479. function Url(url, params) {
  480. var self = this || {},
  481. options = url,
  482. transform;
  483. if (isString(url)) {
  484. options = { url: url, params: params };
  485. }
  486. options = merge({}, Url.options, self.$options, options);
  487. Url.transforms.forEach(function (handler) {
  488. transform = factory(handler, transform, self.$vm);
  489. });
  490. return transform(options);
  491. }
  492. /**
  493. * Url options.
  494. */
  495. Url.options = {
  496. url: '',
  497. root: null,
  498. params: {}
  499. };
  500. /**
  501. * Url transforms.
  502. */
  503. Url.transforms = [template, query, root];
  504. /**
  505. * Encodes a Url parameter string.
  506. *
  507. * @param {Object} obj
  508. */
  509. Url.params = function (obj) {
  510. var params = [],
  511. escape = encodeURIComponent;
  512. params.add = function (key, value) {
  513. if (isFunction(value)) {
  514. value = value();
  515. }
  516. if (value === null) {
  517. value = '';
  518. }
  519. this.push(escape(key) + '=' + escape(value));
  520. };
  521. serialize(params, obj);
  522. return params.join('&').replace(/%20/g, '+');
  523. };
  524. /**
  525. * Parse a URL and return its components.
  526. *
  527. * @param {String} url
  528. */
  529. Url.parse = function (url) {
  530. if (ie) {
  531. el.href = url;
  532. url = el.href;
  533. }
  534. el.href = url;
  535. return {
  536. href: el.href,
  537. protocol: el.protocol ? el.protocol.replace(/:$/, '') : '',
  538. port: el.port,
  539. host: el.host,
  540. hostname: el.hostname,
  541. pathname: el.pathname.charAt(0) === '/' ? el.pathname : '/' + el.pathname,
  542. search: el.search ? el.search.replace(/^\?/, '') : '',
  543. hash: el.hash ? el.hash.replace(/^#/, '') : ''
  544. };
  545. };
  546. function factory(handler, next, vm) {
  547. return function (options) {
  548. return handler.call(vm, options, next);
  549. };
  550. }
  551. function serialize(params, obj, scope) {
  552. var array = isArray(obj),
  553. plain = isPlainObject(obj),
  554. hash;
  555. each(obj, function (value, key) {
  556. hash = isObject(value) || isArray(value);
  557. if (scope) {
  558. key = scope + '[' + (plain || hash ? key : '') + ']';
  559. }
  560. if (!scope && array) {
  561. params.add(value.name, value.value);
  562. } else if (hash) {
  563. serialize(params, value, key);
  564. } else {
  565. params.add(key, value);
  566. }
  567. });
  568. }
  569. function xdrClient (request) {
  570. return new Promise$1(function (resolve) {
  571. var xdr = new XDomainRequest(),
  572. handler = function (event) {
  573. var response = request.respondWith(xdr.responseText, {
  574. status: xdr.status,
  575. statusText: xdr.statusText
  576. });
  577. resolve(response);
  578. };
  579. request.abort = function () {
  580. return xdr.abort();
  581. };
  582. xdr.open(request.method, request.getUrl(), true);
  583. xdr.timeout = 0;
  584. xdr.onload = handler;
  585. xdr.onerror = handler;
  586. xdr.ontimeout = function () {};
  587. xdr.onprogress = function () {};
  588. xdr.send(request.getBody());
  589. });
  590. }
  591. var ORIGIN_URL = Url.parse(location.href);
  592. var SUPPORTS_CORS = 'withCredentials' in new XMLHttpRequest();
  593. function cors (request, next) {
  594. if (!isBoolean(request.crossOrigin) && crossOrigin(request)) {
  595. request.crossOrigin = true;
  596. }
  597. if (request.crossOrigin) {
  598. if (!SUPPORTS_CORS) {
  599. request.client = xdrClient;
  600. }
  601. delete request.emulateHTTP;
  602. }
  603. next();
  604. }
  605. function crossOrigin(request) {
  606. var requestUrl = Url.parse(Url(request));
  607. return requestUrl.protocol !== ORIGIN_URL.protocol || requestUrl.host !== ORIGIN_URL.host;
  608. }
  609. function body (request, next) {
  610. if (request.emulateJSON && isPlainObject(request.body)) {
  611. request.body = Url.params(request.body);
  612. request.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  613. }
  614. if (isFormData(request.body)) {
  615. delete request.headers['Content-Type'];
  616. }
  617. if (isPlainObject(request.body)) {
  618. request.body = JSON.stringify(request.body);
  619. }
  620. next(function (response) {
  621. var contentType = response.headers['Content-Type'];
  622. if (isString(contentType) && contentType.indexOf('application/json') === 0) {
  623. try {
  624. response.data = response.json();
  625. } catch (e) {
  626. response.data = null;
  627. }
  628. } else {
  629. response.data = response.text();
  630. }
  631. });
  632. }
  633. function jsonpClient (request) {
  634. return new Promise$1(function (resolve) {
  635. var name = request.jsonp || 'callback',
  636. callback = '_jsonp' + Math.random().toString(36).substr(2),
  637. body = null,
  638. handler,
  639. script;
  640. handler = function (event) {
  641. var status = 0;
  642. if (event.type === 'load' && body !== null) {
  643. status = 200;
  644. } else if (event.type === 'error') {
  645. status = 404;
  646. }
  647. resolve(request.respondWith(body, { status: status }));
  648. delete window[callback];
  649. document.body.removeChild(script);
  650. };
  651. request.params[name] = callback;
  652. window[callback] = function (result) {
  653. body = JSON.stringify(result);
  654. };
  655. script = document.createElement('script');
  656. script.src = request.getUrl();
  657. script.type = 'text/javascript';
  658. script.async = true;
  659. script.onload = handler;
  660. script.onerror = handler;
  661. document.body.appendChild(script);
  662. });
  663. }
  664. function jsonp (request, next) {
  665. if (request.method == 'JSONP') {
  666. request.client = jsonpClient;
  667. }
  668. next(function (response) {
  669. if (request.method == 'JSONP') {
  670. response.data = response.json();
  671. }
  672. });
  673. }
  674. function before (request, next) {
  675. if (isFunction(request.before)) {
  676. request.before.call(this, request);
  677. }
  678. next();
  679. }
  680. /**
  681. * HTTP method override Interceptor.
  682. */
  683. function method (request, next) {
  684. if (request.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(request.method)) {
  685. request.headers['X-HTTP-Method-Override'] = request.method;
  686. request.method = 'POST';
  687. }
  688. next();
  689. }
  690. function header (request, next) {
  691. request.method = request.method.toUpperCase();
  692. request.headers = assign({}, Http.headers.common, !request.crossOrigin ? Http.headers.custom : {}, Http.headers[request.method.toLowerCase()], request.headers);
  693. next();
  694. }
  695. /**
  696. * Timeout Interceptor.
  697. */
  698. function timeout (request, next) {
  699. var timeout;
  700. if (request.timeout) {
  701. timeout = setTimeout(function () {
  702. request.abort();
  703. }, request.timeout);
  704. }
  705. next(function (response) {
  706. clearTimeout(timeout);
  707. });
  708. }
  709. function xhrClient (request) {
  710. return new Promise$1(function (resolve) {
  711. var xhr = new XMLHttpRequest(),
  712. handler = function (event) {
  713. var response = request.respondWith('response' in xhr ? xhr.response : xhr.responseText, {
  714. status: xhr.status === 1223 ? 204 : xhr.status, // IE9 status bug
  715. statusText: xhr.status === 1223 ? 'No Content' : trim(xhr.statusText),
  716. headers: parseHeaders(xhr.getAllResponseHeaders())
  717. });
  718. resolve(response);
  719. };
  720. request.abort = function () {
  721. return xhr.abort();
  722. };
  723. xhr.open(request.method, request.getUrl(), true);
  724. xhr.timeout = 0;
  725. xhr.onload = handler;
  726. xhr.onerror = handler;
  727. if (request.progress) {
  728. if (request.method === 'GET') {
  729. xhr.addEventListener('progress', request.progress);
  730. } else if (/^(POST|PUT)$/i.test(request.method)) {
  731. xhr.upload.addEventListener('progress', request.progress);
  732. }
  733. }
  734. if (request.credentials === true) {
  735. xhr.withCredentials = true;
  736. }
  737. each(request.headers || {}, function (value, header) {
  738. xhr.setRequestHeader(header, value);
  739. });
  740. xhr.send(request.getBody());
  741. });
  742. }
  743. function parseHeaders(str) {
  744. var headers = {},
  745. value,
  746. name,
  747. i;
  748. each(trim(str).split('\n'), function (row) {
  749. i = row.indexOf(':');
  750. name = trim(row.slice(0, i));
  751. value = trim(row.slice(i + 1));
  752. if (headers[name]) {
  753. if (isArray(headers[name])) {
  754. headers[name].push(value);
  755. } else {
  756. headers[name] = [headers[name], value];
  757. }
  758. } else {
  759. headers[name] = value;
  760. }
  761. });
  762. return headers;
  763. }
  764. function Client (context) {
  765. var reqHandlers = [sendRequest],
  766. resHandlers = [],
  767. handler;
  768. if (!isObject(context)) {
  769. context = null;
  770. }
  771. function Client(request) {
  772. return new Promise$1(function (resolve) {
  773. function exec() {
  774. handler = reqHandlers.pop();
  775. if (isFunction(handler)) {
  776. handler.call(context, request, next);
  777. } else {
  778. warn('Invalid interceptor of type ' + typeof handler + ', must be a function');
  779. next();
  780. }
  781. }
  782. function next(response) {
  783. if (isFunction(response)) {
  784. resHandlers.unshift(response);
  785. } else if (isObject(response)) {
  786. resHandlers.forEach(function (handler) {
  787. response = when(response, function (response) {
  788. return handler.call(context, response) || response;
  789. });
  790. });
  791. when(response, resolve);
  792. return;
  793. }
  794. exec();
  795. }
  796. exec();
  797. }, context);
  798. }
  799. Client.use = function (handler) {
  800. reqHandlers.push(handler);
  801. };
  802. return Client;
  803. }
  804. function sendRequest(request, resolve) {
  805. var client = request.client || xhrClient;
  806. resolve(client(request));
  807. }
  808. var classCallCheck = function (instance, Constructor) {
  809. if (!(instance instanceof Constructor)) {
  810. throw new TypeError("Cannot call a class as a function");
  811. }
  812. };
  813. /**
  814. * HTTP Response.
  815. */
  816. var Response = function () {
  817. function Response(body, _ref) {
  818. var url = _ref.url;
  819. var headers = _ref.headers;
  820. var status = _ref.status;
  821. var statusText = _ref.statusText;
  822. classCallCheck(this, Response);
  823. this.url = url;
  824. this.body = body;
  825. this.headers = headers || {};
  826. this.status = status || 0;
  827. this.statusText = statusText || '';
  828. this.ok = status >= 200 && status < 300;
  829. }
  830. Response.prototype.text = function text() {
  831. return this.body;
  832. };
  833. Response.prototype.blob = function blob() {
  834. return new Blob([this.body]);
  835. };
  836. Response.prototype.json = function json() {
  837. return JSON.parse(this.body);
  838. };
  839. return Response;
  840. }();
  841. var Request = function () {
  842. function Request(options) {
  843. classCallCheck(this, Request);
  844. this.method = 'GET';
  845. this.body = null;
  846. this.params = {};
  847. this.headers = {};
  848. assign(this, options);
  849. }
  850. Request.prototype.getUrl = function getUrl() {
  851. return Url(this);
  852. };
  853. Request.prototype.getBody = function getBody() {
  854. return this.body;
  855. };
  856. Request.prototype.respondWith = function respondWith(body, options) {
  857. return new Response(body, assign(options || {}, { url: this.getUrl() }));
  858. };
  859. return Request;
  860. }();
  861. /**
  862. * Service for sending network requests.
  863. */
  864. var CUSTOM_HEADERS = { 'X-Requested-With': 'XMLHttpRequest' };
  865. var COMMON_HEADERS = { 'Accept': 'application/json, text/plain, */*' };
  866. var JSON_CONTENT_TYPE = { 'Content-Type': 'application/json;charset=utf-8' };
  867. function Http(options) {
  868. var self = this || {},
  869. client = Client(self.$vm);
  870. defaults(options || {}, self.$options, Http.options);
  871. Http.interceptors.forEach(function (handler) {
  872. client.use(handler);
  873. });
  874. return client(new Request(options)).then(function (response) {
  875. return response.ok ? response : Promise$1.reject(response);
  876. }, function (response) {
  877. if (response instanceof Error) {
  878. error(response);
  879. }
  880. return Promise$1.reject(response);
  881. });
  882. }
  883. Http.options = {};
  884. Http.headers = {
  885. put: JSON_CONTENT_TYPE,
  886. post: JSON_CONTENT_TYPE,
  887. patch: JSON_CONTENT_TYPE,
  888. delete: JSON_CONTENT_TYPE,
  889. custom: CUSTOM_HEADERS,
  890. common: COMMON_HEADERS
  891. };
  892. Http.interceptors = [before, timeout, method, body, jsonp, header, cors];
  893. ['get', 'delete', 'head', 'jsonp'].forEach(function (method) {
  894. Http[method] = function (url, options) {
  895. return this(assign(options || {}, { url: url, method: method }));
  896. };
  897. });
  898. ['post', 'put', 'patch'].forEach(function (method) {
  899. Http[method] = function (url, body, options) {
  900. return this(assign(options || {}, { url: url, method: method, body: body }));
  901. };
  902. });
  903. function Resource(url, params, actions, options) {
  904. var self = this || {},
  905. resource = {};
  906. actions = assign({}, Resource.actions, actions);
  907. each(actions, function (action, name) {
  908. action = merge({ url: url, params: params || {} }, options, action);
  909. resource[name] = function () {
  910. return (self.$http || Http)(opts(action, arguments));
  911. };
  912. });
  913. return resource;
  914. }
  915. function opts(action, args) {
  916. var options = assign({}, action),
  917. params = {},
  918. body;
  919. switch (args.length) {
  920. case 2:
  921. params = args[0];
  922. body = args[1];
  923. break;
  924. case 1:
  925. if (/^(POST|PUT|PATCH)$/i.test(options.method)) {
  926. body = args[0];
  927. } else {
  928. params = args[0];
  929. }
  930. break;
  931. case 0:
  932. break;
  933. default:
  934. throw 'Expected up to 4 arguments [params, body], got ' + args.length + ' arguments';
  935. }
  936. options.body = body;
  937. options.params = assign({}, options.params, params);
  938. return options;
  939. }
  940. Resource.actions = {
  941. get: { method: 'GET' },
  942. save: { method: 'POST' },
  943. query: { method: 'GET' },
  944. update: { method: 'PUT' },
  945. remove: { method: 'DELETE' },
  946. delete: { method: 'DELETE' }
  947. };
  948. function plugin(Vue) {
  949. if (plugin.installed) {
  950. return;
  951. }
  952. Util(Vue);
  953. Vue.url = Url;
  954. Vue.http = Http;
  955. Vue.resource = Resource;
  956. Vue.Promise = Promise$1;
  957. Object.defineProperties(Vue.prototype, {
  958. $url: {
  959. get: function () {
  960. return options(Vue.url, this, this.$options.url);
  961. }
  962. },
  963. $http: {
  964. get: function () {
  965. return options(Vue.http, this, this.$options.http);
  966. }
  967. },
  968. $resource: {
  969. get: function () {
  970. return Vue.resource.bind(this);
  971. }
  972. },
  973. $promise: {
  974. get: function () {
  975. var _this = this;
  976. return function (executor) {
  977. return new Vue.Promise(executor, _this);
  978. };
  979. }
  980. }
  981. });
  982. }
  983. if (typeof window !== 'undefined' && window.Vue) {
  984. window.Vue.use(plugin);
  985. }
  986. return plugin;
  987. }));