@cainiaofe/cn-utils
Version:
菜鸟前端基础工具库
100 lines (99 loc) • 2.92 kB
JavaScript
import osParsersList from './osList';
import array from "../../common/array";
/**
* The main class that arranges the whole parsing process.
*/
var Parser = /** @class */ (function () {
function Parser(UA) {
if (!UA) {
throw new Error("UserAgent parameter can't be empty");
}
this._ua = UA;
/**
* @property {Object} os
* @property {String|undefined} [os.name] OS name, like `"Windows"` or `"macOS"`
* @property {String|undefined} [os.version] OS version, like `"NT 5.1"` or `"10.11.1"`
* @property {String|undefined} [os.versionName] OS name, like `"XP"` or `"High Sierra"`
*/
// @ts-ignore
this.parsedResult = {};
this.parseOS();
}
/**
* Get UserAgent string of current Parser instance
* @return {String} User-Agent String of the current <Parser> object
*
* @public
*/
Parser.prototype.getUA = function () {
return this._ua;
};
/**
* Test a UA string for a regexp
* @param {RegExp} regex
* @return {Boolean}
*/
Parser.prototype.test = function (regex) {
return regex.test(this._ua);
};
/**
* Get OS
* @return {Object}
*
* @example
* this.getOS();
* {
* name: 'macOS',
* version: '10.11.12'
* }
*/
Parser.prototype.getOS = function () {
if (this.parsedResult.os) {
return this.parsedResult.os;
}
return this.parseOS();
};
/**
* Parse OS and save it to this.parsedResult.os
* @return {*|{}}
*/
Parser.prototype.parseOS = function () {
var _this = this;
// @ts-ignore
this.parsedResult.os = {};
var os = array.find(osParsersList, function (_os) {
if (typeof _os.test === 'function') {
return _os.test(_this);
}
if (_os.test instanceof Array) {
return _os.test.some(function (condition) { return _this.test(condition); });
}
throw new Error("Browser's test function is not valid");
});
if (os) {
this.parsedResult.os = os.describe(this.getUA());
}
return this.parsedResult.os;
};
/**
* Get OS name
* @param {Boolean} [toLowerCase] return lower-cased value
* @return {String} name of the OS — macOS, Windows, Linux, etc.
*/
Parser.prototype.getOSName = function (toLowerCase) {
var name = this.getOS().name;
if (toLowerCase) {
return String(name).toLowerCase() || '';
}
return name || '';
};
/**
* Get OS version
* @return {String} full version with dots ('10.11.12', '5.6', etc)
*/
Parser.prototype.getOSVersion = function () {
return this.getOS().version;
};
return Parser;
}());
export default Parser;