| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942 |
- /**
- * polyfills.js — IE11 / 老浏览器兼容垫片
- * ES5 语法,离线内置,无外部依赖。
- *
- * 提供:
- * String: padStart / startsWith / endsWith / includes
- * Array: includes
- * Object: assign
- * Promise: then / catch / finally / all / race / resolve / reject
- * fetch: 基于 XMLHttpRequest
- * EventSource: 基于 XMLHttpRequest,支持 SSE 消息解析和断线重连
- *
- * 注意:
- * 1. 本文件应在业务 JS 之前加载。
- * 2. fetch 和 EventSource 是兼容实现,不保证与原生 API 完全一致。
- * 3. downloadBlobFile() 保留在 util.js,不放在这里。
- */
- (function (global) {
- "use strict";
- /* =========================================================
- * String / Array / Object
- * ========================================================= */
- if (!String.prototype.padStart) {
- String.prototype.padStart = function (targetLength, padString) {
- var str = String(this);
- var len = Number(targetLength) || 0;
- var pad = padString === undefined ? " " : String(padString);
- var need = len - str.length;
- var result = "";
- if (need <= 0) return str;
- if (pad === "") return str;
- while (result.length < need) {
- result += pad;
- }
- return result.slice(0, need) + str;
- };
- }
- if (!String.prototype.startsWith) {
- String.prototype.startsWith = function (search, position) {
- var str = String(this);
- var pos = Number(position) || 0;
- search = String(search);
- if (pos < 0) pos = 0;
- return str.substr(pos, search.length) === search;
- };
- }
- if (!String.prototype.endsWith) {
- String.prototype.endsWith = function (search, length) {
- var str = String(this);
- search = String(search);
- if (length === undefined || length > str.length) {
- length = str.length;
- }
- length = Number(length);
- if (isNaN(length) || length < 0) length = 0;
- return str.substring(length - search.length, length) === search;
- };
- }
- if (!String.prototype.includes) {
- String.prototype.includes = function (search, start) {
- if (search instanceof RegExp) {
- throw new TypeError("不支持将 RegExp 作为 includes 参数");
- }
- return String(this).indexOf(String(search), Number(start) || 0) !== -1;
- };
- }
- if (!Array.prototype.includes) {
- Array.prototype.includes = function (search, fromIndex) {
- var arr = Object(this);
- var len = arr.length >>> 0;
- var i = Number(fromIndex) || 0;
- if (!len) return false;
- if (i < 0) {
- i = Math.max(len + i, 0);
- }
- for (; i < len; i++) {
- if (arr[i] === search ||
- (arr[i] !== arr[i] && search !== search)) {
- return true;
- }
- }
- return false;
- };
- }
- if (!Object.assign) {
- Object.assign = function (target) {
- if (target == null) {
- throw new TypeError("Object.assign 的目标不能为 null 或 undefined");
- }
- var to = Object(target);
- var i;
- var source;
- var key;
- for (i = 1; i < arguments.length; i++) {
- source = arguments[i];
- if (source == null) continue;
- source = Object(source);
- for (key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- to[key] = source[key];
- }
- }
- }
- return to;
- };
- }
- /* =========================================================
- * Promise
- * ========================================================= */
- if (!global.Promise) {
- var PENDING = 0;
- var FULFILLED = 1;
- var REJECTED = 2;
- function flushLater(fn) {
- setTimeout(fn, 0);
- }
- function isObjectOrFunction(value) {
- return value !== null &&
- (typeof value === "object" || typeof value === "function");
- }
- function settle(promise, state, value) {
- if (promise._state !== PENDING) return;
- if (state === FULFILLED && value === promise) {
- settle(promise, REJECTED, new TypeError("Promise 不能解决为自身"));
- return;
- }
- if (state === FULFILLED && isObjectOrFunction(value)) {
- var then;
- var called = false;
- try {
- then = value.then;
- } catch (err) {
- settle(promise, REJECTED, err);
- return;
- }
- if (typeof then === "function") {
- try {
- then.call(
- value,
- function (result) {
- if (called) return;
- called = true;
- settle(promise, FULFILLED, result);
- },
- function (reason) {
- if (called) return;
- called = true;
- settle(promise, REJECTED, reason);
- }
- );
- } catch (err2) {
- if (!called) {
- called = true;
- settle(promise, REJECTED, err2);
- }
- }
- return;
- }
- }
- promise._state = state;
- promise._value = value;
- if (promise._handlers.length) {
- flushLater(function () {
- flushHandlers(promise);
- });
- }
- }
- function flushHandlers(promise) {
- var handlers = promise._handlers.slice();
- var i;
- var handler;
- var callback;
- var result;
- promise._handlers = [];
- for (i = 0; i < handlers.length; i++) {
- handler = handlers[i];
- callback = promise._state === FULFILLED
- ? handler.onFulfilled
- : handler.onRejected;
- if (typeof callback !== "function") {
- if (promise._state === FULFILLED) {
- settle(handler.next, FULFILLED, promise._value);
- } else {
- settle(handler.next, REJECTED, promise._value);
- }
- continue;
- }
- try {
- result = callback(promise._value);
- settle(handler.next, FULFILLED, result);
- } catch (err) {
- settle(handler.next, REJECTED, err);
- }
- }
- }
- function PromisePolyfill(executor) {
- if (!(this instanceof PromisePolyfill)) {
- throw new TypeError("Promise 必须通过 new 调用");
- }
- if (typeof executor !== "function") {
- throw new TypeError("Promise executor 必须是函数");
- }
- this._state = PENDING;
- this._value = undefined;
- this._handlers = [];
- var self = this;
- var done = false;
- function resolve(value) {
- if (done) return;
- done = true;
- settle(self, FULFILLED, value);
- }
- function reject(reason) {
- if (done) return;
- done = true;
- settle(self, REJECTED, reason);
- }
- try {
- executor(resolve, reject);
- } catch (err) {
- reject(err);
- }
- }
- PromisePolyfill.prototype.then = function (onFulfilled, onRejected) {
- var next = new PromisePolyfill(function () {});
- this._handlers.push({
- onFulfilled: onFulfilled,
- onRejected: onRejected,
- next: next
- });
- if (this._state !== PENDING) {
- var self = this;
- flushLater(function () {
- flushHandlers(self);
- });
- }
- return next;
- };
- PromisePolyfill.prototype["catch"] = function (onRejected) {
- return this.then(null, onRejected);
- };
- PromisePolyfill.prototype["finally"] = function (callback) {
- var P = this.constructor || PromisePolyfill;
- if (typeof callback !== "function") {
- return this.then(callback, callback);
- }
- return this.then(
- function (value) {
- return P.resolve(callback()).then(function () {
- return value;
- });
- },
- function (reason) {
- return P.resolve(callback()).then(function () {
- throw reason;
- });
- }
- );
- };
- PromisePolyfill.resolve = function (value) {
- if (value instanceof PromisePolyfill) return value;
- return new PromisePolyfill(function (resolve) {
- resolve(value);
- });
- };
- PromisePolyfill.reject = function (reason) {
- return new PromisePolyfill(function (resolve, reject) {
- reject(reason);
- });
- };
- PromisePolyfill.all = function (items) {
- return new PromisePolyfill(function (resolve, reject) {
- var list;
- var results = [];
- var remaining;
- var i;
- try {
- list = Array.prototype.slice.call(items);
- } catch (err) {
- reject(err);
- return;
- }
- if (!list.length) {
- resolve([]);
- return;
- }
- remaining = list.length;
- function makeResolver(index) {
- return function (value) {
- results[index] = value;
- remaining--;
- if (remaining === 0) {
- resolve(results);
- }
- };
- }
- for (i = 0; i < list.length; i++) {
- PromisePolyfill.resolve(list[i]).then(
- makeResolver(i),
- reject
- );
- }
- });
- };
- PromisePolyfill.race = function (items) {
- return new PromisePolyfill(function (resolve, reject) {
- var list;
- var i;
- try {
- list = Array.prototype.slice.call(items);
- } catch (err) {
- reject(err);
- return;
- }
- for (i = 0; i < list.length; i++) {
- PromisePolyfill.resolve(list[i]).then(resolve, reject);
- }
- });
- };
- global.Promise = PromisePolyfill;
- }
- /* =========================================================
- * fetch — 基于 XMLHttpRequest
- * ========================================================= */
- if (!global.fetch && global.XMLHttpRequest) {
- function HeadersPolyfill(headers) {
- this._headers = {};
- var key;
- var value;
- var i;
- if (!headers) return;
- if (typeof headers.forEach === "function") {
- var self = this;
- headers.forEach(function (v, k) {
- self.append(k, v);
- });
- } else if (Object.prototype.toString.call(headers) === "[object Array]") {
- for (i = 0; i < headers.length; i++) {
- if (headers[i] && headers[i].length >= 2) {
- this.append(headers[i][0], headers[i][1]);
- }
- }
- } else {
- for (key in headers) {
- if (Object.prototype.hasOwnProperty.call(headers, key)) {
- value = headers[key];
- this.append(key, value);
- }
- }
- }
- }
- HeadersPolyfill.prototype.append = function (name, value) {
- name = String(name).toLowerCase();
- value = String(value);
- if (this._headers[name]) {
- this._headers[name] += ", " + value;
- } else {
- this._headers[name] = value;
- }
- };
- HeadersPolyfill.prototype.set = function (name, value) {
- this._headers[String(name).toLowerCase()] = String(value);
- };
- HeadersPolyfill.prototype.get = function (name) {
- var value = this._headers[String(name).toLowerCase()];
- return value === undefined ? null : value;
- };
- HeadersPolyfill.prototype.has = function (name) {
- return Object.prototype.hasOwnProperty.call(
- this._headers,
- String(name).toLowerCase()
- );
- };
- HeadersPolyfill.prototype["delete"] = function (name) {
- delete this._headers[String(name).toLowerCase()];
- };
- HeadersPolyfill.prototype.forEach = function (callback, thisArg) {
- var key;
- for (key in this._headers) {
- if (Object.prototype.hasOwnProperty.call(this._headers, key)) {
- callback.call(thisArg, this._headers[key], key, this);
- }
- }
- };
- function parseResponseHeaders(raw) {
- var headers = new HeadersPolyfill();
- var lines = raw ? raw.split(/\r?\n/) : [];
- var i;
- var index;
- for (i = 0; i < lines.length; i++) {
- index = lines[i].indexOf(":");
- if (index > 0) {
- headers.append(
- lines[i].substring(0, index).replace(/^\s+|\s+$/g, ""),
- lines[i].substring(index + 1).replace(/^\s+|\s+$/g, "")
- );
- }
- }
- return headers;
- }
- function ResponsePolyfill(xhr) {
- this.status = xhr.status === 1223 ? 204 : xhr.status;
- this.statusText = xhr.statusText || "";
- this.ok = this.status >= 200 && this.status < 300;
- this.url = xhr.responseURL || "";
- this.headers = parseResponseHeaders(xhr.getAllResponseHeaders());
- this._xhr = xhr;
- this._bodyUsed = false;
- }
- ResponsePolyfill.prototype.text = function () {
- var xhr = this._xhr;
- return Promise.resolve(xhr.responseText || "");
- };
- ResponsePolyfill.prototype.json = function () {
- return this.text().then(function (text) {
- return JSON.parse(text);
- });
- };
- ResponsePolyfill.prototype.blob = function () {
- var xhr = this._xhr;
- if (xhr.response && typeof xhr.response !== "string") {
- return Promise.resolve(xhr.response);
- }
- if (global.Blob) {
- return Promise.resolve(new Blob([xhr.responseText || ""], {
- type: this.headers.get("content-type") || ""
- }));
- }
- return Promise.reject(new Error("当前浏览器不支持 Blob"));
- };
- ResponsePolyfill.prototype.clone = function () {
- return new ResponsePolyfill(this._xhr);
- };
- global.Headers = global.Headers || HeadersPolyfill;
- global.Response = global.Response || ResponsePolyfill;
- global.fetch = function (input, init) {
- return new Promise(function (resolve, reject) {
- var options = init || {};
- var url = typeof input === "string" ? input : input.url;
- var method = options.method || "GET";
- var xhr = new XMLHttpRequest();
- var headers = new HeadersPolyfill(options.headers);
- var body = options.body === undefined ? null : options.body;
- var key;
- var settled = false;
- function fail(err) {
- if (settled) return;
- settled = true;
- reject(err);
- }
- try {
- xhr.open(method, url, true);
- if (options.credentials === "include") {
- xhr.withCredentials = true;
- } else if (options.credentials === "same-origin") {
- xhr.withCredentials = false;
- }
- if (options.responseType && options.responseType !== "text") {
- try {
- xhr.responseType = options.responseType;
- } catch (ignore) {}
- }
- headers.forEach(function (value, name) {
- xhr.setRequestHeader(name, value);
- });
- xhr.onload = function () {
- if (settled) return;
- settled = true;
- if (xhr.status === 0) {
- reject(new TypeError("网络请求失败"));
- return;
- }
- resolve(new ResponsePolyfill(xhr));
- };
- xhr.onerror = function () {
- fail(new TypeError("网络请求失败"));
- };
- xhr.ontimeout = function () {
- fail(new TypeError("网络请求超时"));
- };
- xhr.onabort = function () {
- fail(new TypeError("网络请求已取消"));
- };
- if (options.timeout) {
- xhr.timeout = options.timeout;
- }
- xhr.send(body);
- } catch (err) {
- fail(err);
- }
- });
- };
- }
- /* =========================================================
- * EventSource — 基于 XMLHttpRequest 的 SSE 兼容实现
- * ========================================================= */
- if (!global.EventSource && global.XMLHttpRequest) {
- function EventSourcePolyfill(url, options) {
- if (!(this instanceof EventSourcePolyfill)) {
- throw new TypeError("EventSource 必须通过 new 调用");
- }
- if (!url) {
- throw new TypeError("EventSource URL 不能为空");
- }
- this.url = String(url);
- this.withCredentials = !!(options && options.withCredentials);
- this.CONNECTING = 0;
- this.OPEN = 1;
- this.CLOSED = 2;
- this.readyState = this.CONNECTING;
- this.onopen = null;
- this.onmessage = null;
- this.onerror = null;
- this._xhr = null;
- this._timer = null;
- this._closed = false;
- this._retry = 3000;
- this._lastEventId = "";
- this._buffer = "";
- this._listeners = {};
- this._connect();
- }
- EventSourcePolyfill.prototype.addEventListener = function (type, listener) {
- if (typeof listener !== "function") return;
- if (!this._listeners[type]) {
- this._listeners[type] = [];
- }
- this._listeners[type].push(listener);
- };
- EventSourcePolyfill.prototype.removeEventListener = function (type, listener) {
- var list = this._listeners[type];
- var i;
- if (!list) return;
- for (i = list.length - 1; i >= 0; i--) {
- if (list[i] === listener) {
- list.splice(i, 1);
- }
- }
- };
- EventSourcePolyfill.prototype.dispatchEvent = function (event) {
- var list = this._listeners[event.type] || [];
- var i;
- if (typeof this["on" + event.type] === "function") {
- try {
- this["on" + event.type].call(this, event);
- } catch (ignore) {}
- }
- list = list.slice();
- for (i = 0; i < list.length; i++) {
- try {
- list[i].call(this, event);
- } catch (ignore2) {}
- }
- return true;
- };
- EventSourcePolyfill.prototype._emit = function (type, data, lastEventId) {
- var event = {
- type: type,
- data: data === undefined ? "" : data,
- lastEventId: lastEventId || "",
- origin: "",
- target: this
- };
- event.preventDefault = function () {};
- event.stopPropagation = function () {};
- this.dispatchEvent(event);
- };
- EventSourcePolyfill.prototype._connect = function () {
- var self = this;
- var xhr;
- var lastLength = 0;
- var finished = false;
- if (this._closed) return;
- try {
- xhr = new XMLHttpRequest();
- this._xhr = xhr;
- this._buffer = "";
- xhr.open("GET", this.url, true);
- xhr.setRequestHeader("Accept", "text/event-stream");
- xhr.setRequestHeader("Cache-Control", "no-cache");
- if (this._lastEventId) {
- xhr.setRequestHeader("Last-Event-ID", this._lastEventId);
- }
- xhr.withCredentials = this.withCredentials;
- function readData() {
- var text;
- var chunk;
- try {
- text = xhr.responseText || "";
- } catch (ignore) {
- return;
- }
- if (text.length < lastLength) {
- lastLength = 0;
- self._buffer = "";
- }
- if (text.length <= lastLength) return;
- chunk = text.substring(lastLength);
- lastLength = text.length;
- self._buffer += chunk;
- self._parseBuffer(false);
- }
- xhr.onreadystatechange = function () {
- if (self._closed || finished) return;
- if (xhr.readyState === 2 || xhr.readyState === 3) {
- if (xhr.status >= 200 && xhr.status < 300) {
- if (self.readyState !== self.OPEN) {
- self.readyState = self.OPEN;
- self._emit("open");
- }
- if (xhr.readyState === 3) {
- readData();
- }
- } else if (xhr.readyState === 2) {
- finished = true;
- self._handleError();
- }
- }
- if (xhr.readyState === 4) {
- readData();
- if (!self._closed) {
- finished = true;
- self._parseBuffer(true);
- self._handleError();
- }
- }
- };
- xhr.onerror = function () {
- if (self._closed || finished) return;
- finished = true;
- self._handleError();
- };
- xhr.ontimeout = function () {
- if (self._closed || finished) return;
- finished = true;
- self._handleError();
- };
- xhr.send(null);
- } catch (err) {
- this._handleError();
- }
- };
- EventSourcePolyfill.prototype._parseBuffer = function (flush) {
- var index;
- var line;
- var fields;
- var i;
- var field;
- var value;
- var data = [];
- var eventType = "";
- var eventId = this._lastEventId;
- var retry = null;
- while ((index = this._buffer.indexOf("\n")) !== -1) {
- line = this._buffer.substring(0, index);
- this._buffer = this._buffer.substring(index + 1);
- if (line.charAt(line.length - 1) === "\r") {
- line = line.substring(0, line.length - 1);
- }
- if (line === "") {
- if (data.length) {
- this._lastEventId = eventId;
- this._emit(
- eventType || "message",
- data.join("\n"),
- eventId
- );
- }
- data = [];
- eventType = "";
- eventId = this._lastEventId;
- continue;
- }
- if (line.charAt(0) === ":") continue;
- fields = line.split(":");
- field = fields.shift();
- value = fields.join(":");
- if (value.charAt(0) === " ") {
- value = value.substring(1);
- }
- if (field === "data") {
- data.push(value);
- } else if (field === "event") {
- eventType = value;
- } else if (field === "id" && value.indexOf("\0") === -1) {
- eventId = value;
- } else if (field === "retry") {
- if (/^\d+$/.test(value)) {
- retry = parseInt(value, 10);
- }
- }
- }
- if (retry !== null && retry >= 0) {
- this._retry = retry;
- }
- if (flush && this._buffer) {
- line = this._buffer;
- this._buffer = "";
- if (line.charAt(line.length - 1) === "\r") {
- line = line.substring(0, line.length - 1);
- }
- if (line.indexOf(":") !== 0) {
- fields = line.split(":");
- field = fields.shift();
- value = fields.join(":");
- if (value.charAt(0) === " ") {
- value = value.substring(1);
- }
- if (field === "data") {
- data.push(value);
- } else if (field === "event") {
- eventType = value;
- } else if (field === "id" && value.indexOf("\0") === -1) {
- eventId = value;
- } else if (field === "retry" && /^\d+$/.test(value)) {
- this._retry = parseInt(value, 10);
- }
- }
- if (data.length) {
- this._lastEventId = eventId;
- this._emit(
- eventType || "message",
- data.join("\n"),
- eventId
- );
- }
- }
- };
- EventSourcePolyfill.prototype._handleError = function () {
- var self = this;
- if (this._closed) return;
- this.readyState = this.CONNECTING;
- this._emit("error");
- if (this._timer) {
- clearTimeout(this._timer);
- }
- this._timer = setTimeout(function () {
- self._timer = null;
- self._connect();
- }, this._retry);
- };
- EventSourcePolyfill.prototype.close = function () {
- this._closed = true;
- this.readyState = this.CLOSED;
- if (this._timer) {
- clearTimeout(this._timer);
- this._timer = null;
- }
- if (this._xhr) {
- try {
- this._xhr.onreadystatechange = null;
- this._xhr.onerror = null;
- this._xhr.abort();
- } catch (ignore) {}
- this._xhr = null;
- }
- };
- global.EventSource = EventSourcePolyfill;
- }
- })(window);
|