-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathindex.js
More file actions
116 lines (89 loc) · 2.55 KB
/
Copy pathindex.js
File metadata and controls
116 lines (89 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
'use strict';
const os = require('node:os');
const { normalizeSerial, normalizeSerialList } = require('./lib/utils');
const providers = {
linux: require('./lib/providers/linux'),
win32: require('./lib/providers/windows'),
darwin: require('./lib/providers/macos'),
sunos: require('./lib/providers/macos')
};
function withOptionalCallback(promise, callback) {
if (typeof callback !== 'function') {
return promise;
}
promise.then(
(value) => callback(null, value),
(error) => callback(error, null)
);
return undefined;
}
function getProvider(platform) {
return providers[platform] || providers.linux;
}
function createApi(getSerials) {
async function allAsync() {
const serials = await getSerials();
const normalized = normalizeSerialList(serials);
if (!normalized.length) {
throw new Error('No disk serial found');
}
return normalized;
}
const api = {
all(callback) {
return withOptionalCallback(allAsync(), callback);
},
first(callback) {
return withOptionalCallback(this.one(0), callback);
},
one(index, callback) {
if (typeof index === 'function') {
return this.all(index);
}
const promise = (async () => {
if (!Number.isInteger(index) || index < 0) {
throw new TypeError('Index must be a non-negative integer');
}
const serials = await allAsync();
const serial = serials[index];
if (!serial) {
throw new RangeError('Disk index out of range');
}
return serial;
})();
return withOptionalCallback(promise, callback);
},
check(serial, callback) {
const promise = (async () => {
if (typeof serial !== 'string') {
throw new TypeError('Serial must be a string');
}
const normalizedInput = normalizeSerial(serial);
if (!normalizedInput) {
return false;
}
const serials = await allAsync();
return serials.includes(normalizedInput);
})();
return withOptionalCallback(promise, callback);
},
isfirst(serial, callback) {
const promise = (async () => {
const first = await this.first();
return normalizeSerial(serial) === first;
})();
return withOptionalCallback(promise, callback);
}
};
return api;
}
const api = createApi(async () => {
const provider = getProvider(os.platform());
return provider.getSerials();
});
api._createApi = createApi;
api._utils = {
normalizeSerial,
normalizeSerialList
};
module.exports = api;