vue-resource.esm.js 35 KB

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