UNPKG

2.31 kBJavaScriptView Raw
1/**
2 * OS detection.
3 *
4 * @copyright Realeyes OU. All rights reserved.
5 */
6
7
8import getFirstMatch from './utils/getFirstMatch';
9
10
11/**
12 * Enum for OSs that we can detect.
13 *
14 * @enum {string}
15 */
16const names = {
17 WINDOWS_PHONE: 'windowsphone',
18 IOS: 'ios',
19 ANDROID: 'android',
20 MAC_OS: 'macos',
21 WINDOWS: 'windows',
22 LINUX: 'linux',
23 OPENBSD: 'openbsd',
24 UNKNOWN: 'unknown',
25};
26
27
28/**
29 * List of tests.
30 */
31const tests = [
32 {
33 osName: names.WINDOWS_PHONE,
34 testRegex: /windows phone/i,
35 getVersion(ua) {
36 return getFirstMatch(ua, /windows phone (?:os)?\s?(\d+(\.\d+)*)/i);
37 },
38 },
39 {
40 osName: names.IOS,
41 testRegex: /(ipod|iphone|ipad)/i,
42 getVersion(ua) {
43 return getFirstMatch(ua, /os (\d+([_\s]\d+)*) like mac os x/i).split('_').join('.');
44 },
45 },
46 {
47 osName: names.ANDROID,
48 testRegex: /^((?!.*like android).*android)|silk/i,
49 getVersion(ua) {
50 return getFirstMatch(ua, /android[ /-](\d+(\.\d+)*)/i);
51 },
52 },
53 {
54 osName: names.MAC_OS,
55 testRegex: /macintosh/i,
56 getVersion(ua) {
57 return ua.replace(/.*?OS X (.*?)(\)|;).*/, '$1').split('_').join('.');
58 },
59 },
60 {
61 osName: names.WINDOWS,
62 testRegex: /windows/i,
63 getVersion(ua) {
64 return ua.replace(/.*?Windows (.*?)(\)|;).*/, '$1');
65 },
66 },
67 {
68 osName: names.LINUX,
69 testRegex: /linux/i,
70 getVersion() { return null; },
71 },
72 {
73 osName: names.OPENBSD,
74 testRegex: /OpenBSD/i,
75 getVersion() { return null; },
76 },
77];
78
79
80export default {
81 names,
82
83 /**
84 * Returns the OS name and version.
85 *
86 * @param {string} ua User Agent string
87 * @return {{
88 * name: string,
89 * version: ?string
90 * }}
91 */
92 detect(ua) {
93 for (let i = 0; i < tests.length; i++) {
94 if (tests[i].testRegex.test(ua)) {
95 return {
96 name: tests[i].osName,
97 version: tests[i].getVersion(ua) || getFirstMatch(ua, /version\/(\d+\.\d+)/i) || null,
98 };
99 }
100 }
101
102 return {
103 name: names.UNKNOWN,
104 version: null,
105 };
106 },
107};