fetch-readablestream

https://github.com/jonnyreeves/fetch-readablestream/blob/master/README.md

当前为 2017-04-28 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/29306/191128/fetch-readablestream.js

  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.fetchStream = f()}})(function(){var define,module,exports;return (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<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. 'use strict';
  3.  
  4. Object.defineProperty(exports, "__esModule", {
  5. value: true
  6. });
  7. exports.default = defaultTransportFactory;
  8.  
  9. var _fetch = require('./fetch');
  10.  
  11. var _fetch2 = _interopRequireDefault(_fetch);
  12.  
  13. var _xhr = require('./xhr');
  14.  
  15. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  16.  
  17. // selected is used to cache the detected transport.
  18. var selected = null;
  19.  
  20. // defaultTransportFactory selects the most appropriate transport based on the
  21. // capabilities of the current environment.
  22. function defaultTransportFactory() {
  23. if (!selected) {
  24. selected = detectTransport();
  25. }
  26. return selected;
  27. }
  28.  
  29. function detectTransport() {
  30. if (typeof Response !== 'undefined' && Response.prototype.hasOwnProperty("body")) {
  31. // fetch with ReadableStream support.
  32. return _fetch2.default;
  33. }
  34.  
  35. var mozChunked = 'moz-chunked-arraybuffer';
  36. if (supportsXhrResponseType(mozChunked)) {
  37. // Firefox, ArrayBuffer support.
  38. return (0, _xhr.makeXhrTransport)({
  39. responseType: mozChunked,
  40. responseParserFactory: function responseParserFactory() {
  41. return function (response) {
  42. return new Uint8Array(response);
  43. };
  44. }
  45. });
  46. }
  47.  
  48. // Bog-standard, expensive, text concatenation with byte encoding :(
  49. return (0, _xhr.makeXhrTransport)({
  50. responseType: 'text',
  51. responseParserFactory: function responseParserFactory() {
  52. var encoder = new TextEncoder();
  53. var offset = 0;
  54. return function (response) {
  55. var chunk = response.substr(offset);
  56. offset = response.length;
  57. return encoder.encode(chunk, { stream: true });
  58. };
  59. }
  60. });
  61. }
  62.  
  63. function supportsXhrResponseType(type) {
  64. try {
  65. var tmpXhr = new XMLHttpRequest();
  66. tmpXhr.responseType = type;
  67. return tmpXhr.responseType === type;
  68. } catch (e) {/* IE throws on setting responseType to an unsupported value */}
  69. return false;
  70. }
  71. },{"./fetch":3,"./xhr":6}],2:[function(require,module,exports){
  72. module.exports = require("./index").default;
  73.  
  74. },{"./index":4}],3:[function(require,module,exports){
  75. "use strict";
  76.  
  77. Object.defineProperty(exports, "__esModule", {
  78. value: true
  79. });
  80. exports.default = fetchRequest;
  81. // thin wrapper around `fetch()` to ensure we only expose the properties provided by
  82. // the XHR polyfil; / fetch-readablestream Response API.
  83. function fetchRequest(url, options) {
  84. return fetch(url, options).then(function (r) {
  85. return {
  86. body: r.body,
  87. headers: r.headers,
  88. ok: r.ok,
  89. status: r.status,
  90. statusText: r.statusText,
  91. url: r.url
  92. };
  93. });
  94. }
  95. },{}],4:[function(require,module,exports){
  96. 'use strict';
  97.  
  98. Object.defineProperty(exports, "__esModule", {
  99. value: true
  100. });
  101. exports.default = fetchStream;
  102.  
  103. var _defaultTransportFactory = require('./defaultTransportFactory');
  104.  
  105. var _defaultTransportFactory2 = _interopRequireDefault(_defaultTransportFactory);
  106.  
  107. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  108.  
  109. function fetchStream(url) {
  110. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  111.  
  112. var transport = options.transport;
  113. if (!transport) {
  114. transport = fetchStream.transportFactory();
  115. }
  116.  
  117. return transport(url, options);
  118. }
  119.  
  120. // override this function to delegate to an alternative transport function selection
  121. // strategy; useful when testing.
  122. fetchStream.transportFactory = _defaultTransportFactory2.default;
  123. },{"./defaultTransportFactory":1}],5:[function(require,module,exports){
  124. "use strict";
  125.  
  126. Object.defineProperty(exports, "__esModule", {
  127. value: true
  128. });
  129.  
  130. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  131.  
  132. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  133.  
  134. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  135.  
  136. // Headers is a partial polyfill for the HTML5 Headers class.
  137. var Headers = exports.Headers = function () {
  138. function Headers() {
  139. var _this = this;
  140.  
  141. var h = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  142.  
  143. _classCallCheck(this, Headers);
  144.  
  145. this.h = {};
  146. if (h instanceof Headers) {
  147. h.forEach(function (value, key) {
  148. return _this.append(key, value);
  149. });
  150. }
  151. Object.getOwnPropertyNames(h).forEach(function (key) {
  152. return _this.append(key, h[key]);
  153. });
  154. }
  155.  
  156. _createClass(Headers, [{
  157. key: "append",
  158. value: function append(key, value) {
  159. key = key.toLowerCase();
  160. if (!Array.isArray(this.h[key])) {
  161. this.h[key] = [];
  162. }
  163. this.h[key].push(value);
  164. }
  165. }, {
  166. key: "set",
  167. value: function set(key, value) {
  168. this.h[key.toLowerCase()] = [value];
  169. }
  170. }, {
  171. key: "has",
  172. value: function has(key) {
  173. return Array.isArray(this.h[key.toLowerCase()]);
  174. }
  175. }, {
  176. key: "get",
  177. value: function get(key) {
  178. key = key.toLowerCase();
  179. if (Array.isArray(this.h[key])) {
  180. return this.h[key][0];
  181. }
  182. }
  183. }, {
  184. key: "getAll",
  185. value: function getAll(key) {
  186. return this.h[key.toLowerCase()].concat();
  187. }
  188. }, {
  189. key: "entries",
  190. value: function entries() {
  191. var items = [];
  192. this.forEach(function (value, key) {
  193. items.push([key, value]);
  194. });
  195. return makeIterator(items);
  196. }
  197.  
  198. // forEach is not part of the official spec.
  199.  
  200. }, {
  201. key: "forEach",
  202. value: function forEach(callback, thisArg) {
  203. var _this2 = this;
  204.  
  205. Object.getOwnPropertyNames(this.h).forEach(function (key) {
  206. _this2.h[key].forEach(function (value) {
  207. return callback.call(thisArg, value, key, _this2);
  208. });
  209. }, this);
  210. }
  211. }]);
  212.  
  213. return Headers;
  214. }();
  215.  
  216. function makeIterator(items) {
  217. return _defineProperty({
  218. next: function next() {
  219. var value = items.shift();
  220. return {
  221. done: value === undefined,
  222. value: value
  223. };
  224. }
  225. }, Symbol.iterator, function () {
  226. return this;
  227. });
  228. }
  229. },{}],6:[function(require,module,exports){
  230. 'use strict';
  231.  
  232. Object.defineProperty(exports, "__esModule", {
  233. value: true
  234. });
  235. exports.makeXhrTransport = makeXhrTransport;
  236. exports.parseResposneHeaders = parseResposneHeaders;
  237.  
  238. var _Headers = require('./polyfill/Headers');
  239.  
  240. function makeXhrTransport(_ref) {
  241. var responseType = _ref.responseType;
  242. var responseParserFactory = _ref.responseParserFactory;
  243.  
  244. return function xhrTransport(url, options) {
  245. var xhr = new XMLHttpRequest();
  246. var responseParser = responseParserFactory();
  247.  
  248. var responseStreamController = void 0;
  249. var cancelled = false;
  250.  
  251. var responseStream = new ReadableStream({
  252. start: function start(c) {
  253. responseStreamController = c;
  254. },
  255. cancel: function cancel() {
  256. cancelled = true;
  257. xhr.abort();
  258. }
  259. });
  260.  
  261. var _options$method = options.method;
  262. var method = _options$method === undefined ? 'GET' : _options$method;
  263.  
  264.  
  265. xhr.open(method, url);
  266. xhr.responseType = responseType;
  267. xhr.withCredentials = options.credentials !== 'omit';
  268. if (options.headers) {
  269. var _iteratorNormalCompletion = true;
  270. var _didIteratorError = false;
  271. var _iteratorError = undefined;
  272.  
  273. try {
  274. for (var _iterator = options.headers.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  275. var pair = _step.value;
  276.  
  277. xhr.setRequestHeader(pair[0], pair[1]);
  278. }
  279. } catch (err) {
  280. _didIteratorError = true;
  281. _iteratorError = err;
  282. } finally {
  283. try {
  284. if (!_iteratorNormalCompletion && _iterator.return) {
  285. _iterator.return();
  286. }
  287. } finally {
  288. if (_didIteratorError) {
  289. throw _iteratorError;
  290. }
  291. }
  292. }
  293. }
  294.  
  295. return new Promise(function (resolve, reject) {
  296. if (options.body && (method === 'GET' || method === 'HEAD')) {
  297. reject(new TypeError("Failed to execute 'fetchStream' on 'Window': Request with GET/HEAD method cannot have body"));
  298. }
  299.  
  300. xhr.onreadystatechange = function () {
  301. if (xhr.readyState === xhr.HEADERS_RECEIVED) {
  302. return resolve({
  303. body: responseStream,
  304. headers: parseResposneHeaders(xhr.getAllResponseHeaders()),
  305. ok: xhr.status >= 200 && xhr.status < 300,
  306. status: xhr.status,
  307. statusText: xhr.statusText,
  308. url: makeResponseUrl(xhr.responseURL, url)
  309. });
  310. }
  311. };
  312.  
  313. xhr.onerror = function () {
  314. return reject(new TypeError('Network request failed'));
  315. };
  316.  
  317. xhr.ontimeout = function () {
  318. reject(new TypeError('Network request failed'));
  319. };
  320.  
  321. xhr.onprogress = function () {
  322. if (!cancelled) {
  323. var bytes = responseParser(xhr.response);
  324. responseStreamController.enqueue(bytes);
  325. }
  326. };
  327.  
  328. xhr.onload = function () {
  329. responseStreamController.close();
  330. };
  331.  
  332. xhr.send(options.body);
  333. });
  334. };
  335. }
  336.  
  337. function makeHeaders() {
  338. // Prefer the native method if provided by the browser.
  339. if (typeof Headers !== 'undefined') {
  340. return new Headers();
  341. }
  342. return new _Headers.Headers();
  343. }
  344.  
  345. function makeResponseUrl(responseUrl, requestUrl) {
  346. if (!responseUrl) {
  347. // best guess; note this will not correctly handle redirects.
  348. if (requestUrl.substring(0, 4) !== "http") {
  349. return location.origin + requestUrl;
  350. }
  351. return requestUrl;
  352. }
  353. return responseUrl;
  354. }
  355.  
  356. function parseResposneHeaders(str) {
  357. var hdrs = makeHeaders();
  358. if (str) {
  359. var pairs = str.split('\r\n');
  360. for (var i = 0; i < pairs.length; i++) {
  361. var p = pairs[i];
  362. var index = p.indexOf(': ');
  363. if (index > 0) {
  364. var key = p.substring(0, index);
  365. var value = p.substring(index + 2);
  366. hdrs.append(key, value);
  367. }
  368. }
  369. }
  370. return hdrs;
  371. }
  372. },{"./polyfill/Headers":5}]},{},[2])(2)
  373. });