-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
99 lines (93 loc) · 2.79 KB
/
index.js
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
"use strict";
// Our C++ Addon
const addon = require('bindings')('node-quirc.node');
function decodeEncoded(img, callback) {
return addon.decodeEncoded(img, callback);
}
function isImageDimension(number) {
return (
typeof number === 'number' &&
number > 0 &&
(number | 0) === number &&
!isNaN(number)
);
}
function decodeRaw(img, callback) {
if (!isImageDimension(img.width)) {
throw new Error(
`unexpected width value for image: ${img.width}`
)
}
if (!isImageDimension(img.height)) {
throw new Error(
`unexpected height value for image: ${img.height}`
)
}
const channels = img.data.length / img.width / img.height;
if (channels !== 1 && channels !== 3 && channels !== 4) {
throw new Error(
`unsupported ${channels}-channel image, expected 1, 3, or 4`
);
}
return addon.decodeRaw(img.data, img.width, img.height, callback);
}
function maybePromisify(fn) {
return (...args) => {
if (args.length < fn.length) {
return new Promise((resolve, reject) => {
fn(...args, (err, results) => {
if (err) {
return reject(err);
} else {
return resolve(results);
}
});
});
} else {
return fn(...args);
}
};
}
// public API
module.exports = {
decode: maybePromisify((img, callback) => {
if (Buffer.isBuffer(img)) {
return decodeEncoded(img, callback);
} else if (img && typeof img === "object") {
return decodeRaw(img, callback);
} else {
throw new TypeError("img must be a Buffer or ImageData");
}
}),
constants: {
// QR-code versions.
VERSION_MIN: 1,
VERSION_MAX: 40,
// QR-code ECC levels.
ECC_LEVEL_M: "M",
ECC_LEVEL_L: "L",
ECC_LEVEL_H: "H",
ECC_LEVEL_Q: "Q",
// QR-code encoding modes.
MODE_NUMERIC: "NUMERIC",
MODE_ALNUM: "ALNUM",
MODE_BYTE: "BYTE",
MODE_KANJI: "KANJI",
// Common character encodings
ECI_ISO_8859_1: "ISO_8859_1",
ECI_IBM437: "IBM437",
ECI_ISO_8859_2: "ISO_8859_2",
ECI_ISO_8859_3: "ISO_8859_3",
ECI_ISO_8859_4: "ISO_8859_4",
ECI_ISO_8859_5: "ISO_8859_5",
ECI_ISO_8859_6: "ISO_8859_6",
ECI_ISO_8859_7: "ISO_8859_7",
ECI_ISO_8859_8: "ISO_8859_8",
ECI_ISO_8859_9: "ISO_8859_9",
ECI_WINDOWS_874: "WINDOWS_874",
ECI_ISO_8859_13: "ISO_8859_13",
ECI_ISO_8859_15: "ISO_8859_15",
ECI_SHIFT_JIS: "SHIFT_JIS",
ECI_UTF_8: "UTF_8",
},
};