Socket
Socket
Sign inDemoInstall

xgplayer-streaming-shared

Package Overview
Dependencies
Maintainers
5
Versions
203
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

xgplayer-streaming-shared - npm Package Compare versions

Comparing version 3.0.0-alpha.5 to 3.0.0-alpha.19

es/_virtual/_rollupPluginBabelHelpers.js

143

es/buffer.js

@@ -1,77 +0,54 @@

import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
var Buffer = /*#__PURE__*/function () {
function Buffer() {
_classCallCheck(this, Buffer);
import { createClass as _createClass, classCallCheck as _classCallCheck } from "./_virtual/_rollupPluginBabelHelpers.js";
import "core-js/modules/es.array.push.js";
import "core-js/modules/es.object.to-string.js";
var Buffer = /* @__PURE__ */ function() {
function Buffer2() {
_classCallCheck(this, Buffer2);
}
_createClass(Buffer, null, [{
_createClass(Buffer2, null, [{
key: "start",
value:
/**
* @param {TimeRanges} buf
* @returns {number}
*/
function start(buf) {
if (!buf || !buf.length) return 0; // Safari bug: https://bit.ly/2trx6O8
if (buf.length === 1 && buf.end(0) - buf.start(0) < 1e-6) return 0; // Edge bug: https://bit.ly/2JYLPeB
if (buf.length === 1 && buf.start(0) < 0) return 0;
value: function start(buf) {
if (!buf || !buf.length)
return 0;
if (buf.length === 1 && buf.end(0) - buf.start(0) < 1e-6)
return 0;
if (buf.length === 1 && buf.start(0) < 0)
return 0;
return buf.start(0);
}
/**
* @param {TimeRanges} buf
* @returns {number}
*/
}, {
key: "end",
value: function end(buf) {
if (!buf || !buf.length) return 0; // Safari bug: https://bit.ly/2trx6O8
if (buf.length === 1 && buf.end(0) - buf.start(0) < 1e-6) return 0;
if (!buf || !buf.length)
return 0;
if (buf.length === 1 && buf.end(0) - buf.start(0) < 1e-6)
return 0;
return buf.end(buf.length - 1);
}
/**
* @param {{buffered?: TimeRanges}} b
* @returns {TimeRanges | void}
*/
}, {
key: "get",
value: function get(b) {
if (!b) return;
if (!b)
return;
try {
return b.buffered;
} catch (error) {// ignore
} catch (error) {
}
}
/**
* @param {TimeRanges} buf
* @param {number} [maxHole]
* @returns {[number,number][]}
*/
}, {
key: "buffers",
value: function buffers(buf, maxHole) {
if (!buf || !buf.length) return [];
var buffers = [];
if (!buf || !buf.length)
return [];
var buffers2 = [];
for (var i = 0, l = buf.length; i < l; i++) {
var bufLen = buffers.length;
var bufLen = buffers2.length;
if (!bufLen || !maxHole) {
buffers.push([buf.start(i), buf.end(i)]);
buffers2.push([buf.start(i), buf.end(i)]);
} else {
var last = buffers[bufLen - 1];
var last = buffers2[bufLen - 1];
var lastEnd = last[1];
var start = buf.start(i);
if (start - lastEnd <= maxHole) {
var end = buf.end(i);
if (end > lastEnd) {

@@ -81,41 +58,28 @@ last[1] = end;

} else {
buffers.push([buf.start(i), buf.end(i)]);
buffers2.push([buf.start(i), buf.end(i)]);
}
}
}
return buffers;
return buffers2;
}
/**
* @param {TimeRanges} buf
* @param {number} [maxHole]
* @returns {{buffers:[number,number][],length:number}}
*/
}, {
key: "length",
value: function length(buffers) {
if (!buffers || !buffers.length) return 0;
return buffers.reduce(function (a, c) {
if (!buffers || !buffers.length)
return 0;
return buffers.reduce(function(a, c) {
return a += c[1] - c[0];
}, 0);
}
/**
*
* @param {TimeRanges} buf
* @param {number} [pos=0]
* @param {number} [maxHole=0]
* @returns {{start:number,end:number,buffers:[number,number][],index?:number,nextStart?:number,nextEnd?:number,prevStart?:number,prevEnd?:number}}
*/
}, {
key: "info",
value: function info(buf) {
var pos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var maxHole = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
if (!buf || !buf.length) return {
start: 0,
end: 0,
buffers: []
};
var pos = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
var maxHole = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0;
if (!buf || !buf.length)
return {
start: 0,
end: 0,
buffers: []
};
var start = 0;

@@ -128,7 +92,5 @@ var end = 0;

var prevEnd = 0;
var buffers = Buffer.buffers(buf, maxHole);
var buffers = Buffer2.buffers(buf, maxHole);
for (var i = 0, l = buffers.length; i < l; i++) {
var item = buffers[i];
if (pos + maxHole >= item[0] && pos < item[1]) {

@@ -147,23 +109,20 @@ start = item[0];

}
return {
start: start,
end: end,
index: index,
buffers: buffers,
nextStart: nextStart,
nextEnd: nextEnd,
prevStart: prevStart,
prevEnd: prevEnd,
start,
end,
index,
buffers,
nextStart,
nextEnd,
prevStart,
prevEnd,
currentTime: pos,
behind: pos - start,
remaining: end ? end - pos : 0,
length: Buffer.length(buffers)
length: Buffer2.length && Buffer2.length(buffers)
};
}
}]);
return Buffer;
return Buffer2;
}();
export { Buffer };
export namespace ERR {
const MANIFEST: string;
const NETWORK: string;
const NETWORK_TIMEOUT: string;
const OPTION: string;
const M3U8: string;
const DEMUX: string;
const REMUX: string;
const MSE: string;
const DECRYPT: string;
const MEDIA: string;
const DRM: string;
const OTHER: string;
namespace SUB_TYPES {
const FLV: string;
const HLS: string;
const MP4: string;
const FMP4: string;
const MSE_ADD_SB: string;
const MSE_APPEND_BUFFER: string;
const MSE_OTHER: string;
const OPTION: string;
}
}
export const ERR_CODE: {
[x: string]: number;
[x: string]: number | {
HLS: number;
FLV?: undefined;
MP4?: undefined;
FMP4?: undefined;
MSE_ADD_SB?: undefined;
MSE_APPEND_BUFFER?: undefined;
MSE_OTHER?: undefined;
} | {
FLV: number;
HLS: number;
MP4: number;
FMP4: number;
MSE_ADD_SB?: undefined;
MSE_APPEND_BUFFER?: undefined;
MSE_OTHER?: undefined;
} | {
FMP4: number;
MP4: number;
HLS?: undefined;
FLV?: undefined;
MSE_ADD_SB?: undefined;
MSE_APPEND_BUFFER?: undefined;
MSE_OTHER?: undefined;
} | {
MSE_ADD_SB: number;
MSE_APPEND_BUFFER: number;
MSE_OTHER: number;
HLS?: undefined;
FLV?: undefined;
MP4?: undefined;
FMP4?: undefined;
};
};
export class StreamingError extends Error {
static create(type: any, origin: any, payload: any, msg: any): StreamingError;
export class StreamingError {
static create(type: any, subType: any, origin: any, payload: any, msg: any): StreamingError;
static network(error: any): StreamingError;
constructor(type: any, origin: any, payload: any, msg: any);
constructor(type: any, subType: any, origin: any, payload: any, msg: any);
errorType: any;
originError: any;
ext: any;
errorCode: number;
errorMessage: string;
errorCode: any;
errorMessage: any;
}

@@ -1,38 +0,45 @@

import 'core-js/modules/es.reflect.construct.js';
import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import _inherits from '@babel/runtime/helpers/inherits';
import _possibleConstructorReturn from '@babel/runtime/helpers/possibleConstructorReturn';
import _getPrototypeOf from '@babel/runtime/helpers/getPrototypeOf';
import _wrapNativeSuper from '@babel/runtime/helpers/wrapNativeSuper';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import { defineProperty as _defineProperty, inherits as _inherits, createSuper as _createSuper, createClass as _createClass, classCallCheck as _classCallCheck, wrapNativeSuper as _wrapNativeSuper } from "./_virtual/_rollupPluginBabelHelpers.js";
import "core-js/modules/es.error.cause.js";
var _ERR_CODE;
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var ERR = {
NETWORK: 'network',
NETWORK_TIMEOUT: 'network_timeout',
OPTION: 'option',
M3U8: 'm3u8',
DEMUX: 'demux',
REMUX: 'remux',
MSE: 'mse',
DECRYPT: 'decrypt',
OTHER: 'other'
MANIFEST: "manifest",
NETWORK: "network",
NETWORK_TIMEOUT: "network_timeout",
DEMUX: "demux",
REMUX: "remux",
MEDIA: "media",
DRM: "drm",
OTHER: "other",
SUB_TYPES: {
FLV: "FLV",
HLS: "HLS",
MP4: "MP4",
FMP4: "FMP4",
MSE_ADD_SB: "MSE_ADD_SB",
MSE_APPEND_BUFFER: "MSE_APPEND_BUFFER",
MSE_OTHER: "MSE_OTHER",
OPTION: "OPTION"
}
};
var ERR_CODE = (_ERR_CODE = {}, _defineProperty(_ERR_CODE, ERR.OPTION, 500), _defineProperty(_ERR_CODE, ERR.NETWORK, 600), _defineProperty(_ERR_CODE, ERR.NETWORK_TIMEOUT, 601), _defineProperty(_ERR_CODE, ERR.M3U8, 900), _defineProperty(_ERR_CODE, ERR.DEMUX, 700), _defineProperty(_ERR_CODE, ERR.DECRYPT, 701), _defineProperty(_ERR_CODE, ERR.REMUX, 800), _defineProperty(_ERR_CODE, ERR.MSE, 1000), _defineProperty(_ERR_CODE, ERR.OTHER, 999), _ERR_CODE);
var StreamingError = /*#__PURE__*/function (_Error) {
_inherits(StreamingError, _Error);
var _super = _createSuper(StreamingError);
function StreamingError(type, origin, payload, msg) {
var ERR_CODE = (_ERR_CODE = {}, _defineProperty(_ERR_CODE, ERR.MANIFEST, {
HLS: 1100
}), _defineProperty(_ERR_CODE, ERR.NETWORK, 2100), _defineProperty(_ERR_CODE, ERR.NETWORK_TIMEOUT, 2101), _defineProperty(_ERR_CODE, ERR.DEMUX, {
FLV: 3100,
HLS: 3200,
MP4: 3300,
FMP4: 3400
}), _defineProperty(_ERR_CODE, ERR.REMUX, {
FMP4: 4100,
MP4: 4200
}), _defineProperty(_ERR_CODE, ERR.MEDIA, {
MSE_ADD_SB: 5200,
MSE_APPEND_BUFFER: 5201,
MSE_OTHER: 5202
}), _defineProperty(_ERR_CODE, ERR.OTHER, 8e3), _ERR_CODE);
var StreamingError = /* @__PURE__ */ function(_Error) {
_inherits(StreamingError2, _Error);
var _super = _createSuper(StreamingError2);
function StreamingError2(type, subType, origin, payload, msg) {
var _this;
_classCallCheck(this, StreamingError);
_classCallCheck(this, StreamingError2);
_this = _super.call(this, msg || (origin === null || origin === void 0 ? void 0 : origin.message));

@@ -42,5 +49,4 @@ _this.errorType = type === ERR.NETWORK_TIMEOUT ? ERR.NETWORK : type;

_this.ext = payload;
_this.errorCode = ERR_CODE[type];
_this.errorCode = ERR_CODE[type][subType] || ERR_CODE[type];
_this.errorMessage = _this.message;
if (!_this.errorCode) {

@@ -50,18 +56,16 @@ _this.errorType = ERR.OTHER;

}
return _this;
}
_createClass(StreamingError, null, [{
_createClass(StreamingError2, null, [{
key: "create",
value: function create(type, origin, payload, msg) {
if (type instanceof StreamingError) {
value: function create(type, subType, origin, payload, msg) {
if (type instanceof StreamingError2) {
return type;
} else if (type instanceof Error) {
origin = type;
type = '';
type = "";
}
if (!type) type = ERR.OTHER;
return new StreamingError(type, origin, payload, msg);
if (!type)
type = ERR.OTHER;
return new StreamingError2(type, subType, origin, payload, msg);
}

@@ -72,4 +76,3 @@ }, {

var _error$response;
return new StreamingError(error !== null && error !== void 0 && error.isTimeout ? ERR.NETWORK_TIMEOUT : ERR.NETWORK, error, {
return new StreamingError2(error !== null && error !== void 0 && error.isTimeout ? ERR.NETWORK_TIMEOUT : ERR.NETWORK, error, null, {
url: error === null || error === void 0 ? void 0 : error.url,

@@ -81,6 +84,4 @@ response: error === null || error === void 0 ? void 0 : error.response,

}]);
return StreamingError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
return StreamingError2;
}(/* @__PURE__ */ _wrapNativeSuper(Error));
export { ERR, ERR_CODE, StreamingError };
var EVENT = {
ERROR: 'error',
TTFB: 'core.ttfb',
LOAD_START: 'core.loadstart',
LOAD_RESPONSE_HEADERS: 'core.loadresponseheaders',
LOAD_COMPLETE: 'core.loadcomplete',
LOAD_RETRY: 'core.loadretry',
SOURCEBUFFER_CREATED: 'core.sourcebuffercreated',
ANALYZE_DURATION_EXCEEDED: 'core.analyzedurationexceeded',
REMOVE_BUFFER: 'core.removebuffer',
BUFFEREOS: 'core.buffereos',
KEYFRAME: 'core.keyframe',
METADATA_PARSED: 'core.metadataparsed',
SEI: 'core.sei',
SEI_IN_TIME: 'core.seiintime',
FLV_SCRIPT_DATA: 'core.flvscriptdata',
LOWDECODE: 'core.lowdecode',
SWITCH_URL_SUCCESS: 'core.switchurlsuccess',
SWITCH_URL_FAILED: 'core.switchurlfailed',
SPEED: 'core.speed',
HLS_MANIFEST_LOADED: 'core.hlsmanifestloaded',
HLS_LEVEL_LOADED: 'core.hlslevelloaded',
STREAM_EXCEPTION: 'core.streamexception',
LARGE_AV_FIRST_FRAME_GAP_DETECT: 'LARGE_AV_FIRST_FRAME_GAP_DETECT',
LARGE_VIDEO_DTS_GAP_DETECT: 'LARGE_VIDEO_DTS_GAP_DETECT',
LARGE_AUDIO_DTS_GAP_DETECT: 'LARGE_AUDIO_DTS_GAP_DETECT',
AUDIO_GAP_DETECT: 'AUDIO_GAP_DETECT',
AUDIO_OVERLAP_DETECT: 'AUDIO_OVERLAP_DETECT',
MAX_DTS_DELTA_WITH_NEXT_SEGMENT_DETECT: 'MAX_DTS_DELTA_WITH_NEXT_SEGMENT_DETECT'
ERROR: "error",
TTFB: "core.ttfb",
LOAD_START: "core.loadstart",
LOAD_RESPONSE_HEADERS: "core.loadresponseheaders",
LOAD_COMPLETE: "core.loadcomplete",
LOAD_RETRY: "core.loadretry",
SOURCEBUFFER_CREATED: "core.sourcebuffercreated",
ANALYZE_DURATION_EXCEEDED: "core.analyzedurationexceeded",
REMOVE_BUFFER: "core.removebuffer",
BUFFEREOS: "core.buffereos",
KEYFRAME: "core.keyframe",
METADATA_PARSED: "core.metadataparsed",
SEI: "core.sei",
SEI_IN_TIME: "core.seiintime",
FLV_SCRIPT_DATA: "core.flvscriptdata",
LOWDECODE: "core.lowdecode",
SWITCH_URL_SUCCESS: "core.switchurlsuccess",
SWITCH_URL_FAILED: "core.switchurlfailed",
SPEED: "core.speed",
HLS_MANIFEST_LOADED: "core.hlsmanifestloaded",
HLS_LEVEL_LOADED: "core.hlslevelloaded",
STREAM_EXCEPTION: "core.streamexception",
LARGE_AV_FIRST_FRAME_GAP_DETECT: "LARGE_AV_FIRST_FRAME_GAP_DETECT",
LARGE_VIDEO_DTS_GAP_DETECT: "LARGE_VIDEO_DTS_GAP_DETECT",
LARGE_AUDIO_DTS_GAP_DETECT: "LARGE_AUDIO_DTS_GAP_DETECT",
AUDIO_GAP_DETECT: "AUDIO_GAP_DETECT",
AUDIO_OVERLAP_DETECT: "AUDIO_OVERLAP_DETECT",
MAX_DTS_DELTA_WITH_NEXT_SEGMENT_DETECT: "MAX_DTS_DELTA_WITH_NEXT_SEGMENT_DETECT"
};
export { EVENT };

@@ -1,11 +0,11 @@

export { MSE, MSEError, MSEErrorType } from './mse.js';
export { Buffer } from './buffer.js';
export { NetLoader } from './net/index.js';
export { ERR, ERR_CODE, StreamingError } from './error.js';
export { EVENT } from './event.js';
export { concatUint8Array, getVideoPlaybackQuality, isMediaPlaying, softDecodeProbe } from './streaming-helper.js';
export { Logger } from './logger.js';
export { LoaderType, ResponseType } from './net/types.js';
export { GapService } from './services/gap.js';
export { SeiService } from './services/sei.js';
export { BandwidthService } from './services/bandwidth.js';
export { MSE, MSEError, MSEErrorType } from "./mse.js";
export { Buffer } from "./buffer.js";
export { NetLoader } from "./net/index.js";
export { ERR, ERR_CODE, StreamingError } from "./error.js";
export { EVENT } from "./event.js";
export { GapService } from "./services/gap.js";
export { SeiService } from "./services/sei.js";
export { BandwidthService } from "./services/bandwidth.js";
export { concatUint8Array, getVideoPlaybackQuality, isMediaPlaying, sleep } from "./streaming-helper.js";
export { Logger } from "./logger.js";
export { LoaderType, ResponseType } from "./net/types.js";

@@ -1,14 +0,14 @@

import _typeof from '@babel/runtime/helpers/typeof';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.object.get-prototype-of.js';
import { typeof as _typeof } from "./_virtual/_rollupPluginBabelHelpers.js";
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.object.get-prototype-of.js";
import "core-js/modules/es.number.is-nan.js";
import "core-js/modules/es.number.constructor.js";
var toString = Object.prototype.toString;
function isObject(a) {
return a !== null && _typeof(a) === 'object';
return a !== null && _typeof(a) === "object";
}
function isPlainObject(val) {
if (toString.call(val) !== '[object Object]') {
if (toString.call(val) !== "[object Object]") {
return false;
}
var prototype = Object.getPrototypeOf(val);

@@ -18,5 +18,4 @@ return prototype === null || prototype === Object.prototype;

function isDate(a) {
return toString.call(a) === '[object Date]';
return toString.call(a) === "[object Date]";
}
export { isDate, isObject, isPlainObject };

@@ -1,26 +0,20 @@

import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import 'core-js/modules/es.function.name.js';
import 'core-js/modules/es.array.concat.js';
var Logger = /*#__PURE__*/function () {
function Logger(name) {
_classCallCheck(this, Logger);
this.name = name || '';
import { defineProperty as _defineProperty, createClass as _createClass, classCallCheck as _classCallCheck } from "./_virtual/_rollupPluginBabelHelpers.js";
import "core-js/modules/es.function.name.js";
import "core-js/modules/es.array.concat.js";
import "core-js/modules/esnext.array.group.js";
var Logger = /* @__PURE__ */ function() {
function Logger2(name) {
_classCallCheck(this, Logger2);
this.name = name || "";
this._prefix = "[".concat(this.name, "]");
}
_createClass(Logger, [{
_createClass(Logger2, [{
key: "debug",
value: function debug() {
var _console;
if (Logger.disabled) return;
if (Logger2.disabled)
return;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
(_console = console).debug.apply(_console, [this._prefix].concat(args));

@@ -32,9 +26,7 @@ }

var _console2;
if (Logger.disabled) return;
if (Logger2.disabled)
return;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
(_console2 = console).log.apply(_console2, [this._prefix].concat(args));

@@ -46,9 +38,7 @@ }

var _console3;
if (Logger.disabled) return;
if (Logger2.disabled)
return;
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
(_console3 = console).warn.apply(_console3, [this._prefix].concat(args));

@@ -60,9 +50,7 @@ }

var _console4;
if (Logger.disabled) return;
if (Logger2.disabled)
return;
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
(_console4 = console).error.apply(_console4, [this._prefix].concat(args));

@@ -74,8 +62,6 @@ }

var _console5;
if (Logger.disabled) return;
if (Logger2.disabled)
return;
console.group(this._prefix);
(_console5 = console).table.apply(_console5, arguments);
console.groupEnd();

@@ -86,3 +72,3 @@ }

value: function enable() {
Logger.disabled = false;
Logger2.disabled = false;
}

@@ -92,11 +78,8 @@ }, {

value: function disable() {
Logger.disabled = true;
Logger2.disabled = true;
}
}]);
return Logger;
return Logger2;
}();
_defineProperty(Logger, "disabled", true);
export { Logger };
export type MSEErrorType = string;
export namespace MSEErrorType {
const CANCELLED: string;
const UPDATE_ERROR: string;
}
export class MSEError extends Error {
export class MSEError {
/**

@@ -16,2 +15,4 @@ * @param {MSEErrorType} type

export class MSE {
static VIDEO: string;
static AUDIO: string;
/**

@@ -29,8 +30,8 @@ * @param {string} [mime='video/mp4; codecs="avc1.42E01E,mp4a.40.2"']

/** @type { MediaSource | null } */
mediaSource: MediaSource | null;
_openPromise: Promise<any>;
mediaSource: any | null;
_openPromise: any;
_queue: any;
_sourceBuffer: any;
get isOpened(): boolean;
get duration(): number;
get duration(): any;
/**

@@ -40,5 +41,5 @@ * @param { number } duration

*/
updateDuration(duration: number): Promise<any>;
updateDuration(duration: number): Promise;
/** @return { Promise } */
open(): Promise<any>;
open(): Promise;
/**

@@ -48,5 +49,5 @@ * @param { HTMLMediaElement } media

*/
bindMedia(media: HTMLMediaElement): Promise<any>;
bindMedia(media: HTMLMediaElement): Promise;
/** @return { Promise } */
unbindMedia(): Promise<any>;
unbindMedia(): Promise;
/**

@@ -62,3 +63,3 @@ * @param { string } type

*/
changeType(type: string, mimeType: string): Promise<any>;
changeType(type: string, mimeType: string): Promise;
/**

@@ -69,3 +70,3 @@ * @param { string } type

*/
createOrChangeSource(type: string, mimeType: string): Promise<any>;
createOrChangeSource(type: string, mimeType: string): Promise;
/**

@@ -76,3 +77,3 @@ * @param { string } type

*/
append(type: string, buffer: BufferSource): Promise<any>;
append(type: string, buffer: BufferSource): Promise;
/**

@@ -84,3 +85,4 @@ * @param { string } type

*/
remove(type: string, startTime: number, endTime: number): Promise<any>;
remove(type: string, startTime: number, endTime: number): Promise;
clearBuffer(startTime: any, endTime: any): undefined;
clearAllBuffer(): undefined;

@@ -91,3 +93,3 @@ /**

*/
endOfStream(reason?: EndOfStreamError): Promise<any>;
endOfStream(reason?: EndOfStreamError): Promise;
setLiveSeekableRange(start: any, end: any): void;

@@ -109,4 +111,4 @@ /**

bufferEnd(type: string): number;
_enqueueOp(type: any, exec: any): Promise<any>;
_enqueueBlockingOp(exec: any): Promise<any>;
_enqueueOp(type: any, exec: any): any;
_enqueueBlockingOp(exec: any): unknown;
_startQueue(type: any): void;

@@ -116,3 +118,1 @@ _onSBUpdateEnd: (type: any) => void;

}
declare const MediaSource: any;
export {};

@@ -1,47 +0,34 @@

import 'core-js/modules/es.reflect.construct.js';
import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import _createClass from '@babel/runtime/helpers/createClass';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _inherits from '@babel/runtime/helpers/inherits';
import _possibleConstructorReturn from '@babel/runtime/helpers/possibleConstructorReturn';
import _getPrototypeOf from '@babel/runtime/helpers/getPrototypeOf';
import _wrapNativeSuper from '@babel/runtime/helpers/wrapNativeSuper';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import 'core-js/modules/es.array.iterator.js';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.string.iterator.js';
import 'core-js/modules/web.dom-collections.iterator.js';
import 'core-js/modules/web.url.js';
import 'core-js/modules/web.dom-collections.for-each.js';
import 'core-js/modules/es.object.keys.js';
import 'core-js/modules/es.promise.js';
import 'core-js/modules/es.regexp.exec.js';
import { createPublicPromise } from './utils.js';
import { Buffer } from './buffer.js';
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var MediaSource = window.MediaSource || window.WebKitMediaSource;
/** @enum {string} */
import { defineProperty as _defineProperty, inherits as _inherits, createSuper as _createSuper, createClass as _createClass, classCallCheck as _classCallCheck, wrapNativeSuper as _wrapNativeSuper, asyncToGenerator as _asyncToGenerator, regeneratorRuntime as _regeneratorRuntime } from "./_virtual/_rollupPluginBabelHelpers.js";
import "core-js/modules/es.error.cause.js";
import "core-js/modules/es.array.iterator.js";
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.string.iterator.js";
import "core-js/modules/web.dom-collections.iterator.js";
import "core-js/modules/web.url.js";
import "core-js/modules/web.url-search-params.js";
import "core-js/modules/web.dom-collections.for-each.js";
import "core-js/modules/es.object.keys.js";
import "core-js/modules/es.promise.js";
import "core-js/modules/es.array.push.js";
import "core-js/modules/es.regexp.exec.js";
import { createPublicPromise } from "./utils.js";
import { Buffer } from "./buffer.js";
import { StreamingError, ERR } from "./error.js";
import { isBrowser } from "./env.js";
function getMediaSource() {
try {
return isBrowser ? window.MediaSource : null;
} catch (e) {
}
}
var MediaSource = getMediaSource();
var MSEErrorType = {
CANCELLED: 'canceled',
UPDATE_ERROR: 'updateError'
UPDATE_ERROR: "updateError"
};
var MSEError = /*#__PURE__*/function (_Error) {
_inherits(MSEError, _Error);
var _super = _createSuper(MSEError);
/**
* @param {MSEErrorType} type
* @param {any} [msg]
*/
function MSEError(type, msg) {
var MSEError = /* @__PURE__ */ function(_Error) {
_inherits(MSEError2, _Error);
var _super = _createSuper(MSEError2);
function MSEError2(type, msg) {
var _this;
_classCallCheck(this, MSEError);
_classCallCheck(this, MSEError2);
_this = _super.call(this, msg || type);

@@ -52,37 +39,19 @@ _this.type = type;

}
return MSEError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
var MSE = /*#__PURE__*/function () {
/** @type { HTMLMediaElement | null } */
/** @type { MediaSource | null } */
/**
* @param {HTMLMediaElement} [media]
*/
function MSE(media) {
return _createClass(MSEError2);
}(/* @__PURE__ */ _wrapNativeSuper(Error));
var MSE = /* @__PURE__ */ function() {
function MSE2(media) {
var _this2 = this;
_classCallCheck(this, MSE);
_classCallCheck(this, MSE2);
_defineProperty(this, "media", null);
_defineProperty(this, "mediaSource", null);
_defineProperty(this, "_openPromise", createPublicPromise());
_defineProperty(this, "_queue", Object.create(null));
_defineProperty(this, "_sourceBuffer", Object.create(null));
_defineProperty(this, "_onSBUpdateEnd", function (type) {
_defineProperty(this, "_queue", /* @__PURE__ */ Object.create(null));
_defineProperty(this, "_sourceBuffer", /* @__PURE__ */ Object.create(null));
_defineProperty(this, "_onSBUpdateEnd", function(type) {
var queue = _this2._queue[type];
if (queue) {
var op = queue.shift();
if (op) {
op.promise.resolve();
_this2._startQueue(type);

@@ -92,24 +61,19 @@ }

});
_defineProperty(this, "_onSBUpdateError", function (type, event) {
_defineProperty(this, "_onSBUpdateError", function(type, event) {
var queue = _this2._queue[type];
if (queue) {
var op = queue[0];
if (op) {
op.promise.reject(new MSEError(MSEErrorType.UPDATE_ERROR, event)); // Do not shift from queue, 'updateend' event will fire next
op.promise.reject(new StreamingError(ERR.MEDIA, ERR.SUB_TYPES.MSE_APPEND_BUFFER, event));
}
}
});
if (media) this.bindMedia(media);
if (media)
this.bindMedia(media);
}
_createClass(MSE, [{
_createClass(MSE2, [{
key: "isOpened",
get: function get() {
var _this$mediaSource;
return ((_this$mediaSource = this.mediaSource) === null || _this$mediaSource === void 0 ? void 0 : _this$mediaSource.readyState) === 'open';
return ((_this$mediaSource = this.mediaSource) === null || _this$mediaSource === void 0 ? void 0 : _this$mediaSource.readyState) === "open";
}

@@ -120,10 +84,4 @@ }, {

var _this$mediaSource2;
return ((_this$mediaSource2 = this.mediaSource) === null || _this$mediaSource2 === void 0 ? void 0 : _this$mediaSource2.duration) || -1;
}
/**
* @param { number } duration
* @return { Promise }
*/
}, {

@@ -133,9 +91,7 @@ key: "updateDuration",

var _this3 = this;
return this._enqueueBlockingOp(function () {
if (_this3.mediaSource) _this3.mediaSource.duration = duration;
return this._enqueueBlockingOp(function() {
if (_this3.mediaSource)
_this3.mediaSource.duration = duration;
});
}
/** @return { Promise } */
}, {

@@ -145,31 +101,20 @@ key: "open",

var _this4 = this;
if (this._openPromise.used && !this.isOpened && this.mediaSource) {
var ms = this.mediaSource;
var onOpen = function onOpen() {
ms.removeEventListener('sourceopen', onOpen);
var onOpen = function onOpen2() {
ms.removeEventListener("sourceopen", onOpen2);
_this4._openPromise.resolve();
};
ms.addEventListener('sourceopen', onOpen);
ms.addEventListener("sourceopen", onOpen);
this._openPromise = createPublicPromise();
}
return this._openPromise;
}
/**
* @param { HTMLMediaElement } media
* @return { Promise }
*/
}, {
key: "bindMedia",
value: function () {
var _bindMedia = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(media) {
value: function() {
var _bindMedia = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee(media) {
var _this5 = this;
var ms, onOpen;
return _regeneratorRuntime.wrap(function _callee$(_context) {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {

@@ -182,6 +127,4 @@ switch (_context.prev = _context.next) {

}
_context.next = 3;
return this.unbindMedia();
case 3:

@@ -192,5 +135,3 @@ if (!(!media || !MediaSource)) {

}
throw new Error('Param media or MediaSource does not exist');
throw new Error("Param media or MediaSource does not exist");
case 5:

@@ -200,13 +141,9 @@ this.media = media;

media.src = URL.createObjectURL(ms);
onOpen = function onOpen() {
ms.removeEventListener('sourceopen', onOpen);
onOpen = function onOpen2() {
ms.removeEventListener("sourceopen", onOpen2);
URL.revokeObjectURL(media.src);
_this5._openPromise.resolve();
};
ms.addEventListener('sourceopen', onOpen);
ms.addEventListener("sourceopen", onOpen);
return _context.abrupt("return", this._openPromise);
case 11:

@@ -219,67 +156,56 @@ case "end":

}));
function bindMedia(_x) {
return _bindMedia.apply(this, arguments);
}
return bindMedia;
}()
/** @return { Promise } */
}, {
key: "unbindMedia",
value: function () {
var _unbindMedia = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
value: function() {
var _unbindMedia = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee2() {
var _this6 = this;
var ms;
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
var ms, hasMetadata, mseOpen;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!this._openPromise.used) this._openPromise.resolve();
if (!this._openPromise.used)
this._openPromise.resolve();
ms = this.mediaSource;
if (ms) {
Object.keys(this._queue).forEach(function (t) {
Object.keys(this._queue).forEach(function(t) {
var queue = _this6._queue[t];
if (queue) {
queue.forEach(function (x) {
return x.promise.reject(new MSEError(MSEErrorType.CANCELLED));
queue.forEach(function(x) {
return x.promise.resolve;
});
}
});
if (ms.readyState === 'open') {
hasMetadata = !!this.media && this.media.readyState >= 1;
mseOpen = ms.readyState === "open";
if (hasMetadata && mseOpen) {
try {
ms.endOfStream();
} catch (error) {// ignore
} catch (error) {
}
}
Object.keys(this._sourceBuffer).forEach(function (k) {
Object.keys(this._sourceBuffer).forEach(function(k) {
try {
ms.removeSourceBuffer(_this6._sourceBuffer[k]);
} catch (error) {// ignore
} catch (error) {
}
});
}
if (this.media) {
this.media.removeAttribute('src');
this.media.removeAttribute("src");
try {
this.media.load();
} catch (error) {// ignore
} catch (error) {
}
this.media = null;
}
this.mediaSource = null;
this._openPromise = createPublicPromise();
this._queue = Object.create(null);
this._sourceBuffer = Object.create(null);
this._queue = /* @__PURE__ */ Object.create(null);
this._sourceBuffer = /* @__PURE__ */ Object.create(null);
case 8:

@@ -292,29 +218,22 @@ case "end":

}));
function unbindMedia() {
return _unbindMedia.apply(this, arguments);
}
return unbindMedia;
}()
/**
* @param { string } type
* @param { string } mimeType
*/
}, {
key: "createSource",
value: function createSource(type, mimeType) {
if (this._sourceBuffer[type] || !this.mediaSource) return;
var sb = this._sourceBuffer[type] = this.mediaSource.addSourceBuffer(mimeType);
if (this._sourceBuffer[type] || !this.mediaSource)
return;
var sb;
try {
sb = this._sourceBuffer[type] = this.mediaSource.addSourceBuffer(mimeType);
} catch (error) {
throw new StreamingError(ERR.MEDIA, ERR.SUB_TYPES.MSE_ADD_SB, error);
}
sb.mimeType = mimeType;
sb.addEventListener('updateend', this._onSBUpdateEnd.bind(this, type));
sb.addEventListener('error', this._onSBUpdateError.bind(this, type));
sb.addEventListener("updateend", this._onSBUpdateEnd.bind(this, type));
sb.addEventListener("error", this._onSBUpdateError.bind(this, type));
}
/**
* @param { string } type
* @param { string } mimeType
* @return { Promise }
*/
}, {

@@ -324,13 +243,8 @@ key: "changeType",

var sb = this._sourceBuffer[type];
if (!this.mediaSource || !sb || sb.mimeType === mimeType || typeof sb.changeType !== 'function') return Promise.resolve();
return this._enqueueOp(function () {
if (!this.mediaSource || !sb || sb.mimeType === mimeType || typeof sb.changeType !== "function")
return Promise.resolve();
return this._enqueueOp(function() {
sb.changeType(mimeType);
});
}
/**
* @param { string } type
* @param { string } mimeType
* @return { Promise }
*/
}, {

@@ -342,8 +256,2 @@ key: "createOrChangeSource",

}
/**
* @param { string } type
* @param { BufferSource } buffer
* @return { Promise }
*/
}, {

@@ -353,21 +261,14 @@ key: "append",

var _this7 = this;
if (!buffer || !buffer.byteLength) {
return Promise.resolve();
}
if (!this._sourceBuffer[type]) return Promise.resolve();
return this._enqueueOp(type, function () {
if (!_this7.mediaSource) return;
_this7._sourceBuffer[type].appendBuffer(buffer);
if (!this._sourceBuffer[type])
return Promise.resolve();
return this._enqueueOp(type, function() {
var _this7$_sourceBuffer$;
if (!_this7.mediaSource)
return;
(_this7$_sourceBuffer$ = _this7._sourceBuffer[type]) === null || _this7$_sourceBuffer$ === void 0 ? void 0 : _this7$_sourceBuffer$.appendBuffer(buffer);
});
}
/**
* @param { string } type
* @param { number } startTime
* @param { number } endTime
* @return { Promise }
*/
}, {

@@ -377,14 +278,12 @@ key: "remove",

var _this8 = this;
if (Object.keys(this._sourceBuffer).length === 1) return;
return this._enqueueOp(type, function () {
if (!_this8.mediaSource) return;
if (Object.keys(this._sourceBuffer).length === 1)
return Promise.resolve();
return this._enqueueOp(type, function() {
if (!_this8.mediaSource)
return;
var sb = _this8._sourceBuffer[type];
if (startTime >= endTime || !sb) {
_this8._onSBUpdateEnd(type);
return;
}
sb.remove(startTime, endTime);

@@ -394,11 +293,26 @@ });

}, {
key: "clearBuffer",
value: function clearBuffer(startTime, endTime) {
var _this9 = this;
var p;
Object.keys(this._sourceBuffer).forEach(function(k) {
p = _this9._enqueueOp(k, function() {
if (!_this9.mediaSource)
return;
var sb = _this9._sourceBuffer[k];
sb.remove(startTime, endTime);
});
});
return p;
}
}, {
key: "clearAllBuffer",
value: function clearAllBuffer() {
var _this9 = this;
var _this10 = this;
var p;
Object.keys(this._sourceBuffer).forEach(function (k) {
p = _this9._enqueueOp(k, function () {
if (!_this9.mediaSource) return;
var sb = _this9._sourceBuffer[k];
Object.keys(this._sourceBuffer).forEach(function(k) {
p = _this10._enqueueOp(k, function() {
if (!_this10.mediaSource)
return;
var sb = _this10._sourceBuffer[k];
sb.remove(0, Buffer.end(Buffer.get(sb)));

@@ -409,17 +323,12 @@ });

}
/**
* @param {EndOfStreamError} [reason]
* @returns {Promise}
*/
}, {
key: "endOfStream",
value: function endOfStream(reason) {
var _this10 = this;
if (!this.mediaSource || this.mediaSource.readyState !== 'open') return Promise.resolve();
return this._enqueueBlockingOp(function () {
var ms = _this10.mediaSource;
if (!ms || ms.readyState !== 'open') return;
var _this11 = this;
if (!this.mediaSource || this.mediaSource.readyState !== "open")
return Promise.resolve();
return this._enqueueBlockingOp(function() {
var ms = _this11.mediaSource;
if (!ms || ms.readyState !== "open")
return;
if (reason) {

@@ -436,10 +345,6 @@ ms.endOfStream(reason);

var ms = this.mediaSource;
if (start < 0 || end < start || !(ms !== null && ms !== void 0 && ms.setLiveSeekableRange) || ms.readyState !== 'open') return;
if (start < 0 || end < start || !(ms !== null && ms !== void 0 && ms.setLiveSeekableRange) || ms.readyState !== "open")
return;
ms.setLiveSeekableRange(start, end);
}
/**
* @param { string } type
* @return { TimeRanges | void }
*/
}, {

@@ -450,7 +355,2 @@ key: "buffered",

}
/**
* @param { string } type
* @return { number }
*/
}, {

@@ -461,7 +361,2 @@ key: "bufferStart",

}
/**
* @param { string } type
* @return { number }
*/
}, {

@@ -475,14 +370,13 @@ key: "bufferEnd",

value: function _enqueueOp(type, exec) {
if (!this.mediaSource) return Promise.resolve();
if (!this.mediaSource)
return Promise.resolve();
var queue = this._queue[type] = this._queue[type] || [];
var op = {
exec: exec,
exec,
promise: createPublicPromise()
};
queue.push(op);
if (queue.length === 1) {
this._startQueue(type);
}
return op.promise;

@@ -492,8 +386,7 @@ }

key: "_enqueueBlockingOp",
value: function () {
var _enqueueBlockingOp2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(exec) {
var _this11 = this;
value: function() {
var _enqueueBlockingOp2 = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee3(exec) {
var _this12 = this;
var types, waiters;
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) {

@@ -506,8 +399,5 @@ switch (_context3.prev = _context3.next) {

}
return _context3.abrupt("return", Promise.resolve());
case 2:
types = Object.keys(this._sourceBuffer);
if (types.length) {

@@ -517,13 +407,11 @@ _context3.next = 5;

}
return _context3.abrupt("return", exec());
case 5:
waiters = [];
types.forEach(function (t) {
var queue = _this11._queue[t];
types.forEach(function(t) {
var queue = _this12._queue[t];
var prom = createPublicPromise();
waiters.push(prom);
queue.push({
exec: function exec() {
exec: function exec2() {
return prom.resolve();

@@ -533,18 +421,16 @@ },

});
if (queue.length === 1) {
_this11._startQueue(t);
_this12._startQueue(t);
}
});
return _context3.abrupt("return", Promise.all(waiters).then(function () {
return _context3.abrupt("return", Promise.all(waiters).then(function() {
try {
return exec();
} finally {
types.forEach(function (t) {
var queue = _this11._queue[t];
var sb = _this11._sourceBuffer[t];
types.forEach(function(t) {
var queue = _this12._queue[t];
var sb = _this12._sourceBuffer[t];
queue === null || queue === void 0 ? void 0 : queue.shift();
if (!sb || !sb.updating) {
_this11._startQueue(t);
_this12._startQueue(t);
}

@@ -554,3 +440,2 @@ });

}));
case 8:

@@ -563,7 +448,5 @@ case "end":

}));
function _enqueueBlockingOp(_x2) {
return _enqueueBlockingOp2.apply(this, arguments);
}
return _enqueueBlockingOp;

@@ -575,6 +458,4 @@ }()

var queue = this._queue[type];
if (queue) {
var op = queue[0];
if (op) {

@@ -584,5 +465,4 @@ try {

} catch (error) {
op.promise.reject(error);
op.promise.reject(new StreamingError(ERR.MEDIA, ERR.SUB_TYPES.MSE_OTHER, error));
queue.shift();
this._startQueue(type);

@@ -595,11 +475,6 @@ }

key: "isSupported",
value:
/**
* @param {string} [mime='video/mp4; codecs="avc1.42E01E,mp4a.40.2"']
* @returns {boolean}
*/
function isSupported() {
var mime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'video/mp4; codecs="avc1.42E01E,mp4a.40.2"';
if (!MediaSource) return false;
value: function isSupported() {
var mime = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 'video/mp4; codecs="avc1.42E01E,mp4a.40.2"';
if (!MediaSource)
return false;
try {

@@ -612,6 +487,6 @@ return MediaSource.isTypeSupported(mime);

}]);
return MSE;
return MSE2;
}();
_defineProperty(MSE, "VIDEO", "video");
_defineProperty(MSE, "AUDIO", "audio");
export { MSE, MSEError, MSEErrorType };

@@ -1,45 +0,33 @@

import 'core-js/modules/es.object.keys.js';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.array.filter.js';
import 'core-js/modules/es.object.get-own-property-descriptor.js';
import 'core-js/modules/web.dom-collections.for-each.js';
import 'core-js/modules/es.object.get-own-property-descriptors.js';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import { LoaderType, ResponseType } from './types.js';
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
import { objectSpread2 as _objectSpread2 } from "../_virtual/_rollupPluginBabelHelpers.js";
import { LoaderType, ResponseType } from "./types.js";
function getConfig(cfg) {
return _objectSpread({
return _objectSpread2({
loaderType: LoaderType.FETCH,
retry: 0,
retryDelay: 0,
// ms
timeout: 0,
request: null,
// Request
onTimeout: undefined,
onProgress: undefined,
onRetryError: undefined,
transformRequest: undefined,
transformResponse: undefined,
transformError: undefined,
onTimeout: void 0,
onProgress: void 0,
onRetryError: void 0,
transformRequest: void 0,
transformResponse: void 0,
transformError: void 0,
responseType: ResponseType.TEXT,
range: undefined,
url: '',
params: undefined,
method: 'GET',
range: void 0,
url: "",
params: void 0,
method: "GET",
headers: {},
body: undefined,
mode: undefined,
credentials: undefined,
cache: undefined,
redirect: undefined,
referrer: undefined,
referrerPolicy: undefined,
integrity: undefined
body: void 0,
mode: void 0,
credentials: void 0,
cache: void 0,
redirect: void 0,
referrer: void 0,
referrerPolicy: void 0,
integrity: void 0,
onProcessMinLen: 1
}, cfg);
}
export { getConfig };

@@ -1,2 +0,2 @@

export class NetError extends Error {
export class NetError {
constructor(url: any, request: any, response: any, msg: any);

@@ -3,0 +3,0 @@ retryCount: number;

@@ -1,36 +0,16 @@

import 'core-js/modules/es.reflect.construct.js';
import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _assertThisInitialized from '@babel/runtime/helpers/assertThisInitialized';
import _inherits from '@babel/runtime/helpers/inherits';
import _possibleConstructorReturn from '@babel/runtime/helpers/possibleConstructorReturn';
import _getPrototypeOf from '@babel/runtime/helpers/getPrototypeOf';
import _wrapNativeSuper from '@babel/runtime/helpers/wrapNativeSuper';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import { LoaderType } from './types.js';
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var NetError = /*#__PURE__*/function (_Error) {
_inherits(NetError, _Error);
var _super = _createSuper(NetError);
function NetError(url, request, response, msg) {
import { inherits as _inherits, createSuper as _createSuper, classCallCheck as _classCallCheck, defineProperty as _defineProperty, assertThisInitialized as _assertThisInitialized, createClass as _createClass, wrapNativeSuper as _wrapNativeSuper } from "../_virtual/_rollupPluginBabelHelpers.js";
import "core-js/modules/es.error.cause.js";
import { LoaderType } from "./types.js";
var NetError = /* @__PURE__ */ function(_Error) {
_inherits(NetError2, _Error);
var _super = _createSuper(NetError2);
function NetError2(url, request, response, msg) {
var _this;
_classCallCheck(this, NetError);
_classCallCheck(this, NetError2);
_this = _super.call(this, msg);
_defineProperty(_assertThisInitialized(_this), "retryCount", 0);
_defineProperty(_assertThisInitialized(_this), "isTimeout", false);
_defineProperty(_assertThisInitialized(_this), "loaderType", LoaderType.FETCH);
_defineProperty(_assertThisInitialized(_this), "startTime", 0);
_defineProperty(_assertThisInitialized(_this), "endTime", 0);
_this.url = url;

@@ -41,6 +21,4 @@ _this.request = request;

}
return NetError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
return _createClass(NetError2);
}(/* @__PURE__ */ _wrapNativeSuper(Error));
export { NetError };

@@ -14,3 +14,4 @@ export class FetchLoader {

_vid: string;
load({ url, vid, timeout, responseType, onProgress, index, onTimeout, range, transformResponse, request, params, logger, method, headers, body, mode, credentials, cache, redirect, referrer, referrerPolicy, integrity }: {
_onProcessMinLen: number;
load({ url, vid, timeout, responseType, onProgress, index, onTimeout, range, transformResponse, request, params, logger, method, headers, body, mode, credentials, cache, redirect, referrer, referrerPolicy, onProcessMinLen, }: {
url: any;

@@ -37,20 +38,10 @@ vid: any;

referrerPolicy: any;
integrity: any;
}): Promise<void | {
data: any;
done: any;
option: {
range: any;
vid: any;
index: any;
contentLength: any;
age: any;
startTime: any;
firstByteTime: any;
endTime: number;
};
response: any;
}>;
cancel(): Promise<void>;
_loadChunk(response: any, onProgress: any): void;
onProcessMinLen: any;
}): any;
resolve: any;
reject: any;
cancel(): any;
_loadChunk(response: any, onProgress: any, st: any, firstByteTime: any): void;
_cache: any;
_writeIdx: number;
get receiveLen(): number;

@@ -57,0 +48,0 @@ set running(arg: boolean);

@@ -1,113 +0,81 @@

import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.promise.js';
import 'core-js/modules/es.array.iterator.js';
import 'core-js/modules/es.typed-array.uint8-array.js';
import 'core-js/modules/es.typed-array.copy-within.js';
import 'core-js/modules/es.typed-array.every.js';
import 'core-js/modules/es.typed-array.fill.js';
import 'core-js/modules/es.typed-array.filter.js';
import 'core-js/modules/es.typed-array.find.js';
import 'core-js/modules/es.typed-array.find-index.js';
import 'core-js/modules/es.typed-array.for-each.js';
import 'core-js/modules/es.typed-array.includes.js';
import 'core-js/modules/es.typed-array.index-of.js';
import 'core-js/modules/es.typed-array.iterator.js';
import 'core-js/modules/es.typed-array.join.js';
import 'core-js/modules/es.typed-array.last-index-of.js';
import 'core-js/modules/es.typed-array.map.js';
import 'core-js/modules/es.typed-array.reduce.js';
import 'core-js/modules/es.typed-array.reduce-right.js';
import 'core-js/modules/es.typed-array.reverse.js';
import 'core-js/modules/es.typed-array.set.js';
import 'core-js/modules/es.typed-array.slice.js';
import 'core-js/modules/es.typed-array.some.js';
import 'core-js/modules/es.typed-array.sort.js';
import 'core-js/modules/es.typed-array.subarray.js';
import 'core-js/modules/es.typed-array.to-locale-string.js';
import 'core-js/modules/es.typed-array.to-string.js';
import { NetError } from './error.js';
import { setUrlParams, getRangeValue, createResponse } from './helper.js';
import { ResponseType } from './types.js';
var FetchLoader = /*#__PURE__*/function () {
function FetchLoader() {
_classCallCheck(this, FetchLoader);
import { createClass as _createClass, classCallCheck as _classCallCheck, defineProperty as _defineProperty, asyncToGenerator as _asyncToGenerator, regeneratorRuntime as _regeneratorRuntime } from "../_virtual/_rollupPluginBabelHelpers.js";
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.promise.js";
import "core-js/modules/es.array.iterator.js";
import "core-js/modules/es.typed-array.uint8-array.js";
import "core-js/modules/es.typed-array.at.js";
import "core-js/modules/es.typed-array.copy-within.js";
import "core-js/modules/es.typed-array.every.js";
import "core-js/modules/es.typed-array.fill.js";
import "core-js/modules/es.typed-array.filter.js";
import "core-js/modules/es.typed-array.find.js";
import "core-js/modules/es.typed-array.find-index.js";
import "core-js/modules/es.typed-array.find-last.js";
import "core-js/modules/es.typed-array.find-last-index.js";
import "core-js/modules/es.typed-array.for-each.js";
import "core-js/modules/es.typed-array.includes.js";
import "core-js/modules/es.typed-array.index-of.js";
import "core-js/modules/es.typed-array.iterator.js";
import "core-js/modules/es.typed-array.join.js";
import "core-js/modules/es.typed-array.last-index-of.js";
import "core-js/modules/es.typed-array.map.js";
import "core-js/modules/es.typed-array.reduce.js";
import "core-js/modules/es.typed-array.reduce-right.js";
import "core-js/modules/es.typed-array.reverse.js";
import "core-js/modules/es.typed-array.set.js";
import "core-js/modules/es.typed-array.slice.js";
import "core-js/modules/es.typed-array.some.js";
import "core-js/modules/es.typed-array.sort.js";
import "core-js/modules/es.typed-array.subarray.js";
import "core-js/modules/es.typed-array.to-locale-string.js";
import "core-js/modules/es.typed-array.to-string.js";
import "core-js/modules/esnext.typed-array.to-reversed.js";
import "core-js/modules/esnext.typed-array.to-sorted.js";
import "core-js/modules/esnext.typed-array.with.js";
import "core-js/modules/es.array.slice.js";
import { NetError } from "./error.js";
import { setUrlParams, getRangeValue, createResponse } from "./helper.js";
import { ResponseType } from "./types.js";
import SpeedSampler from "./speed-sampler.js";
var CACHESIZE = 2 * 1024 * 1024;
var FetchLoader = /* @__PURE__ */ function() {
function FetchLoader2() {
_classCallCheck(this, FetchLoader2);
_defineProperty(this, "_abortController", null);
_defineProperty(this, "_timeoutTimer", null);
_defineProperty(this, "_reader", null);
_defineProperty(this, "_response", null);
_defineProperty(this, "_aborted", false);
_defineProperty(this, "_index", -1);
_defineProperty(this, "_range", null);
_defineProperty(this, "_receivedLength", 0);
_defineProperty(this, "_running", false);
_defineProperty(this, "_logger", null);
_defineProperty(this, "_vid", '');
_defineProperty(this, "_vid", "");
_defineProperty(this, "_onProcessMinLen", 0);
}
_createClass(FetchLoader, [{
_createClass(FetchLoader2, [{
key: "load",
value: function load(_ref) {
var _this = this;
var url = _ref.url,
vid = _ref.vid,
timeout = _ref.timeout,
responseType = _ref.responseType,
onProgress = _ref.onProgress,
index = _ref.index,
onTimeout = _ref.onTimeout,
range = _ref.range,
transformResponse = _ref.transformResponse,
request = _ref.request,
params = _ref.params,
logger = _ref.logger,
method = _ref.method,
headers = _ref.headers,
body = _ref.body,
mode = _ref.mode,
credentials = _ref.credentials,
cache = _ref.cache,
redirect = _ref.redirect,
referrer = _ref.referrer,
referrerPolicy = _ref.referrerPolicy,
integrity = _ref.integrity;
var _this$_abortControlle, _this = this;
var url = _ref.url, vid = _ref.vid, timeout = _ref.timeout, responseType = _ref.responseType, onProgress = _ref.onProgress, index = _ref.index, onTimeout = _ref.onTimeout, range = _ref.range, transformResponse = _ref.transformResponse, request = _ref.request, params = _ref.params, logger = _ref.logger, method = _ref.method, headers = _ref.headers, body = _ref.body, mode = _ref.mode, credentials = _ref.credentials, cache = _ref.cache, redirect = _ref.redirect, referrer = _ref.referrer, referrerPolicy = _ref.referrerPolicy, onProcessMinLen = _ref.onProcessMinLen;
this._logger = logger;
this._aborted = false;
this._onProcessMinLen = onProcessMinLen;
this._abortController = typeof AbortController !== "undefined" && new AbortController();
this._running = true;
this._abortController = new AbortController();
this._index = index;
this._range = range || [0, 0];
this._vid = vid || url;
this._logger.debug('【fetchLoader task】, range', this._range);
var init = {
method: method,
headers: headers,
body: body,
mode: mode,
credentials: credentials,
cache: cache,
redirect: redirect,
referrer: referrer,
referrerPolicy: referrerPolicy,
integrity: integrity,
signal: this._abortController.signal
method,
headers,
body,
mode,
credentials,
cache,
redirect,
referrer,
referrerPolicy,
signal: (_this$_abortControlle = this._abortController) === null || _this$_abortControlle === void 0 ? void 0 : _this$_abortControlle.signal
};

@@ -118,3 +86,2 @@ var isTimeout = false;

var rangeValue = getRangeValue(range);
if (rangeValue) {

@@ -126,5 +93,4 @@ if (request) {

}
if (headers instanceof Headers) {
headers.append('Range', rangeValue);
headers.append("Range", rangeValue);
} else {

@@ -134,9 +100,6 @@ headers.Range = rangeValue;

}
if (timeout) {
this._timeoutTimer = setTimeout(function () {
this._timeoutTimer = setTimeout(function() {
isTimeout = true;
_this.cancel();
if (onTimeout) {

@@ -149,106 +112,100 @@ var error = new NetError(url, init);

}
var startTime = Date.now();
return fetch(request || url, request ? undefined : init).then( /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(response) {
var firstByteTime, data;
return _regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
clearTimeout(_this._timeoutTimer);
_this._response = response;
if (!_this._aborted) {
_context.next = 4;
this._logger.debug("[fetch load start], index,", index, ",range,", range);
return new Promise(function(resolve, reject) {
fetch(request || url, request ? void 0 : init).then(/* @__PURE__ */ function() {
var _ref2 = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee(response) {
var firstByteTime, data, costTime;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
clearTimeout(_this._timeoutTimer);
_this._response = response;
if (!(_this._aborted || !_this._running)) {
_context.next = 4;
break;
}
return _context.abrupt("return");
case 4:
if (transformResponse) {
response = transformResponse(response, url) || response;
}
if (response.ok) {
_context.next = 7;
break;
}
throw new NetError(url, init, response, "bad network response");
case 7:
firstByteTime = Date.now();
if (!(responseType === ResponseType.TEXT)) {
_context.next = 15;
break;
}
_context.next = 11;
return response.text();
case 11:
data = _context.sent;
_this._running = false;
_context.next = 36;
break;
}
return _context.abrupt("return");
case 4:
if (transformResponse) {
response = transformResponse(response, url) || response;
}
if (response.ok) {
_context.next = 7;
case 15:
if (!(responseType === ResponseType.JSON)) {
_context.next = 22;
break;
}
_context.next = 18;
return response.json();
case 18:
data = _context.sent;
_this._running = false;
_context.next = 36;
break;
}
throw new NetError(url, init, response, 'bad network response');
case 7:
firstByteTime = Date.now();
if (!(responseType === ResponseType.TEXT)) {
_context.next = 14;
break;
}
_context.next = 11;
return response.text();
case 11:
data = _context.sent;
_context.next = 28;
break;
case 14:
if (!(responseType === ResponseType.JSON)) {
_context.next = 20;
break;
}
_context.next = 17;
return response.json();
case 17:
data = _context.sent;
_context.next = 28;
break;
case 20:
if (!onProgress) {
_context.next = 24;
break;
}
_this._loadChunk(response, onProgress);
_context.next = 28;
break;
case 24:
_context.next = 26;
return response.arrayBuffer();
case 26:
data = _context.sent;
data = new Uint8Array(data);
case 28:
_this._running = false;
return _context.abrupt("return", createResponse(data, true, response, response.headers.get('Content-Length'), response.headers.get('age'), startTime, firstByteTime, index, range, _this._vid));
case 30:
case "end":
return _context.stop();
case 22:
if (!onProgress) {
_context.next = 29;
break;
}
_this.resolve = resolve;
_this.reject = reject;
_this._loadChunk(response, onProgress, startTime, firstByteTime);
return _context.abrupt("return");
case 29:
_context.next = 31;
return response.arrayBuffer();
case 31:
data = _context.sent;
data = new Uint8Array(data);
_this._running = false;
costTime = Date.now() - startTime;
SpeedSampler.netSampling({
mTime: costTime,
mBytes: data.byteLength,
mSpeedInbPS: data.byteLength * 8 / (costTime / 1e3),
mRTT: firstByteTime - startTime
});
case 36:
_this._logger.debug("[fetch load end], index,", index, ",range,", range);
resolve(createResponse(data, true, response, response.headers.get("Content-Length"), response.headers.get("age"), startTime, firstByteTime, index, range, _this._vid));
case 38:
case "end":
return _context.stop();
}
}
}
}, _callee);
}));
return function (_x) {
return _ref2.apply(this, arguments);
};
}()).catch(function (error) {
clearTimeout(_this._timeoutTimer);
_this._running = false;
if (_this._aborted && !isTimeout) return;
error = error instanceof NetError ? error : new NetError(url, init);
error.startTime = startTime;
error.endTime = Date.now();
error.isTimeout = isTimeout;
throw error;
}, _callee);
}));
return function(_x) {
return _ref2.apply(this, arguments);
};
}()).catch(function(error) {
clearTimeout(_this._timeoutTimer);
_this._running = false;
if (_this._aborted && !isTimeout)
return;
error = error instanceof NetError ? error : new NetError(url, init);
error.startTime = startTime;
error.endTime = Date.now();
error.isTimeout = isTimeout;
reject(error);
});
});

@@ -258,5 +215,5 @@ }

key: "cancel",
value: function () {
var _cancel = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
value: function() {
var _cancel = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee2() {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) {

@@ -269,49 +226,34 @@ switch (_context2.prev = _context2.next) {

}
return _context2.abrupt("return");
case 2:
this._aborted = true;
this._running = false;
if (!this._response) {
_context2.next = 16;
_context2.next = 14;
break;
}
_context2.prev = 5;
_context2.next = 8;
return this._response.body.cancel();
case 8:
if (!this._reader) {
_context2.next = 11;
_context2.next = 9;
break;
}
_context2.next = 11;
_context2.next = 9;
return this._reader.cancel();
case 9:
_context2.next = 13;
break;
case 11:
_context2.next = 15;
break;
_context2.prev = 11;
_context2.t0 = _context2["catch"](5);
case 13:
_context2.prev = 13;
_context2.t0 = _context2["catch"](5);
case 15:
this._response = this._reader = null;
case 16:
case 14:
if (this._abortController) {
try {
this._abortController.abort();
} catch (error) {// ignore
} catch (error) {
}
this._abortController = null;
}
case 17:
case 15:
case "end":

@@ -321,9 +263,7 @@ return _context2.stop();

}
}, _callee2, this, [[5, 13]]);
}, _callee2, this, [[5, 11]]);
}));
function cancel() {
return _cancel.apply(this, arguments);
}
return cancel;

@@ -333,5 +273,13 @@ }()

key: "_loadChunk",
value: function _loadChunk(response, onProgress) {
value: function _loadChunk(response, onProgress, st, firstByteTime) {
var _this2 = this;
if (!response.body || !response.body.getReader) {
this._running = false;
this.reject(NetError(response.url, "", response, "onProgress of bad response.body.getReader"));
return;
}
if (this._onProcessMinLen > 0) {
this._cache = new Uint8Array(CACHESIZE);
this._writeIdx = 0;
}
var reader = this._reader = response.body.getReader();

@@ -341,7 +289,6 @@ var data;

var endTime;
var pump = /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
var startByte;
return _regeneratorRuntime.wrap(function _callee3$(_context3) {
var pump = /* @__PURE__ */ function() {
var _ref3 = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee3() {
var startByte, curLen, retData, temp, costTime;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) {

@@ -354,3 +301,2 @@ switch (_context3.prev = _context3.next) {

return reader.read();
case 4:

@@ -361,54 +307,77 @@ data = _context3.sent;

break;
case 8:
_context3.prev = 8;
_context3.t0 = _context3["catch"](1);
// request aborted
endTime = Date.now();
onProgress(undefined, true, {
range: _this2._range,
vid: _this2._vid,
index: _this2._index,
startTime: startTime,
endTime: endTime
}, response);
if (!_this2._aborted) {
_this2._running = false;
_this2.reject(_context3.t0);
}
return _context3.abrupt("return");
case 13:
startByte = _this2._range[0] + _this2._receivedLength;
if (!_this2._aborted) {
_context3.next = 16;
_context3.next = 18;
break;
}
onProgress(undefined, true, {
range: _this2._range,
_this2._running = false;
onProgress(void 0, false, {
range: [startByte, startByte],
vid: _this2._vid,
index: _this2._index,
startTime: startTime,
endTime: endTime
startTime,
endTime
}, response);
return _context3.abrupt("return");
case 16:
startByte = _this2._range[0] + _this2._receivedLength;
_this2._receivedLength += data.value ? data.value.byteLength : 0;
_this2._logger.debug('【fetchLoader,onProgress call】,task,', _this2._range, ', start,', startByte, ', end,', _this2._range[0] + _this2._receivedLength, ', done,', data.done);
_this2._running = data.done;
onProgress(data.value, data.done, {
range: [startByte, _this2._range[0] + _this2._receivedLength],
vid: _this2._vid,
index: _this2._index,
startTime: startTime,
endTime: endTime
}, response);
case 18:
curLen = data.value ? data.value.byteLength : 0;
_this2._receivedLength += curLen;
_this2._logger.debug("\u3010fetchLoader,onProgress call\u3011,task,", _this2._range, ", start,", startByte, ", end,", _this2._range[0] + _this2._receivedLength, ", done,", data.done);
if (_this2._writeIdx + curLen >= _this2._onProcessMinLen || data.done) {
retData = new Uint8Array(_this2._writeIdx + curLen);
retData.set(_this2._cache.slice(0, _this2._writeIdx), 0);
curLen > 0 && retData.set(data.value, _this2._writeIdx);
_this2._writeIdx = 0;
_this2._logger.debug("\u3010fetchLoader,onProgress enough\u3011,done,", data.done, ",len,", retData.byteLength, ", writeIdx,", _this2._writeIdx);
} else {
if (curLen > 0 && _this2._writeIdx + curLen < CACHESIZE) {
_this2._cache.set(data.value, _this2._writeIdx);
_this2._writeIdx += curLen;
_this2._logger.debug("\u3010fetchLoader,onProgress cache\u3011,len,", curLen, ", writeIdx,", _this2._writeIdx);
} else if (curLen > 0) {
temp = new Uint8Array(_this2._writeIdx + curLen + 2048);
_this2._logger.debug("\u3010fetchLoader,onProgress extra start\u3011,size,", _this2._writeIdx + curLen + 2048, ", datalen,", curLen, ", writeIdx,", _this2._writeIdx);
temp.set(_this2._cache.slice(0, _this2._writeIdx), 0);
curLen > 0 && temp.set(data.value, _this2._writeIdx);
_this2._writeIdx += curLen;
delete _this2._cache;
_this2._cache = temp;
_this2._logger.debug("\u3010fetchLoader,onProgress extra end\u3011,len,", curLen, ", writeIdx,", _this2._writeIdx);
}
}
if (retData && retData.byteLength > 0 || data.done) {
onProgress(retData, data.done, {
range: [_this2._range[0] + _this2._receivedLength - retData.byteLength, _this2._range[0] + _this2._receivedLength],
vid: _this2._vid,
index: _this2._index,
startTime,
endTime
}, response);
}
costTime = Date.now() - st;
_this2._logger.debug("[fetchLoader SPEED], fetch speed(b/s),", _this2._receivedLength * 8 / (costTime / 1e3));
SpeedSampler.netSampling({
mTime: costTime,
mBytes: _this2._receivedLength,
mSpeedInbPS: _this2._receivedLength * 8 / (costTime / 1e3),
mRTT: firstByteTime - st
});
if (!data.done) {
pump();
} else {
_this2._logger.debug('【fetchLoader,onProgress call】,task,', _this2._range, ',done,', data.done);
_this2._running = false;
_this2._logger.debug("[fetchLoader onProgress end],task,", _this2._range, ",done,", data.done);
_this2.resolve(createResponse(data, true, response, response.headers.get("Content-Length"), response.headers.get("age"), startTime, firstByteTime, _this2._index, _this2._range, _this2._vid));
}
case 22:
case 27:
case "end":

@@ -420,8 +389,6 @@ return _context3.stop();

}));
return function pump() {
return function pump2() {
return _ref3.apply(this, arguments);
};
}();
pump();

@@ -445,19 +412,7 @@ }

value: function isSupported() {
if (typeof ReadableStream !== 'undefined') {
try {
new ReadableStream({}); // eslint-disable-line no-new
} catch (e) {
return false;
}
} else {
return false;
}
return !!(typeof fetch !== 'undefined' && typeof AbortController !== 'undefined');
return !!(typeof fetch !== "undefined");
}
}]);
return FetchLoader;
return FetchLoader2;
}();
export { FetchLoader };

@@ -14,5 +14,5 @@ export function getRangeValue(value: any): string;

firstByteTime: any;
endTime: number;
endTime: any;
};
response: any;
};

@@ -1,40 +0,42 @@

import 'core-js/modules/es.regexp.exec.js';
import 'core-js/modules/es.string.replace.js';
import 'core-js/modules/es.array.join.js';
import 'core-js/modules/es.array.filter.js';
import 'core-js/modules/es.array.map.js';
import 'core-js/modules/es.object.keys.js';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.array.slice.js';
import { isDate, isObject } from '../is.js';
import "core-js/modules/es.regexp.exec.js";
import "core-js/modules/es.string.replace.js";
import "core-js/modules/es.array.join.js";
import "core-js/modules/es.array.filter.js";
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.array.map.js";
import "core-js/modules/es.object.keys.js";
import "core-js/modules/es.json.stringify.js";
import "core-js/modules/es.array.concat.js";
import "core-js/modules/es.array.slice.js";
import "core-js/modules/es.number.is-nan.js";
import "core-js/modules/es.number.constructor.js";
import { isDate, isObject } from "../is.js";
function getRangeValue(value) {
if (!value || value[0] == null || value[0] === 0 && value[1] == null) {
if (!value || value[0] === null || value[0] === void 0 || value[0] === 0 && (value[1] === null || value[1] === void 0)) {
return;
}
var ret = 'bytes=' + value[0] + '-';
if (value[1]) ret += value[1];
var ret = "bytes=" + value[0] + "-";
if (value[1])
ret += value[1];
return ret;
}
function encode(val) {
return encodeURIComponent(val).replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+').replace(/%5B/gi, '[').replace(/%5D/gi, ']');
return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
}
function setUrlParams(url, params) {
if (!url) return;
if (!params) return url;
if (!url)
return;
if (!params)
return url;
var v;
var str = Object.keys(params).map(function (k) {
var str = Object.keys(params).map(function(k) {
v = params[k];
if (v == null) return;
if (v === null || v === void 0)
return;
if (Array.isArray(v)) {
k = k + '[]';
k = k + "[]";
} else {
v = [v];
}
return v.map(function (x) {
return v.map(function(x) {
if (isDate(x)) {

@@ -45,41 +47,36 @@ x = x.toISOString();

}
return "".concat(encode(k), "=").concat(encode(x));
}).join('&');
}).filter(Boolean).join('&');
}).join("&");
}).filter(Boolean).join("&");
if (str) {
var hashIndex = url.indexOf('#');
var hashIndex = url.indexOf("#");
if (hashIndex !== -1) {
url = url.slice(0, hashIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + str;
url += (url.indexOf("?") === -1 ? "?" : "&") + str;
}
return url;
}
function createResponse(data, done, response, contentLength, age, startTime, firstByteTime, index, range, vid) {
age = age != null ? parseFloat(age) : null;
contentLength = parseInt(contentLength || '0', 10);
if (isNaN(contentLength)) contentLength = 0;
age = age !== null && age !== void 0 ? parseFloat(age) : null;
contentLength = parseInt(contentLength || "0", 10);
if (Number.isNaN(contentLength))
contentLength = 0;
var option = {
range: range,
vid: vid,
index: index,
contentLength: contentLength,
age: age,
startTime: startTime,
firstByteTime: firstByteTime,
range,
vid,
index,
contentLength,
age,
startTime,
firstByteTime,
endTime: Date.now()
};
return {
data: data,
done: done,
option: option,
response: response
data,
done,
option,
response
};
}
export { createResponse, getRangeValue, setUrlParams };
export class NetLoader {
static isFetchSupport(): boolean;
static getSpeed(): number;
static getRealTimeSpeed(): number;
static getRTT(): any;
constructor(cfg: any);

@@ -11,4 +14,4 @@ type: string;

isFetch(): boolean;
load(url: any, config?: {}): Promise<any>;
cancel(): Promise<any[]>;
load(url: any, config?: {}): any;
cancel(): any;
_processTask(): void;

@@ -15,0 +18,0 @@ }

@@ -1,43 +0,35 @@

import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import 'core-js/modules/es.object.assign.js';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.array.map.js';
import 'core-js/modules/es.array.iterator.js';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.promise.js';
import 'core-js/modules/es.string.iterator.js';
import 'core-js/modules/web.dom-collections.iterator.js';
import 'core-js/modules/es.promise.finally.js';
import 'core-js/modules/es.regexp.exec.js';
import { FetchLoader } from './fetch.js';
import { LoaderType } from './types.js';
export { LoaderType, ResponseType } from './types.js';
import { getConfig } from './config.js';
import { Task } from './task.js';
import { isPlainObject } from '../is.js';
var NetLoader = /*#__PURE__*/function () {
function NetLoader(cfg) {
_classCallCheck(this, NetLoader);
import { createClass as _createClass, classCallCheck as _classCallCheck, defineProperty as _defineProperty, asyncToGenerator as _asyncToGenerator, regeneratorRuntime as _regeneratorRuntime } from "../_virtual/_rollupPluginBabelHelpers.js";
import "core-js/modules/es.object.assign.js";
import "core-js/modules/es.array.push.js";
import "core-js/modules/es.array.concat.js";
import "core-js/modules/es.array.map.js";
import "core-js/modules/es.array.iterator.js";
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.promise.js";
import "core-js/modules/es.string.iterator.js";
import "core-js/modules/web.dom-collections.iterator.js";
import "core-js/modules/es.promise.finally.js";
import "core-js/modules/es.regexp.exec.js";
import { FetchLoader } from "./fetch.js";
import { LoaderType } from "./types.js";
export { LoaderType, ResponseType } from "./types.js";
import { getConfig } from "./config.js";
import { Task } from "./task.js";
import { isPlainObject } from "../is.js";
import { sleep } from "../streaming-helper.js";
import SpeedSampler from "./speed-sampler.js";
var NetLoader = /* @__PURE__ */ function() {
function NetLoader2(cfg) {
_classCallCheck(this, NetLoader2);
_defineProperty(this, "type", LoaderType.FETCH);
_defineProperty(this, "_queue", []);
_defineProperty(this, "_alive", []);
_defineProperty(this, "_currentTask", null);
this._config = getConfig(cfg);
if (this._config.loaderType === LoaderType.XHR || !FetchLoader.isSupported()) {
this.type = LoaderType.XHR;
}
this.log = cfg.logger;
}
_createClass(NetLoader, [{
_createClass(NetLoader2, [{
key: "isFetch",

@@ -50,5 +42,4 @@ value: function isFetch() {

value: function load(url) {
var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (typeof url === 'string' || !url) {
var config = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
if (typeof url === "string" || !url) {
config.url = url || config.url || this._config.url;

@@ -58,22 +49,18 @@ } else {

}
config = Object.assign({}, this._config, config);
if (config.params) config.params = Object.assign({}, config.params);
if (config.headers && isPlainObject(config.headers)) config.headers = Object.assign({}, config.headers);
if (config.body && isPlainObject(config.body)) config.body = Object.assign({}, config.body);
if (config.params)
config.params = Object.assign({}, config.params);
if (config.headers && isPlainObject(config.headers))
config.headers = Object.assign({}, config.headers);
if (config.body && isPlainObject(config.body))
config.body = Object.assign({}, config.body);
if (config.transformRequest) {
config = config.transformRequest(config) || config;
}
config.logger = this.log;
var task = new Task(this.type, config);
this.log.debug('[task add queue]', config.range, ', queueLen,', this._queue.length);
this._queue.push(task);
if (this._queue.length === 1 && (!this._currentTask || !this._currentTask.running)) {
this._processTask();
}
return task.promise;

@@ -83,17 +70,36 @@ }

key: "cancel",
value: function cancel() {
var cancels = this._queue.map(function (t) {
return t.cancel();
}).concat(this._alive.map(function (t) {
return t.cancel();
value: function() {
var _cancel = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee() {
var cancels;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
cancels = this._queue.map(function(t) {
return t.cancel();
}).concat(this._alive.map(function(t) {
return t.cancel();
}));
if (this._currentTask) {
cancels.push(this._currentTask.cancel());
}
this._queue = [];
this._alive = [];
_context.next = 6;
return Promise.all(cancels);
case 6:
_context.next = 8;
return sleep();
case 8:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
if (this._currentTask) {
cancels.push(this._currentTask.cancel());
function cancel() {
return _cancel.apply(this, arguments);
}
this._queue = [];
this._alive = [];
return Promise.all(cancels);
}
return cancel;
}()
}, {

@@ -103,13 +109,10 @@ key: "_processTask",

var _this = this;
this._currentTask = this._queue.shift();
if (!this._currentTask) return;
if (!this._currentTask)
return;
if (this._currentTask.alive) {
this._alive.push(this._currentTask);
}
this.log.debug('[task exec]', this._currentTask._config.range, ', queueLen,', this._queue.length);
this._currentTask.exec().finally(function () {
this._currentTask.exec().catch(function(e) {
}).finally(function() {
_this._processTask();

@@ -123,7 +126,20 @@ });

}
}, {
key: "getSpeed",
value: function getSpeed() {
return SpeedSampler.getSpeed();
}
}, {
key: "getRealTimeSpeed",
value: function getRealTimeSpeed() {
return SpeedSampler.getRealTimeSpeed();
}
}, {
key: "getRTT",
value: function getRTT() {
return SpeedSampler.getRTT();
}
}]);
return NetLoader;
return NetLoader2;
}();
export { NetLoader };
export default SpeedSampler;
declare class SpeedSampler {
static _netRecords: any[];
static getSpeed(): number;
static getRealTimeSpeed(): number;
/**
* 获取RTT中位数
* @returns
*/
static getRTT(): any;
/**
* 采集下载数据
* @param {{
* mTime: number, //下载耗时,单位ms
* mBytes: number, //下载数据量 单位Byte
* mSpeedInbPS: number, // 下载速度,单位b/s
* mRTT: number // 建联耗时,单位ms
* }} record
*/
static netSampling(record: {
mTime: number;
mBytes: number;
mSpeedInbPS: number;
mRTT: number;
}): void;
_firstCheckpoint: number;

@@ -8,2 +31,3 @@ _lastCheckpoint: number;

_lastSecondBytes: number;
_realTimeSpeed: number;
_now: any;

@@ -14,3 +38,2 @@ reset(): void;

get lastSecondKBps(): number;
get averageKBps(): number;
}

@@ -1,27 +0,11 @@

import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
/*
* Copyright (C) 2016 Bilibili. All Rights Reserved.
*
* @author zheng qian <xqq@xqq.im>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Utility class to calculate realtime network I/O speed
var SpeedSampler = /*#__PURE__*/function () {
function SpeedSampler() {
_classCallCheck(this, SpeedSampler);
// milliseconds
import { defineProperty as _defineProperty, createClass as _createClass, classCallCheck as _classCallCheck } from "../_virtual/_rollupPluginBabelHelpers.js";
import "core-js/modules/es.array.map.js";
import "core-js/modules/es.array.push.js";
import "core-js/modules/es.array.sort.js";
import "core-js/modules/es.array.splice.js";
var MaxQueueCapacity = 10;
var INVALID_SPEED = 0;
var SpeedSampler = /* @__PURE__ */ function() {
function SpeedSampler2() {
_classCallCheck(this, SpeedSampler2);
this._firstCheckpoint = 0;

@@ -31,4 +15,4 @@ this._lastCheckpoint = 0;

this._totalBytes = 0;
this._lastSecondBytes = 0; // compatibility detection
this._lastSecondBytes = 0;
this._realTimeSpeed = 0;
if (self.performance && self.performance.now) {

@@ -40,4 +24,3 @@ this._now = self.performance.now.bind(self.performance);

}
_createClass(SpeedSampler, [{
_createClass(SpeedSampler2, [{
key: "reset",

@@ -57,7 +40,6 @@ value: function reset() {

this._totalBytes += bytes;
} else if (this._now() - this._lastCheckpoint < 1000) {
} else if (this._now() - this._lastCheckpoint < 1e3) {
this._intervalBytes += bytes;
this._totalBytes += bytes;
} else {
// duration >= 1000
this._lastSecondBytes = this._intervalBytes;

@@ -73,4 +55,5 @@ this._intervalBytes = bytes;

this.addBytes(0);
var durationSeconds = (this._now() - this._lastCheckpoint) / 1000;
if (durationSeconds == 0) durationSeconds = 1;
var durationSeconds = (this._now() - this._lastCheckpoint) / 1e3;
if (durationSeconds === 0)
durationSeconds = 1;
return this._intervalBytes / durationSeconds / 1024;

@@ -82,13 +65,8 @@ }

this.addBytes(0);
if (this._lastSecondBytes !== 0) {
return this._lastSecondBytes / 1024;
} else {
// lastSecondBytes === 0
if (this._now() - this._lastCheckpoint >= 500) {
// if time interval since last checkpoint has exceeded 500ms
// the speed is nearly accurate
return this.currentKBps;
} else {
// We don't know
return 0;

@@ -98,15 +76,69 @@ }

}
}], [{
key: "getSpeed",
value: function getSpeed() {
var speed = INVALID_SPEED;
if (this._netRecords.length < 1) {
return speed;
}
var _recordsCopy = [];
this._netRecords.map(function(item) {
_recordsCopy.push(item);
});
_recordsCopy.sort(function(a, b) {
return a.mSpeedInbPS - b.mSpeedInbPS;
});
var _len = _recordsCopy.length;
var targetWeight = 0;
for (var i = 0; i < _len; i++) {
targetWeight += _recordsCopy[i].mBytes;
}
targetWeight /= 2;
for (var _i = 0; _i < _len; _i++) {
targetWeight -= _recordsCopy[_i].mBytes;
if (targetWeight <= 0) {
speed = _recordsCopy[_i].mSpeedInbPS;
break;
}
}
return speed < 0 ? INVALID_SPEED : speed;
}
}, {
key: "averageKBps",
get: function get() {
var durationSeconds = (this._now() - this._firstCheckpoint) / 1000;
return this._totalBytes / durationSeconds / 1024;
key: "getRealTimeSpeed",
value: function getRealTimeSpeed() {
return this._realTimeSpeed;
}
}, {
key: "getRTT",
value: function getRTT() {
if (this._netRecords.length < 1) {
return 0;
}
var _recordsRTT = [];
this._netRecords.map(function(item) {
_recordsRTT.push(item.mRTT);
});
_recordsRTT.sort(function(a, b) {
return a - b;
});
var _len = _recordsRTT.length;
if (_len % 2 === 0) {
return (_recordsRTT[_len / 2 - 1] + _recordsRTT[_len / 2]) / 2;
} else {
return _recordsRTT[Math.floor(_len / 2)];
}
}
}, {
key: "netSampling",
value: function netSampling(record) {
this._netRecords.push(record);
this._realTimeSpeed = record.mSpeedInbPS;
if (this._netRecords.length > MaxQueueCapacity) {
this._netRecords.splice(0, 1);
}
}
}]);
return SpeedSampler;
return SpeedSampler2;
}();
var SpeedSampler$1 = SpeedSampler;
export { SpeedSampler$1 as default };
_defineProperty(SpeedSampler, "_netRecords", []);
export { SpeedSampler as default };
export class Task {
constructor(type: any, config: any);
promise: Promise<any>;
promise: any;
alive: boolean;

@@ -12,4 +12,4 @@ _loaderType: any;

_logger: any;
exec(): Promise<any>;
cancel(): Promise<any>;
exec(): any;
cancel(): unknown;
get running(): any;

@@ -16,0 +16,0 @@ }

@@ -1,21 +0,16 @@

import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import { FetchLoader } from './fetch.js';
import { XhrLoader } from './xhr.js';
import { LoaderType } from './types.js';
import { createPublicPromise } from '../utils.js';
import { createClass as _createClass, objectWithoutProperties as _objectWithoutProperties, classCallCheck as _classCallCheck, asyncToGenerator as _asyncToGenerator, regeneratorRuntime as _regeneratorRuntime } from "../_virtual/_rollupPluginBabelHelpers.js";
import { FetchLoader } from "./fetch.js";
import { XhrLoader } from "./xhr.js";
import { LoaderType } from "./types.js";
import { createPublicPromise } from "../utils.js";
import { Logger } from "../logger.js";
var _excluded = ["retry", "retryDelay", "onRetryError", "transformError"];
var testType = localStorage.getItem('type');
var Task = /*#__PURE__*/function () {
function Task(type, config) {
_classCallCheck(this, Task);
var Task = /* @__PURE__ */ function() {
function Task2(type, config) {
_classCallCheck(this, Task2);
this.promise = createPublicPromise();
this.alive = !!config.onProgress;
!config.logger && (config.logger = new Logger("Loader"));
this._loaderType = type;
this._loader = type === LoaderType.FETCH && !testType ? new FetchLoader() : new XhrLoader();
this._loader = type === LoaderType.FETCH ? new FetchLoader() : new XhrLoader();
this._config = config;

@@ -27,19 +22,11 @@ this._retryCount = 0;

}
_createClass(Task, [{
_createClass(Task2, [{
key: "exec",
value: function exec() {
var _this = this;
var _this$_config = this._config,
retry = _this$_config.retry,
retryDelay = _this$_config.retryDelay,
onRetryError = _this$_config.onRetryError,
transformError = _this$_config.transformError,
rest = _objectWithoutProperties(_this$_config, _excluded);
var request = /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
var _this$_config = this._config, retry = _this$_config.retry, retryDelay = _this$_config.retryDelay, onRetryError = _this$_config.onRetryError, transformError = _this$_config.transformError, rest = _objectWithoutProperties(_this$_config, _excluded);
var request = /* @__PURE__ */ function() {
var _ref = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee() {
var response, error;
return _regeneratorRuntime.wrap(function _callee$(_context) {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {

@@ -49,59 +36,47 @@ switch (_context.prev = _context.next) {

_context.prev = 0;
_this._logger.debug('[task request ready to load]', rest.range);
_context.next = 4;
_context.next = 3;
return _this._loader.load(rest);
case 4:
case 3:
response = _context.sent;
_this._loader.running = false;
_this.promise.resolve(response);
_context.next = 27;
_context.next = 28;
break;
case 9:
_context.prev = 9;
case 7:
_context.prev = 7;
_context.t0 = _context["catch"](0);
_this._loader.running = false;
_this._logger.debug('[task request catch err]', _context.t0.errorMessage);
_this._logger.debug("[task request catch err]", _context.t0);
if (!_this._canceled) {
_context.next = 15;
_context.next = 13;
break;
}
return _context.abrupt("return");
case 15:
case 13:
if (!(_context.t0.response && _context.t0.response.status >= 400 && _context.t0.response.status <= 599)) {
_context.next = 16;
break;
}
_this.promise.reject(_context.t0);
return _context.abrupt("return");
case 16:
_context.t0.loaderType = _this._loaderType;
_context.t0.retryCount = _this._retryCount;
error = _context.t0;
if (transformError) {
error = transformError(error) || error;
}
if (onRetryError && _this._retryCount > 0) onRetryError(error, _this._retryCount, retry);
if (onRetryError && _this._retryCount > 0)
onRetryError(error, _this._retryCount, retry);
_this._retryCount++;
if (!(_this._retryCount <= retry)) {
_context.next = 26;
_context.next = 27;
break;
}
clearTimeout(_this._retryTimer);
_this._logger.debug('[task request setTimeout],retry', _this._retryCount, ',retry range,', rest.range);
_this._logger.debug("[task request setTimeout],retry", _this._retryCount, ",retry range,", rest.range);
_this._retryTimer = setTimeout(request, retryDelay);
return _context.abrupt("return");
case 26:
case 27:
_this.promise.reject(error);
case 27:
case 28:
case "end":

@@ -111,12 +86,8 @@ return _context.stop();

}
}, _callee, null, [[0, 9]]);
}, _callee, null, [[0, 7]]);
}));
return function request() {
return function request2() {
return _ref.apply(this, arguments);
};
}();
this._logger.debug('[task request start]', this._config.range);
request();

@@ -127,5 +98,5 @@ return this.promise;

key: "cancel",
value: function () {
var _cancel = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
return _regeneratorRuntime.wrap(function _callee2$(_context2) {
value: function() {
var _cancel = _asyncToGenerator(/* @__PURE__ */ _regeneratorRuntime().mark(function _callee2() {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) {

@@ -138,3 +109,2 @@ switch (_context2.prev = _context2.next) {

return _context2.abrupt("return", this._loader.cancel());
case 4:

@@ -147,7 +117,5 @@ case "end":

}));
function cancel() {
return _cancel.apply(this, arguments);
}
return cancel;

@@ -161,6 +129,4 @@ }()

}]);
return Task;
return Task2;
}();
export { Task };
var LoaderType = {
FETCH: 'fetch',
XHR: 'xhr'
FETCH: "fetch",
XHR: "xhr"
};
var ResponseType = {
ARRAY_BUFFER: 'arraybuffer',
TEXT: 'text',
JSON: 'json'
ARRAY_BUFFER: "arraybuffer",
TEXT: "text",
JSON: "json"
};
export { LoaderType, ResponseType };

@@ -19,3 +19,2 @@ export class XhrLoader {

_startTime: number;
_firstByteTime: number;
_speedSampler: SpeedSampler;

@@ -27,8 +26,17 @@ _loadCompleteResolve: any;

_vid: string;
load(req: any): Promise<any>;
_openSubRange(): void;
_internalOpen(url: any, range: any): void;
_responseType: any;
_credentials: any;
_method: any;
_transformResponse: any;
_firstRtt: any;
_subRangeStartTime: any;
load(req: any): any;
_onTimeout: any;
_request: any;
_startLoad(): void;
_internalOpen(range: any): void;
_running: any;
_onLoad(e: any): void;
_normalizeSpeed(input: any): number;
_onReadyStatechange(e: any): void;
_onLoad(e: any): any;
_normalizeSpeed(input: any): any;
cancel(): any;

@@ -35,0 +43,0 @@ get receiveLen(): number;

@@ -1,113 +0,81 @@

import 'core-js/modules/es.function.name.js';
import 'core-js/modules/es.array.from.js';
import 'core-js/modules/es.string.iterator.js';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.symbol.description.js';
import 'core-js/modules/es.symbol.iterator.js';
import 'core-js/modules/web.dom-collections.iterator.js';
import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.promise.js';
import 'core-js/modules/web.dom-collections.for-each.js';
import 'core-js/modules/es.object.keys.js';
import 'core-js/modules/es.array.iterator.js';
import 'core-js/modules/es.typed-array.uint8-array.js';
import 'core-js/modules/es.typed-array.copy-within.js';
import 'core-js/modules/es.typed-array.every.js';
import 'core-js/modules/es.typed-array.fill.js';
import 'core-js/modules/es.typed-array.filter.js';
import 'core-js/modules/es.typed-array.find.js';
import 'core-js/modules/es.typed-array.find-index.js';
import 'core-js/modules/es.typed-array.for-each.js';
import 'core-js/modules/es.typed-array.includes.js';
import 'core-js/modules/es.typed-array.index-of.js';
import 'core-js/modules/es.typed-array.iterator.js';
import 'core-js/modules/es.typed-array.join.js';
import 'core-js/modules/es.typed-array.last-index-of.js';
import 'core-js/modules/es.typed-array.map.js';
import 'core-js/modules/es.typed-array.reduce.js';
import 'core-js/modules/es.typed-array.reduce-right.js';
import 'core-js/modules/es.typed-array.reverse.js';
import 'core-js/modules/es.typed-array.set.js';
import 'core-js/modules/es.typed-array.slice.js';
import 'core-js/modules/es.typed-array.some.js';
import 'core-js/modules/es.typed-array.sort.js';
import 'core-js/modules/es.typed-array.subarray.js';
import 'core-js/modules/es.typed-array.to-locale-string.js';
import 'core-js/modules/es.typed-array.to-string.js';
import 'core-js/modules/es.regexp.exec.js';
import 'core-js/modules/es.string.split.js';
import 'core-js/modules/es.string.trim.js';
import 'core-js/modules/es.array.join.js';
import 'core-js/modules/es.array.slice.js';
import { NetError } from './error.js';
import { setUrlParams, getRangeValue, createResponse } from './helper.js';
import { ResponseType } from './types.js';
import SpeedSampler from './speed-sampler.js';
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var XhrLoader = /*#__PURE__*/function () {
function XhrLoader() {
_classCallCheck(this, XhrLoader);
import { createClass as _createClass, objectSpread2 as _objectSpread2, createForOfIteratorHelper as _createForOfIteratorHelper, classCallCheck as _classCallCheck, defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js";
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.promise.js";
import "core-js/modules/web.dom-collections.for-each.js";
import "core-js/modules/es.object.keys.js";
import "core-js/modules/es.array.iterator.js";
import "core-js/modules/es.typed-array.uint8-array.js";
import "core-js/modules/es.typed-array.at.js";
import "core-js/modules/es.typed-array.copy-within.js";
import "core-js/modules/es.typed-array.every.js";
import "core-js/modules/es.typed-array.fill.js";
import "core-js/modules/es.typed-array.filter.js";
import "core-js/modules/es.typed-array.find.js";
import "core-js/modules/es.typed-array.find-index.js";
import "core-js/modules/es.typed-array.find-last.js";
import "core-js/modules/es.typed-array.find-last-index.js";
import "core-js/modules/es.typed-array.for-each.js";
import "core-js/modules/es.typed-array.includes.js";
import "core-js/modules/es.typed-array.index-of.js";
import "core-js/modules/es.typed-array.iterator.js";
import "core-js/modules/es.typed-array.join.js";
import "core-js/modules/es.typed-array.last-index-of.js";
import "core-js/modules/es.typed-array.map.js";
import "core-js/modules/es.typed-array.reduce.js";
import "core-js/modules/es.typed-array.reduce-right.js";
import "core-js/modules/es.typed-array.reverse.js";
import "core-js/modules/es.typed-array.set.js";
import "core-js/modules/es.typed-array.slice.js";
import "core-js/modules/es.typed-array.some.js";
import "core-js/modules/es.typed-array.sort.js";
import "core-js/modules/es.typed-array.subarray.js";
import "core-js/modules/es.typed-array.to-locale-string.js";
import "core-js/modules/es.typed-array.to-string.js";
import "core-js/modules/esnext.typed-array.to-reversed.js";
import "core-js/modules/esnext.typed-array.to-sorted.js";
import "core-js/modules/esnext.typed-array.with.js";
import "core-js/modules/es.string.trim.js";
import "core-js/modules/es.array.join.js";
import "core-js/modules/es.array.slice.js";
import { NetError } from "./error.js";
import { setUrlParams, getRangeValue, createResponse } from "./helper.js";
import { ResponseType } from "./types.js";
import SpeedSampler from "./speed-sampler.js";
var XhrLoader = /* @__PURE__ */ function() {
function XhrLoader2() {
_classCallCheck(this, XhrLoader2);
_defineProperty(this, "_xhr", null);
_defineProperty(this, "_aborted", false);
_defineProperty(this, "_timeoutTimer", null);
_defineProperty(this, "_range", null);
_defineProperty(this, "_receivedLength", 0);
_defineProperty(this, "_url", null);
_defineProperty(this, "_onProgress", null);
_defineProperty(this, "_index", -1);
_defineProperty(this, "_headers", null);
_defineProperty(this, "_chunkSizeKBList", [128, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 5120, 6144, 7168, 8192]);
_defineProperty(this, "_currentChunkSizeKB", 384);
_defineProperty(this, "_currentSpeedNormalized", 0);
_defineProperty(this, "_zeroSpeedChunkCount", 0);
_defineProperty(this, "_timeout", null);
_defineProperty(this, "_xhr", null);
_defineProperty(this, "_withCredentials", null);
_defineProperty(this, "_startTime", -1);
_defineProperty(this, "_firstByteTime", -1);
_defineProperty(this, "_speedSampler", new SpeedSampler());
_defineProperty(this, "_loadCompleteResolve", null);
_defineProperty(this, "_loadCompleteReject", null);
_defineProperty(this, "_runing", false);
_defineProperty(this, "_logger", false);
_defineProperty(this, "_vid", '');
_defineProperty(this, "_vid", "");
_defineProperty(this, "_responseType", void 0);
_defineProperty(this, "_credentials", void 0);
_defineProperty(this, "_method", void 0);
_defineProperty(this, "_transformResponse", void 0);
_defineProperty(this, "_firstRtt", void 0);
_defineProperty(this, "_subRangeStartTime", void 0);
}
_createClass(XhrLoader, [{
_createClass(XhrLoader2, [{
key: "load",
value: function load(req) {
var _this = this;
clearTimeout(this._timeoutTimer);

@@ -119,192 +87,102 @@ this._logger = req.logger;

this._headers = req.headers;
this._withCredentials = req.credentials === 'include' || req.credentials === 'same-origin';
this._logger.debug('【xhrLoader task】, range', this._range);
var url = req.url,
params = req.params,
timeout = req.timeout,
responseType = req.responseType,
onTimeout = req.onTimeout,
transformResponse = req.transformResponse,
onProgress = req.onProgress,
method = req.method,
credentials = req.credentials,
body = req.body,
index = req.index,
range = req.range,
request = req.request;
var isTimeout = false;
this._timeout = timeout || null;
this._withCredentials = req.credentials === "include" || req.credentials === "same-origin";
this._timeout = req.timeout || null;
this._runing = true;
this._vid = req.vid || url;
this._url = setUrlParams(url, params);
this._vid = req.vid || req.url;
this._responseType = req.responseType;
this._firstRtt = -1;
this._onTimeout = req.onTimeout;
this._request = req.request;
this._credentials = req.credentials;
this._logger.debug("\u3010xhrLoader task\u3011, range", this._range);
this._url = setUrlParams(req.url, req.params);
var startTime = Date.now();
if (this._onProgress && range.length > 1 && range[1] && range[1] - range[0] > this._currentChunkSizeKB * 1024) {
this._logger.debug('【xhrLoader】, task', this._range, ', need to sub range');
this._openSubRange();
return new Promise(function (resolve, reject) {
_this._loadCompleteResolve = resolve;
_this._loadCompleteReject = reject;
});
} else {
return new Promise(function (resolve, reject) {
var xhr = _this._xhr = new XMLHttpRequest();
xhr.open(method || 'GET', url, true);
xhr.responseType = responseType;
xhr.withCredentials = credentials === 'include' || credentials === 'same-origin';
var rangeValue = getRangeValue(range);
var headers = null;
if (rangeValue) {
headers = _this._headers || {};
headers.Range = rangeValue;
}
if (headers) {
Object.keys(headers).forEach(function (k) {
xhr.setRequestHeader(k, headers[k]);
});
}
if (timeout) {
_this._timeoutTimer = setTimeout(function () {
isTimeout = true;
_this.cancel();
if (onTimeout) {
var error = new NetError(url, request);
error.isTimeout = true;
onTimeout(error);
}
}, timeout);
}
xhr.onerror = function (event) {
return reject(event);
};
xhr.onreadystatechange = function () {
if (xhr.readyState >= 2) {
clearTimeout(_this._timeoutTimer);
var firstByteTime = Date.now();
if (xhr.readyState === 4) {
xhr.onreadystatechange = null;
if (_this._aborted) return;
var status = xhr.status;
var response = {
ok: status >= 200 && status < 300,
status: status,
statusText: xhr.statusText,
url: xhr.responseURL,
headers: _this._getHeaders(xhr),
body: xhr.response
};
if (transformResponse) {
response = transformResponse(response, url) || response;
}
if (!response.ok) {
return reject(new NetError(url, request, response, 'bad network response'));
}
var isArraybuffer = xhr.responseType === ResponseType.ARRAY_BUFFER;
var data = isArraybuffer ? new Uint8Array(xhr.response) : xhr.response;
if (onProgress) {
onProgress(isArraybuffer ? data : undefined, true, {
range: _this._range,
index: _this._index,
startTime: startTime,
endTime: Date.now()
}, response);
}
_this._runing = false;
resolve(createResponse(data, true, response, response.headers['content-length'], response.headers.age, startTime, firstByteTime, index, _this._range, _this._vid));
}
}
};
xhr.send(body);
}).catch(function (error) {
clearTimeout(_this._timeoutTimer);
_this._runing = false;
if (_this._aborted && !isTimeout) return;
error = error instanceof NetError ? error : new NetError(url, request);
error.startTime = startTime;
error.endTime = Date.now();
error.isTimeout = isTimeout;
throw error;
});
}
return new Promise(function(resolve, reject) {
_this._loadCompleteResolve = resolve;
_this._loadCompleteReject = reject;
_this._startLoad();
}).catch(function(error) {
clearTimeout(_this._timeoutTimer);
_this._runing = false;
if (_this._aborted)
return;
error = error instanceof NetError ? error : new NetError(_this._url, _this._request);
error.startTime = startTime;
error.endTime = Date.now();
throw error;
});
}
}, {
key: "_openSubRange",
value: function _openSubRange() {
var chunkSize = this._currentChunkSizeKB * 1024;
var from = this._range[0] + this._receivedLength;
this._logger.debug('[xhr_loader->] ,tast: ', this._range, ',subRangeFrom ', from, ', currentReceivedLength, ', this._receivedLength);
var to = this._range[1];
if (chunkSize < this._range[1] - from) {
to = from + chunkSize;
key: "_startLoad",
value: function _startLoad() {
var range = null;
if (this._range && this._range.length > 1) {
if (this._onProgress) {
this._subRangeStartTime = Date.now();
this._firstRtt = -1;
var chunkSize = this._currentChunkSizeKB * 1024;
var from = this._range[0] + this._receivedLength;
var to = this._range[1];
if (chunkSize < this._range[1] - from) {
to = from + chunkSize;
}
range = [from, to];
this._logger.debug("[xhr_loader->],tast :", this._range, ", SubRange, ", range);
} else {
range = this._range;
this._logger.debug("[xhr_loader->],tast :", this._range, ", allRange, ", range);
}
}
var range = [from, to];
this._logger.debug('[xhr_loader->],tast :', this._range, ', SubRange, ', range);
this._internalOpen(this._url, range);
this._internalOpen(range);
}
}, {
key: "_internalOpen",
value: function _internalOpen(url, range) {
value: function _internalOpen(range) {
var _this2 = this;
this._startTime = Date.now();
var xhr = this._xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
this._timeout && (xhr.timeout = this._timeout);
xhr.withCredentials = this._withCredentials;
xhr.onload = this._onLoad.bind(this);
xhr.onerror = function (event) {
_this2._running = false;
_this2._loadCompleteReject(event);
};
xhr.ontimeout = function (event) {
_this2._running = false;
_this2._loadCompleteReject(event);
};
var rangeValue = getRangeValue(range);
var headers = null;
if (rangeValue) {
headers = this._headers || {};
headers.Range = rangeValue;
try {
this._startTime = Date.now();
var xhr = this._xhr = new XMLHttpRequest();
xhr.open(this._method || "GET", this._url, true);
xhr.responseType = this._responseType;
this._timeout && (xhr.timeout = this._timeout);
xhr.withCredentials = this._credentials;
xhr.onload = this._onLoad.bind(this);
xhr.onreadystatechange = this._onReadyStatechange.bind(this);
xhr.onerror = function(event) {
_this2._running = false;
_this2._loadCompleteReject(event);
};
xhr.ontimeout = function(event) {
_this2.cancel();
if (_this2._onTimeout) {
var error = new NetError(_this2._url, _this2._request);
error.isTimeout = true;
_this2._onTimeout(error);
}
_this2._loadCompleteReject(event);
};
var rangeValue = getRangeValue(range);
var headers = null;
if (rangeValue) {
headers = this._headers || {};
headers.Range = rangeValue;
}
if (headers) {
Object.keys(headers).forEach(function(k) {
xhr.setRequestHeader(k, headers[k]);
});
}
this._logger.debug("[xhr.send->] tast,", this._range, ",load sub range, ", range);
xhr.send();
} catch (e) {
this._loadCompleteReject(e);
}
if (headers) {
Object.keys(headers).forEach(function (k) {
xhr.setRequestHeader(k, headers[k]);
});
}
}, {
key: "_onReadyStatechange",
value: function _onReadyStatechange(e) {
var xhr = e.target;
if (xhr.readyState === 2) {
this._firstRtt < 0 && (this._firstRtt = Date.now());
}
this._logger.debug('[xhr.send->] tast,', this._range, ',load sub range, ', range);
xhr.send();
}

@@ -315,21 +193,16 @@ }, {

var status = e.target.status;
if (status < 200 || status > 299) {
this._loadCompleteReject(new NetError(this._url, null, e.target.response, 'bad response,status:' + status));
return this._loadCompleteReject(new NetError(this._url, null, _objectSpread2(_objectSpread2({}, e.target.response), {}, {
status
}), "bad response,status:" + status));
}
var KBps = this._speedSampler.lastSecondKBps;
if (KBps === 0) {
this._zeroSpeedChunkCount++;
if (this._zeroSpeedChunkCount >= 3) {
// Try get currentKBps after 3 chunks
KBps = this._speedSampler.currentKBps;
}
}
if (KBps !== 0) {
var normalized = this._normalizeSpeed(KBps);
if (this._currentSpeedNormalized !== normalized) {

@@ -340,22 +213,43 @@ this._currentSpeedNormalized = normalized;

}
var chunk = e.target.response;
if (this._firstByteTime) this._firstByteTime = Date.now();
var byteStart = this._range[0] + this._receivedLength;
this._receivedLength += chunk.byteLength;
this._logger.debug('[xhr load done->], tast :', this._range, ', from', byteStart, 'end ', this._range[0] + this._receivedLength, ',dataLen,', chunk.byteLength, ',receivedLength', this._receivedLength);
var reportComplete;
if (this._range.length > 1 && this._range[1] && this._receivedLength < this._range[1] - this._range[0]) {
reportComplete = false;
var data = null;
var done = false;
var byteStart;
if (this._responseType === ResponseType.ARRAY_BUFFER) {
var chunk = new Uint8Array(e.target.response);
byteStart = this._range[0] + this._receivedLength;
if (chunk && chunk.byteLength > 0) {
this._receivedLength += chunk.byteLength;
var costTime = Date.now() - this._subRangeStartTime;
this._speedSampler.addBytes(chunk.byteLength);
SpeedSampler.netSampling({
mTime: costTime,
mBytes: this._receivedLength,
mSpeedInbPS: this._receivedLength * 8 / (costTime / 1e3),
mRTT: this._firstRtt - this._subRangeStartTime
});
}
data = chunk;
if (this._range.length > 1 && this._range[1] && this._receivedLength < this._range[1] - this._range[0]) {
done = false;
} else {
done = true;
}
this._logger.debug("[xhr load done->], tast :", this._range, ", start", byteStart, "end ", this._range[0] + this._receivedLength, ",dataLen,", chunk ? chunk.byteLength : 0, ",receivedLength", this._receivedLength, ",index,", this._index, ", done,", done);
} else {
reportComplete = true;
done = true;
data = e.target.response;
}
var response = {
ok: status >= 200 && status < 300,
status,
statusText: this._xhr.statusText,
url: this._xhr.responseURL,
headers: this._getHeaders(this._xhr),
body: this._xhr.response
};
if (this._transformResponse) {
response = this._transformResponse(response, this._url) || response;
}
if (this._onProgress) {
this._logger.debug('[xhr onDataArrivalCall],tast :', this._range, ',start, ', byteStart, ',end, ', this._range[0] + this._receivedLength, ',index,', this._index);
this._onProgress(chunk, reportComplete, {
this._onProgress(data, done, {
index: this._index,

@@ -366,18 +260,9 @@ vid: this._vid,

endTime: Date.now()
}, null);
}, response);
}
if (!reportComplete) {
this._openSubRange();
if (!done) {
this._startLoad();
} else {
this._runing = false;
var response = {
ok: status >= 200 && status < 300,
status: status,
statusText: this._xhr.statusText,
url: this._xhr.responseURL,
headers: this._getHeaders(this._xhr),
body: this._xhr.response
};
this._loadCompleteResolve && this._loadCompleteResolve(createResponse(null, true, response, response.headers['content-length'], response.headers.age, this._startTime, this._firstByteTime, this._index, this._range, this._vid));
this._loadCompleteResolve && this._loadCompleteResolve(createResponse(this._onProgress ? null : data, done, response, response.headers["content-length"], response.headers.age, this._startTime, -1, this._index, this._range, this._vid));
}

@@ -393,10 +278,7 @@ }

var ubound = last;
if (input < list[0]) {
return list[0];
}
while (lbound <= ubound) {
mid = lbound + Math.floor((ubound - lbound) / 2);
if (mid === last || input >= list[mid] && input < list[mid + 1]) {

@@ -414,6 +296,6 @@ return list[mid];

value: function cancel() {
if (this._aborted) return;
if (this._aborted)
return;
this._aborted = true;
this._runing = false;
if (this._xhr) {

@@ -439,13 +321,10 @@ return this._xhr.abort();

value: function _getHeaders(xhr) {
var headerLines = xhr.getAllResponseHeaders().trim().split('\r\n');
var headerLines = xhr.getAllResponseHeaders().trim().split("\r\n");
var headers = {};
var _iterator = _createForOfIteratorHelper(headerLines),
_step;
var _iterator = _createForOfIteratorHelper(headerLines), _step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
for (_iterator.s(); !(_step = _iterator.n()).done; ) {
var header = _step.value;
var parts = header.split(': ');
headers[parts[0].toLowerCase()] = parts.slice(1).join(': ');
var parts = header.split(": ");
headers[parts[0].toLowerCase()] = parts.slice(1).join(": ");
}

@@ -457,3 +336,2 @@ } catch (err) {

}
return headers;

@@ -464,9 +342,7 @@ }

value: function isSupported() {
return typeof XMLHttpRequest !== 'undefined';
return typeof XMLHttpRequest !== "undefined";
}
}]);
return XhrLoader;
return XhrLoader2;
}();
export { XhrLoader };

@@ -1,23 +0,17 @@

import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import 'core-js/modules/es.array.slice.js';
var BandwidthService = /*#__PURE__*/function () {
function BandwidthService() {
_classCallCheck(this, BandwidthService);
import { createClass as _createClass, classCallCheck as _classCallCheck, defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js";
import "core-js/modules/es.array.push.js";
import "core-js/modules/es.array.slice.js";
import "core-js/modules/es.object.to-string.js";
var BandwidthService = /* @__PURE__ */ function() {
function BandwidthService2() {
_classCallCheck(this, BandwidthService2);
_defineProperty(this, "_chunkSpeeds", []);
_defineProperty(this, "_speeds", []);
}
_createClass(BandwidthService, [{
_createClass(BandwidthService2, [{
key: "addRecord",
value: // bps
function addRecord(totalByte, ms) {
if (!totalByte || !ms) return;
this._speeds.push(8000 * totalByte / ms);
value: function addRecord(totalByte, ms) {
if (!totalByte || !ms)
return;
this._speeds.push(8e3 * totalByte / ms);
this._speeds = this._speeds.slice(-3);

@@ -28,7 +22,6 @@ }

value: function addChunkRecord(totalByte, ms) {
if (!totalByte || !ms) return;
this._chunkSpeeds.push(8000 * totalByte / ms);
this._chunkSpeeds = this._chunkSpeeds.slice(-10);
if (!totalByte || !ms)
return;
this._chunkSpeeds.push(8e3 * totalByte / ms);
this._chunkSpeeds = this._chunkSpeeds.slice(-100);
}

@@ -38,11 +31,10 @@ }, {

value: function getAvgSpeed() {
if (!this._chunkSpeeds.length && !this._speeds.length) return 0;
if (!this._chunkSpeeds.length && !this._speeds.length)
return 0;
if (this._speeds.length) {
return this._speeds.reduce(function (a, c) {
return this._speeds.reduce(function(a, c) {
return a += c;
}) / this._speeds.length;
}
return this._chunkSpeeds.reduce(function (a, c) {
return this._chunkSpeeds.reduce(function(a, c) {
return a += c;

@@ -54,8 +46,7 @@ }) / this._chunkSpeeds.length;

value: function getLatestSpeed() {
if (!this._chunkSpeeds.length && !this._speeds.length) return 0;
if (!this._chunkSpeeds.length && !this._speeds.length)
return 0;
if (this._speeds.length) {
return this._speeds[this._speeds.length - 1];
}
return this._chunkSpeeds[this._chunkSpeeds.length - 1];

@@ -70,6 +61,4 @@ }

}]);
return BandwidthService;
return BandwidthService2;
}();
export { BandwidthService };

@@ -1,27 +0,22 @@

import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import { Buffer } from '../buffer.js';
var GapService = /*#__PURE__*/function () {
function GapService() {
_classCallCheck(this, GapService);
import { createClass as _createClass, classCallCheck as _classCallCheck, defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js";
import { Buffer } from "../buffer.js";
var GapService = /* @__PURE__ */ function() {
function GapService2() {
_classCallCheck(this, GapService2);
_defineProperty(this, "_prevCurrentTime", 0);
}
_createClass(GapService, [{
_createClass(GapService2, [{
key: "do",
value: function _do(media) {
var maxJumpDistance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
var isLive = arguments.length > 2 ? arguments[2] : undefined;
var seekThreshold = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
if (!media) return;
var maxJumpDistance = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 3;
var isLive = arguments.length > 2 ? arguments[2] : void 0;
var seekThreshold = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 1;
if (!media)
return;
var currentTime = media.currentTime;
var jumpTo = 0;
if (this._prevCurrentTime === currentTime) {
var info = Buffer.info(Buffer.get(media), currentTime);
if (!info.buffers.length) return;
if (!info.buffers.length)
return;
if (isLive && info.nextStart || info.nextStart && info.nextStart - currentTime < maxJumpDistance) {

@@ -33,5 +28,3 @@ jumpTo = info.nextStart + 0.1;

}
this._prevCurrentTime = currentTime;
if (jumpTo && currentTime !== jumpTo) {

@@ -42,6 +35,4 @@ media.currentTime = jumpTo;

}]);
return GapService;
return GapService2;
}();
export { GapService };
export class SeiService {
constructor(emitter: any);
_seiSet: Set<any>;
_seiSet: any;
emitter: any;

@@ -5,0 +5,0 @@ throw(currentTime: any): void;

@@ -1,37 +0,31 @@

import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import 'core-js/modules/es.array.iterator.js';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.set.js';
import 'core-js/modules/es.string.iterator.js';
import 'core-js/modules/web.dom-collections.iterator.js';
import 'core-js/modules/web.dom-collections.for-each.js';
import { EVENT } from '../event.js';
var SeiService = /*#__PURE__*/function () {
function SeiService(emitter) {
import { createClass as _createClass, classCallCheck as _classCallCheck, defineProperty as _defineProperty } from "../_virtual/_rollupPluginBabelHelpers.js";
import "core-js/modules/es.array.iterator.js";
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.set.js";
import "core-js/modules/es.string.iterator.js";
import "core-js/modules/web.dom-collections.iterator.js";
import "core-js/modules/web.dom-collections.for-each.js";
import "core-js/modules/es.array.push.js";
import { EVENT } from "../event.js";
var SeiService = /* @__PURE__ */ function() {
function SeiService2(emitter) {
var _this = this;
_classCallCheck(this, SeiService);
_defineProperty(this, "_seiSet", new Set());
_classCallCheck(this, SeiService2);
_defineProperty(this, "_seiSet", /* @__PURE__ */ new Set());
this.emitter = emitter;
emitter.on(EVENT.SEI, function (sei) {
if (sei) _this._seiSet.add(sei);
emitter.on(EVENT.SEI, function(sei) {
if (sei)
_this._seiSet.add(sei);
});
}
_createClass(SeiService, [{
_createClass(SeiService2, [{
key: "throw",
value: function _throw(currentTime) {
var _this2 = this;
if (currentTime == null || !this._seiSet.size) return;
if (currentTime === null || currentTime === void 0 || !this._seiSet.size)
return;
var min = currentTime - 0.2;
var max = currentTime + 0.2;
var toThrow = [];
this._seiSet.forEach(function (sei) {
this._seiSet.forEach(function(sei) {
if (sei.time >= min && sei.time <= max) {

@@ -41,6 +35,4 @@ toThrow.push(sei);

});
toThrow.forEach(function (sei) {
toThrow.forEach(function(sei) {
_this2._seiSet.delete(sei);
_this2.emitter.emit(EVENT.SEI_IN_TIME, sei);

@@ -55,6 +47,4 @@ });

}]);
return SeiService;
return SeiService2;
}();
export { SeiService };

@@ -11,3 +11,7 @@ export function isMediaPlaying(media: any): boolean;

};
export function concatUint8Array(...arr: any[]): Uint8Array;
export function softDecodeProbe(): any;
/**
* @param {Array.<Uint8Array>} arr
* @returns
*/
export function concatUint8Array(...arr: Array<Uint8Array>): any;
export function sleep(t?: number): any;

@@ -1,30 +0,36 @@

import 'core-js/modules/es.array.filter.js';
import 'core-js/modules/es.array.iterator.js';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.typed-array.uint8-array.js';
import 'core-js/modules/es.typed-array.copy-within.js';
import 'core-js/modules/es.typed-array.every.js';
import 'core-js/modules/es.typed-array.fill.js';
import 'core-js/modules/es.typed-array.filter.js';
import 'core-js/modules/es.typed-array.find.js';
import 'core-js/modules/es.typed-array.find-index.js';
import 'core-js/modules/es.typed-array.for-each.js';
import 'core-js/modules/es.typed-array.includes.js';
import 'core-js/modules/es.typed-array.index-of.js';
import 'core-js/modules/es.typed-array.iterator.js';
import 'core-js/modules/es.typed-array.join.js';
import 'core-js/modules/es.typed-array.last-index-of.js';
import 'core-js/modules/es.typed-array.map.js';
import 'core-js/modules/es.typed-array.reduce.js';
import 'core-js/modules/es.typed-array.reduce-right.js';
import 'core-js/modules/es.typed-array.reverse.js';
import 'core-js/modules/es.typed-array.set.js';
import 'core-js/modules/es.typed-array.slice.js';
import 'core-js/modules/es.typed-array.some.js';
import 'core-js/modules/es.typed-array.sort.js';
import 'core-js/modules/es.typed-array.subarray.js';
import 'core-js/modules/es.typed-array.to-locale-string.js';
import 'core-js/modules/es.typed-array.to-string.js';
import 'core-js/modules/web.dom-collections.for-each.js';
import "core-js/modules/es.array.filter.js";
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.array.iterator.js";
import "core-js/modules/es.typed-array.uint8-array.js";
import "core-js/modules/es.typed-array.at.js";
import "core-js/modules/es.typed-array.copy-within.js";
import "core-js/modules/es.typed-array.every.js";
import "core-js/modules/es.typed-array.fill.js";
import "core-js/modules/es.typed-array.filter.js";
import "core-js/modules/es.typed-array.find.js";
import "core-js/modules/es.typed-array.find-index.js";
import "core-js/modules/es.typed-array.find-last.js";
import "core-js/modules/es.typed-array.find-last-index.js";
import "core-js/modules/es.typed-array.for-each.js";
import "core-js/modules/es.typed-array.includes.js";
import "core-js/modules/es.typed-array.index-of.js";
import "core-js/modules/es.typed-array.iterator.js";
import "core-js/modules/es.typed-array.join.js";
import "core-js/modules/es.typed-array.last-index-of.js";
import "core-js/modules/es.typed-array.map.js";
import "core-js/modules/es.typed-array.reduce.js";
import "core-js/modules/es.typed-array.reduce-right.js";
import "core-js/modules/es.typed-array.reverse.js";
import "core-js/modules/es.typed-array.set.js";
import "core-js/modules/es.typed-array.slice.js";
import "core-js/modules/es.typed-array.some.js";
import "core-js/modules/es.typed-array.sort.js";
import "core-js/modules/es.typed-array.subarray.js";
import "core-js/modules/es.typed-array.to-locale-string.js";
import "core-js/modules/es.typed-array.to-string.js";
import "core-js/modules/esnext.typed-array.to-reversed.js";
import "core-js/modules/esnext.typed-array.to-sorted.js";
import "core-js/modules/esnext.typed-array.with.js";
import "core-js/modules/web.dom-collections.for-each.js";
import "core-js/modules/es.promise.js";
function isMediaPlaying(media) {

@@ -34,5 +40,5 @@ return media && !media.paused && !media.ended && media.playbackRate !== 0 && media.readyState !== 0;

function getVideoPlaybackQuality(video) {
if (!video) return {};
if (typeof video.getVideoPlaybackQuality === 'function') {
if (!video)
return {};
if (typeof video.getVideoPlaybackQuality === "function") {
var info = video.getVideoPlaybackQuality();

@@ -45,3 +51,2 @@ return {

}
return {

@@ -57,9 +62,10 @@ droppedVideoFrames: video.webkitDroppedFrameCount,

}
arr = arr.filter(Boolean);
var data = new Uint8Array(arr.reduce(function (p, c) {
if (arr.length < 2)
return arr[0];
var data = new Uint8Array(arr.reduce(function(p, c) {
return p + c.byteLength;
}, 0));
var prevLen = 0;
arr.forEach(function (d) {
arr.forEach(function(d) {
data.set(d, prevLen);

@@ -70,41 +76,8 @@ prevLen += d.byteLength;

}
function softDecodeProbe() {
var webAudioEnable = false;
var webglEnable = false;
try {
var AudioContext = window.AudioContext || window.webkitAudioContext;
var ctx = new AudioContext();
ctx.close();
ctx = null;
webAudioEnable = true;
} catch (e) {}
try {
var cvs = document.createElement('canvas');
var validContextNames = ['webgl', 'experimental-webgl', 'moz-webgl', 'webkit-3d'];
for (var i = 0; i < validContextNames.length; i++) {
var glCtx = cvs.getContext(validContextNames[i]);
if (glCtx) {
glCtx = null;
cvs = null;
webglEnable = true;
break;
}
}
} catch (e) {}
var WebComponentSupported = 'customElements' in window && window.customElements.define;
var isComponentSupport;
if (WebComponentSupported) {
var Video = window.customElements.get('live-video');
isComponentSupport = Video && Video.isSupported();
}
return webAudioEnable && webglEnable && isComponentSupport;
function sleep() {
var t = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 0;
return new Promise(function(resolve) {
return setTimeout(resolve, t);
});
}
export { concatUint8Array, getVideoPlaybackQuality, isMediaPlaying, softDecodeProbe };
export { concatUint8Array, getVideoPlaybackQuality, isMediaPlaying, sleep };

@@ -1,1 +0,1 @@

export function createPublicPromise(): Promise<any>;
export function createPublicPromise(): any;

@@ -1,7 +0,6 @@

import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.promise.js';
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.promise.js";
function createPublicPromise() {
var res, rej;
var promise = new Promise(function (resolve, reject) {
var promise = new Promise(function(resolve, reject) {
res = resolve;

@@ -11,16 +10,12 @@ rej = reject;

promise.used = false;
promise.resolve = function () {
promise.resolve = function() {
promise.used = true;
return res.apply(void 0, arguments);
};
promise.reject = function () {
promise.reject = function() {
promise.used = true;
return rej.apply(void 0, arguments);
};
return promise;
}
export { createPublicPromise };
{
"name": "xgplayer-streaming-shared",
"version": "3.0.0-alpha.5",
"version": "3.0.0-alpha.19",
"main": "dist/index.min.js",

@@ -8,3 +8,5 @@ "module": "es/index.js",

"sideEffects": false,
"umdName": "XGPlayerStreamingShared",
"libd": {
"umdName": "XGPlayerStreamingShared"
},
"files": [

@@ -16,3 +18,4 @@ "dist",

"registry": "https://registry.npmjs.org/",
"access": "public"
"access": "public",
"tag": "alpha"
},

@@ -22,7 +25,3 @@ "license": "MIT",

"dist"
],
"dependencies": {
"core-js": "3",
"@babel/runtime": "^7.15.3"
}
]
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc